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: duplicate resolution, conflict journal, and Series→Universe hierarchy (#489)

[._.]/ Adam Eivy33a2010c707c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f369da1b34..8a6cde8bd2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,11 +9,18 @@ TBD
## Added
- **Writers Room Guide.** A new deep-linkable documentation page at `/writers-room/guide` (reachable via a "Guide" link in the Writers Room header and from `⌘K` / voice). It documents the literary length ladder — Microfiction, Flash Fiction, Standard Short Story, Novelette, plus Novella/Novel for context — with both word and character bands, a page-based book-length estimate table (200/300 pages), and craft principles grouped by structure, character, prose, and revision. The length targets and principles live in a single canonical data module (`client/src/lib/writingGuide.js`, with a `classifyByWordCount()` helper) so forthcoming editor analyses — including the planned **emotional-roadmap evaluator** that charts the reader's emotional journey beat by beat — read the same source the docs render from.
+- **Sync hygiene: duplicate resolution + a non-blocking edit-conflict journal.** Because two PortOS installs (or two machines federated as peers, or two copies of a `data/` folder synced through Google Drive/Dropbox) can each independently create a Universe or Series with the same name — and records are keyed by random id, not name — sync used to leave silent duplicates (e.g. two "Clandestiny" universes) and silently discard the loser whenever both sides edited the same record. Two new tabs under **Sharing** fix this:
+ - **Duplicates** — finds same-named-but-different-id Universes (and Series, scoped within their universe) and offers to **Merge** (smart field-union: canon, categories, variations, influences, and render history are unioned; genuinely-conflicting fields are resolved field-by-field via a side-by-side diff; child series/issues and media collections are re-pointed to the survivor; the loser is tombstoned and propagated to peers) or **Rename** one to keep both.
+ - **Conflicts** — when a cross-install last-write-wins merge would overwrite a record both sides edited, the losing version is now archived to a local conflict journal instead of vanishing. Review the diff and **Restore mine**, **Merge** specific fields back, or **Discard**. Convergence is never blocked — peers still agree on the LWW winner; no edit is lost.
+ Both surfaces are deep-linkable (`/sharing/duplicates`, `/sharing/conflicts`) and reachable from ⌘K / voice.
+- **Series now belong to exactly one Universe (enforced).** Creating a series requires a universe, a linked series can no longer be un-linked (only moved to another universe), and deleting a universe that still has live series is blocked until they're moved or deleted. A migration adopts any legacy orphan series into a synthesized universe so existing installs satisfy the rule.
- **Use a different Chrome variant for the PortOS-managed browser.** PortOS now reads a `chromePath` (and `macAppBundle` on macOS) from `data/browser-config.json`, so you can point it at Chrome Canary, Chromium, Brave, Edge, or any Chromium-based browser — separating the automation surface from your daily-driver Chrome. Setup (`./setup.sh` / `setup.ps1`) and update (`./update.sh` / `./update.ps1`) now offer to install and configure Chrome Canary automatically: on macOS via `brew install --cask google-chrome@canary`, on Windows via `winget install Google.Chrome.Canary`. The prompt is interactive-only (CI / non-TTY runs skip silently), idempotent (won't re-prompt once configured), and supports `PORTOS_USE_CANARY=1` for headless opt-in. The Browser page's Config panel exposes both fields for after-the-fact edits.
## Changed
+- **Importer source ceiling raised from 200K → 5M characters.** The Create › Importer page previously rejected pasted sources over 200,000 characters — far short of a real novel (a 250-page book runs ~400K chars; long novels reach several million). That cap was an over-conservative "v1" product limit, not a fundamental constraint: the schema layer already allowed 5MB, and modern large-context providers (Claude, Gemini) ingest a whole novel in a single call. The importer now matches the 5MB abuse-guard ceiling, so the only remaining limit is dynamic — the active provider's context window (the entire corpus still goes into one extraction call until chunked extraction lands). Sources that fit the ceiling but overflow the chosen model's window surface a provider error; pick a large-context provider or trim in the meantime. The pipeline's per-issue canon-extract truncation budget was decoupled (stays 200K) since a single issue's stage output is already hard-bounded at 400K and operates at a fundamentally smaller scale than whole-book ingest.
+
- **Dashboard Quick Image widget** — now exposes **resolution** and **negative prompt** options (collapsible) alongside the prompt, and renders the result inline: async backends stream the diffusion loading animation (spinner / step counter / latent preview) and resolve to the final image, mirroring the Universe asset slots via the shared `MediaJobThumb`. Sync (external) backends show the completed image directly. The "Edit" hand-off now carries the chosen size + negative prompt into the full Image Gen page.
- **Universes table** — each row now shows a 48×48 thumbnail of the latest image from the universe's auto-managed media collection (the `Universe: <name>` bucket linked by `collection.universeId`). Rows without media fall back to a Globe placeholder; a broken file ref also degrades to the placeholder via `<img onError>`. Applies to both the desktop table and the mobile card layout.
diff --git a/PLAN.md b/PLAN.md
index f1504b88ab..e4db49e3da 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -114,6 +114,32 @@ Surfaced during code review of the federated-media-collection-sync feature and c
- [ ] [voice-vision-model-settings-ui] **Wire a `cfg.llm.visionModel` field into the Voice settings UI.** The v2.9.0 release review decoupled `ui_describe_visually`'s vision model from the voice text model — `describeScreenshot` (`server/services/voice/pipeline.js`) now reads an optional `cfg.llm.visionModel` and otherwise falls back to the provider's vision-capable `defaultModel` (so a pinned text-only voice model no longer breaks vision). But nothing in the Voice settings UI sets `visionModel` yet, so it can only be configured by hand-editing settings (the read path is forward-compatible, mirroring `cfg.location` for `weather_now`). Add a Voice-settings field + a Zod slice so a user can pin a specific vision model. Small.
- [ ] [ltx2-utils-constants-qualified] **LTX2 negative-prompt patch imports a generic top-level module.** `scripts/generate_ltx2.py:92` tries `("utils", "constants")` to override `DEFAULT_NEGATIVE_PROMPT`; `utils` is a very generic top-level package name in a shared venv and could be shadowed (the `hasattr(...)` guard makes a wrong-module *write* improbable, so this is defense-in-depth only). If the real module is namespaced under the ltx package, prefer the fully-qualified import path. Surfaced during v2.9.0 release review (claude, NIT). Deferred: guarded; cosmetic robustness.
+### Duplicate resolution + conflict journal — deferred follow-ups (2026-05-25)
+
+Surfaced while building the sync-hygiene feature (duplicate detection/merge, non-blocking conflict journal, Series→Universe hierarchy). Consciously scoped out of v1.
+
+- [ ] [conflict-journal-media-collections] **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ (items get unioned, so they're not actually "lost"). Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.
+- [ ] [conflict-journal-issues] **Issue-level conflict journaling.** The share-bucket importer hook (`server/services/sharing/importer.js` `applyAutoMerge`→`mergeOne`) is gated to `universe`/`series`; child issues ride LWW silently. Extend the journal to issues (needs the issue merge path to thread a `source` + call `maybeJournalBeforeOverwrite`).
+- [ ] [conflict-journal-deep-diff] **`diffSummary` is top-level shallow only.** `conflictJournal.diffSummary` compares top-level fields via canonicalStringify, so the UI shows "categories differ" rather than which variation/canon entry changed. Add per-field deep diffing for richer InlineDiff rendering in the Conflicts tab.
+- [ ] [series-merge-season-rehoming] **Series merge re-homes issues un-grouped.** `recordMerge.mergeSeries` re-points the loser series' issues to the survivor via `issues.reassignIssuesToSeries`, which sets `seasonId: null` (seasons are series-scoped, so the loser's season ids don't exist on the survivor; seasons are unioned by number separately). The moved issues land un-grouped and the user must re-assign them to a survivor season. A smarter merge could map loser seasons → survivor seasons by number and preserve issue→season grouping.
+- [ ] [conflict-restore-additive] **"Restore mine" is additive for keyed fields, not a faithful overwrite.** `conflictJournalResolver.resolveConflict` restore-all applies the snapshot via `updateUniverse(id, () => patch)`, which merges `categories` per-key — so a category the user deleted *after* the conflict is resurrected on restore. Acceptable for v1 (resurrect-not-lose), but the UI says "restore your whole version." Consider a true-replace path for restore-all. Surfaced in /code-review (medium).
+- [ ] [merge-cascade-no-rollback] **`recordMerge.mergeUniverses`/`mergeSeries` cascade has no rollback.** Union-write survivor → re-point each child → tombstone loser runs as separate awaits; a mid-loop throw (e.g. a child concurrently tombstoned → NOT_FOUND) leaves the survivor merged but the loser un-tombstoned, and a retry trips `ERR_HAS_LIVE_SERIES` on the remaining children. Single-user/low-concurrency so low-probability, but a half-merge has no cleanup. Consider catching per-child and reporting, or finishing the loser tombstone best-effort. Surfaced in /code-review (medium).
+- [ ] [merge-orphan-series-via-api] **`mergeSeries` permits merging two orphan series via the API.** The same-universe guard `(survivor.universeId||null) !== (loser.universeId||null)` is `null !== null` = false for two orphans, so a direct POST `/api/pipeline/series/merge` with two orphan ids proceeds — contradicting `duplicateDetection`, which segregates orphans as un-mergeable in the UI. Reject when both `universeId` are empty (or require a universe). Surfaced in /code-review (low-medium).
+- [ ] [conflict-source-attribution] **Conflict-journal `source` is `via:'sync'/peerId:null` on the peer-push path.** `applyIncomingPush` calls `mergeUniversesFromSync`/`mergeSeriesFromSync` without the `{ source }` arg even though `sourceInstanceId` is in scope, so the Conflicts tab can't attribute which peer collided. Thread `{ via:'peer-push', peerId: sourceInstanceId }` from `applyIncomingPush`. Surfaced in /code-review (low, attribution only).
+- [ ] [dup-detect-collection-count-undercount] **`duplicateDetection.collectionItemsByUniverse` last-wins instead of summing.** Uses `.set(universeId, length)` while `seriesByUniverse` accumulates with `+`; if two live collections share a `universeId` (partial-merge/hand-edit), `linkedCollectionItemCount` undercounts the survivor-suggestion heuristic. Sum like the series count. Surfaced in /code-review (low, display only).
+- [ ] [conflict-journal-push-flush-coalesce] **Coalesce per-push base-hash flushes.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~947) stamps a base hash and calls `flushBaseHashes()` per pushed universe/series, so a large push loop rewrites `sync_base_hashes.json` once per record. Copilot (PR #489) suggested debouncing. A `setTimeout`-based debounce was tried and reverted because the real unref'd timer leaked into `peerSync.test.js`'s same-file settle-waits and made the suite flaky. A safe coalescing approach (e.g. a microtask/`queueMicrotask` batch within a single push burst, or a test-injectable scheduler) could land the optimization without the timer-leak flake. Low priority — the flush is serialized + fire-and-forget and the file is tiny.
+- [ ] [conflict-journal-base-hash-prune] **`sync_base_hashes.json` grows unbounded.** `server/lib/conflictJournal.js` seeds a base hash per synced universe/series and never prunes entries for deleted/tombstoned records. Tiny per-entry, but a long-lived install accumulates dead keys. Add a sweep (drop keys whose record no longer resolves) to the tombstone GC path.
+
+### Browser / Chrome-variant + commands hardening (review candidates, 2026-05-25)
+
+Surfaced by a gemini review during PR #489 (sync-hygiene) that scoped beyond that PR's diff — these are in the already-merged Chrome-variant browser feature + the commands service, NOT in #489. Verified against the actual code where noted; out of scope for #489, land them in a separate hardening PR.
+
+- [ ] [browser-spawn-error-handler] **Chrome `spawn()` calls have no `'error'` listener → crash the browser supervisor.** `browser/server.js` lines ~208 (`spawn('/usr/bin/open', …)`) and ~216 (`spawn(chromePath, …)`) attach no `.on('error', …)`, so a missing/non-executable Chrome binary raises `uncaughtException` and takes the process down. Add `.on('error', (err) => { console.error('❌ Failed to spawn Chrome:', err.message); chromeProcess = null; })` to both. Verified (gemini CRITICAL).
+- [ ] [browser-loadconfig-json-guard] **`loadConfig` bare `JSON.parse` crashes on a corrupt config.** `browser/server.js:54` does `raw ? JSON.parse(raw) : {}` with no try/catch — a partially-written/corrupt `data/browser-config.json` throws and crashes boot. Wrap in try/catch returning `{}` with an emoji-prefixed warning. Verified (gemini CRITICAL).
+- [ ] [commands-centralized-parser] **`commands.js` re-implements command parsing with a naive `split(/\s+/)` instead of the centralized quote-aware parser.** `server/services/commands.js:28` splits on whitespace (breaks quoted args) and only imports `ALLOWED_COMMANDS`/`DANGEROUS_SHELL_CHARS` from `commandSecurity.js` — not its `parseCommandArgs`/`validateCommand`. Route through `validateCommand` so allow-listing, dangerous-char checks, and quote-aware arg parsing are one verified step. Verified (gemini IMPROVEMENT).
+- [ ] [setup-browser-config-loss] **`scripts/setup-browser.js` `loadConfig` swallows JSON parse errors silently, then `applyCanaryToConfig` → `saveConfig` can overwrite a corrupt config with a near-empty one (key loss).** Add an emoji-prefixed warning on parse failure and avoid calling `saveConfig` when the existing file was unreadable. Verified (gemini IMPROVEMENT).
+- [ ] [setup-browser-canary-headless] **Fresh Canary opt-in may run headless-invisible — verify intent.** gemini flagged that `applyCanaryToConfig` (`scripts/setup-browser.js:81`) sets `chromePath`/`macAppBundle` but not `headless: false`, so a fresh install that opts into Canary could run it invisibly. UNVERIFIED — confirm whether `false` is already the effective default before changing. (gemini IMPROVEMENT.)
+
## Future Ideas
- **Identity Context Injection** — per-task-type digital twin preamble toggle.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 99cde3d959..d006481953 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -263,6 +263,7 @@ export default function App() {
<Route path="writers-room" element={<WritersRoom />} />
<Route path="writers-room/guide" element={<WritersRoomGuide />} />
<Route path="sharing" element={<Sharing />} />
+ <Route path="sharing/:section" element={<Sharing />} />
<Route path="importer" element={<Importer />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
diff --git a/client/src/components/sharing/ConflictsTab.jsx b/client/src/components/sharing/ConflictsTab.jsx
new file mode 100644
index 0000000000..347c60253c
--- /dev/null
+++ b/client/src/components/sharing/ConflictsTab.jsx
@@ -0,0 +1,136 @@
+/**
+ * Sharing → Conflicts. Lists versions the non-blocking conflict journal
+ * preserved when a cross-install LWW merge would have silently overwritten a
+ * locally-diverged edit. The user can restore their whole version, merge back
+ * specific fields, or discard (keep what synced in).
+ */
+
+import { useEffect, useState, useCallback } from 'react';
+import { Loader2, GitMerge, RotateCcw, Trash2, ChevronDown, ChevronRight } from 'lucide-react';
+import toast from '../ui/Toast';
+import InlineDiff from '../ui/InlineDiff';
+import { listConflicts, resolveConflict, deleteConflict } from '../../services/api';
+
+const asText = (v) => {
+ if (v === null || v === undefined) return '';
+ return typeof v === 'string' ? v : JSON.stringify(v, null, 2);
+};
+
+export default function ConflictsTab() {
+ const [loading, setLoading] = useState(true);
+ const [conflicts, setConflicts] = useState([]);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const res = await listConflicts('pending', { silent: true }).catch(() => ({ conflicts: [] }));
+ setConflicts(res.conflicts || []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ if (loading) {
+ return <div className="flex items-center gap-2 text-gray-400 text-sm py-8"><Loader2 className="animate-spin" size={16} /> Loading conflicts…</div>;
+ }
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-gray-400">
+ When two machines edited the same record, sync keeps the newest by timestamp — but the overwritten version is
+ archived here so nothing is lost. Restore yours, merge back specific fields, or discard.
+ </p>
+ {conflicts.length === 0 ? (
+ <div className="text-sm text-gray-500 py-8 text-center border border-port-border rounded-lg">✓ No pending conflicts.</div>
+ ) : (
+ conflicts.map((c) => <ConflictEntry key={c.id} entry={c} onResolved={load} />)
+ )}
+ </div>
+ );
+}
+
+function ConflictEntry({ entry, onResolved }) {
+ const [expanded, setExpanded] = useState(false);
+ const [selectedFields, setSelectedFields] = useState(() => new Set());
+ const [busy, setBusy] = useState(false);
+
+ const fields = (entry.diffSummary || []).map((d) => d.field);
+
+ const resolve = async (action, fieldList) => {
+ setBusy(true);
+ const ok = await resolveConflict(entry.id, { action, ...(fieldList ? { fields: fieldList } : {}) }, { silent: true })
+ .then(() => true).catch((err) => { toast.error(`Resolve failed: ${err.message}`); return false; });
+ setBusy(false);
+ if (ok) {
+ const msg = action === 'discard' ? 'Discarded — kept the synced version.'
+ : action === 'merge-fields' ? 'Merged selected fields.'
+ : 'Restored your version.';
+ toast.success(msg);
+ onResolved();
+ }
+ };
+
+ const remove = async () => {
+ setBusy(true);
+ const ok = await deleteConflict(entry.id, { silent: true }).then(() => true)
+ .catch((err) => { toast.error(`Delete failed: ${err.message}`); return false; });
+ setBusy(false);
+ if (ok) onResolved();
+ };
+
+ const toggleField = (f) => setSelectedFields((s) => {
+ const next = new Set(s);
+ if (next.has(f)) next.delete(f); else next.add(f);
+ return next;
+ });
+
+ return (
+ <div className="border border-port-border rounded-lg bg-port-card">
+ <div className="flex items-center justify-between gap-3 p-3">
+ <button type="button" onClick={() => setExpanded((v) => !v)} className="flex items-center gap-2 min-w-0 text-left">
+ {expanded ? <ChevronDown size={14} className="text-gray-500 shrink-0" /> : <ChevronRight size={14} className="text-gray-500 shrink-0" />}
+ <span className="text-sm text-white truncate">
+ {entry.recordKind} <span className="font-mono text-[11px] text-gray-500">{entry.recordId?.slice(0, 14)}</span>
+ </span>
+ <span className="text-[11px] text-gray-500 shrink-0">
+ {fields.length} field(s) · via {entry.source?.via || 'sync'}{entry.source?.peerId ? ` (${entry.source.peerId.slice(0, 8)})` : ''} · {entry.detectedAt?.slice(0, 16).replace('T', ' ')}
+ </span>
+ </button>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <button type="button" onClick={() => resolve('restore-all')} disabled={busy}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded bg-port-accent hover:bg-port-accent/90 text-white text-[11px]" title="Restore your overwritten version">
+ <RotateCcw size={12} /> Restore mine
+ </button>
+ <button type="button" onClick={() => resolve('discard')} disabled={busy}
+ className="px-2 py-1 rounded border border-port-border text-gray-400 hover:text-white text-[11px]">
+ Discard
+ </button>
+ <button type="button" onClick={remove} disabled={busy} className="p-1 text-gray-500 hover:text-port-error" title="Remove entry">
+ <Trash2 size={13} />
+ </button>
+ </div>
+ </div>
+
+ {expanded && (
+ <div className="border-t border-port-border p-3 space-y-3">
+ {(entry.diffSummary || []).map((d) => (
+ <div key={d.field} className="border border-port-border rounded p-2">
+ <label className="flex items-center gap-2 text-xs text-white mb-1.5">
+ <input type="checkbox" checked={selectedFields.has(d.field)} onChange={() => toggleField(d.field)} />
+ {d.field} <span className="text-[10px] text-gray-500">({d.changed})</span>
+ </label>
+ {/* old = your archived local value, new = the version that synced in */}
+ <InlineDiff oldText={asText(d.localValue)} newText={asText(d.remoteValue)} />
+ </div>
+ ))}
+ <div className="flex justify-end">
+ <button type="button" disabled={busy || selectedFields.size === 0}
+ onClick={() => resolve('merge-fields', [...selectedFields])}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs disabled:opacity-50">
+ <GitMerge size={13} /> Merge {selectedFields.size || ''} selected field{selectedFields.size === 1 ? '' : 's'}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/sharing/ConflictsTab.test.jsx b/client/src/components/sharing/ConflictsTab.test.jsx
new file mode 100644
index 0000000000..113042940c
--- /dev/null
+++ b/client/src/components/sharing/ConflictsTab.test.jsx
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ listConflicts: vi.fn(),
+ resolveConflict: vi.fn(),
+ deleteConflict: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('../ui/InlineDiff', () => ({ default: ({ oldText, newText }) => <div data-testid="diff">{oldText}|{newText}</div> }));
+
+import * as api from '../../services/api';
+import ConflictsTab from './ConflictsTab';
+
+const entry = {
+ id: 'entry-1',
+ recordKind: 'universe',
+ recordId: 'u-123456789012',
+ detectedAt: '2026-05-25T10:00:00Z',
+ source: { via: 'push', peerId: 'peer-abc' },
+ diffSummary: [
+ { field: 'starterPrompt', localValue: 'my local', remoteValue: 'their remote', changed: 'both' },
+ { field: 'logline', localValue: 'mine', remoteValue: 'theirs', changed: 'both' },
+ ],
+ status: 'pending',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.listConflicts.mockResolvedValue({ conflicts: [entry] });
+});
+
+describe('ConflictsTab', () => {
+ it('lists pending conflicts', async () => {
+ render(<ConflictsTab />);
+ await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
+ expect(screen.getByText(/via push/)).toBeInTheDocument();
+ });
+
+ it('restore-all resolves the whole entry', async () => {
+ api.resolveConflict.mockResolvedValue({ status: 'resolved' });
+ const user = userEvent.setup();
+ render(<ConflictsTab />);
+ await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
+ await user.click(screen.getByRole('button', { name: /Restore mine/ }));
+ await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'restore-all' }, expect.anything()));
+ });
+
+ it('merge-fields sends only the selected fields', async () => {
+ api.resolveConflict.mockResolvedValue({ status: 'resolved' });
+ const user = userEvent.setup();
+ render(<ConflictsTab />);
+ await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
+
+ // Expand the entry, select one field, merge.
+ await user.click(screen.getByText(/u-123456789012/));
+ const checkboxes = await screen.findAllByRole('checkbox');
+ await user.click(checkboxes[0]); // starterPrompt
+ await user.click(screen.getByRole('button', { name: /Merge 1 selected field/ }));
+ await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'merge-fields', fields: ['starterPrompt'] }, expect.anything()));
+ });
+
+ it('discard keeps the synced version', async () => {
+ api.resolveConflict.mockResolvedValue({ status: 'resolved' });
+ const user = userEvent.setup();
+ render(<ConflictsTab />);
+ await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
+ await user.click(screen.getByRole('button', { name: /Discard/ }));
+ await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'discard' }, expect.anything()));
+ });
+});
diff --git a/client/src/components/sharing/DuplicatesTab.jsx b/client/src/components/sharing/DuplicatesTab.jsx
new file mode 100644
index 0000000000..df18294de0
--- /dev/null
+++ b/client/src/components/sharing/DuplicatesTab.jsx
@@ -0,0 +1,311 @@
+/**
+ * Sharing → Duplicates. Lists same-named-but-different-id Universes / Series
+ * that cross-install sync produced, and lets the user MERGE (smart field-union
+ * + cascade) or RENAME one to disambiguate. "Keep both" hides the group for the
+ * session (the records are legitimately distinct).
+ */
+
+import { useEffect, useState, useCallback } from 'react';
+import { Loader2, GitMerge, Pencil, Check, X, Copy } from 'lucide-react';
+import toast from '../ui/Toast';
+import Modal from '../ui/Modal';
+import InlineDiff from '../ui/InlineDiff';
+import {
+ listUniverseDuplicates, listSeriesDuplicates,
+ previewUniverseMerge, mergeUniverses, previewSeriesMerge, mergeSeries,
+ updateUniverse, updatePipelineSeries,
+} from '../../services/api';
+
+const asText = (v) => {
+ if (v === null || v === undefined) return '';
+ return typeof v === 'string' ? v : JSON.stringify(v, null, 2);
+};
+
+export default function DuplicatesTab() {
+ const [loading, setLoading] = useState(true);
+ const [universeGroups, setUniverseGroups] = useState([]);
+ const [seriesGroups, setSeriesGroups] = useState([]);
+ const [orphanCount, setOrphanCount] = useState(0);
+ const [dismissed, setDismissed] = useState(() => new Set());
+ const [merge, setMerge] = useState(null); // { kind, records, survivorId, loserId, preview, choices, busy }
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const [uni, ser] = await Promise.all([
+ listUniverseDuplicates({ silent: true }).catch(() => ({ groups: [] })),
+ listSeriesDuplicates({ silent: true }).catch(() => ({ series: [], orphanCount: 0 })),
+ ]);
+ setUniverseGroups(uni.groups || []);
+ setSeriesGroups(ser.series || []);
+ setOrphanCount(ser.orphanCount || 0);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const groupKey = (kind, normalizedName, scope = '') => `${kind}:${scope}:${normalizedName}`;
+
+ const openMerge = async (kind, records) => {
+ const survivorId = records[0].id;
+ const loserId = records[1].id;
+ setMerge({ kind, records, survivorId, loserId, preview: null, choices: {}, busy: true });
+ await runPreview(kind, survivorId, loserId, records);
+ };
+
+ const runPreview = async (kind, survivorId, loserId, records) => {
+ // Commit the new survivor/loser ids and invalidate the current preview up
+ // front so a quick "Merge" click during the in-flight request can't run with
+ // stale ids/choices (the Merge button gates on `busy || !preview`).
+ setMerge((m) => (m ? {
+ ...m, kind, survivorId, loserId, records: records || m.records, preview: null, choices: {}, busy: true,
+ } : m));
+ const preview = (kind === 'universe' ? previewUniverseMerge : previewSeriesMerge);
+ const result = await preview({ survivorId, loserId }, { silent: true }).catch((err) => {
+ toast.error(`Preview failed: ${err.message}`);
+ return null;
+ });
+ setMerge((m) => (m ? {
+ ...m, kind, survivorId, loserId, records: records || m.records, preview: result,
+ // Default each conflicting field to the survivor's value.
+ choices: Object.fromEntries((result?.conflicts || []).map((c) => [c.field, 'survivor'])),
+ busy: false,
+ } : m));
+ };
+
+ const executeMerge = async () => {
+ const { kind, survivorId, loserId, choices } = merge;
+ setMerge((m) => ({ ...m, busy: true }));
+ const run = kind === 'universe' ? mergeUniverses : mergeSeries;
+ const ok = await run({ survivorId, loserId, fieldChoices: choices }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(`Merge failed: ${err.message}`); return false; });
+ if (ok) {
+ toast.success('Merged — the duplicate was folded in and tombstoned.');
+ setMerge(null);
+ await load();
+ } else {
+ setMerge((m) => (m ? { ...m, busy: false } : m));
+ }
+ };
+
+ if (loading) {
+ return <div className="flex items-center gap-2 text-gray-400 text-sm py-8"><Loader2 className="animate-spin" size={16} /> Scanning for duplicates…</div>;
+ }
+
+ const visibleUniverse = universeGroups.filter((g) => !dismissed.has(groupKey('universe', g.normalizedName)));
+ const visibleSeries = seriesGroups.filter((g) => !dismissed.has(groupKey('series', g.normalizedName, g.universeId)));
+ const nothing = visibleUniverse.length === 0 && visibleSeries.length === 0;
+
+ return (
+ <div className="space-y-6">
+ <p className="text-sm text-gray-400">
+ Cross-install sync can leave two records with the same name but different ids (e.g. both machines created
+ “Clandestiny”). Merge folds one into the other (unioning canon, re-pointing children) or rename one to keep both.
+ </p>
+
+ {nothing && (
+ <div className="text-sm text-gray-500 py-8 text-center border border-port-border rounded-lg">
+ ✓ No duplicates found.
+ {orphanCount > 0 && <div className="mt-1 text-xs text-port-warning">{orphanCount} orphan series (no universe) — they’ll be adopted on next migration.</div>}
+ </div>
+ )}
+
+ {visibleUniverse.map((g) => (
+ <DuplicateGroup
+ key={groupKey('universe', g.normalizedName)} kind="universe" label="Universe" group={g}
+ onMerge={openMerge} onRenamed={load}
+ onKeepBoth={() => setDismissed((s) => new Set(s).add(groupKey('universe', g.normalizedName)))}
+ />
+ ))}
+ {visibleSeries.map((g) => (
+ <DuplicateGroup
+ key={groupKey('series', g.normalizedName, g.universeId)} kind="series"
+ label={`Series in “${g.universeName || g.universeId}”`} group={g}
+ onMerge={openMerge} onRenamed={load}
+ onKeepBoth={() => setDismissed((s) => new Set(s).add(groupKey('series', g.normalizedName, g.universeId)))}
+ />
+ ))}
+
+ {merge && (
+ <MergeModal
+ merge={merge} setMerge={setMerge} onExecute={executeMerge}
+ onRepreview={(survivorId, loserId) => runPreview(merge.kind, survivorId, loserId, merge.records)}
+ />
+ )}
+ </div>
+ );
+}
+
+function DuplicateGroup({ kind, label, group, onMerge, onRenamed, onKeepBoth }) {
+ return (
+ <div className="border border-port-border rounded-lg p-4 bg-port-card">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-white flex items-center gap-2">
+ <Copy size={14} className="text-port-warning" /> {label}: <span className="text-port-warning">{group.records[0].name}</span>
+ <span className="text-xs text-gray-500">({group.records.length} copies)</span>
+ </h3>
+ <div className="flex items-center gap-2">
+ <button type="button" onClick={() => onMerge(kind, group.records)}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium">
+ <GitMerge size={13} /> Merge…
+ </button>
+ <button type="button" onClick={onKeepBoth}
+ className="px-2.5 py-1.5 rounded border border-port-border text-gray-400 hover:text-white text-xs">
+ Keep both
+ </button>
+ </div>
+ </div>
+ <div className="space-y-2">
+ {group.records.map((r) => <RecordRow key={r.id} kind={kind} record={r} onRenamed={onRenamed} />)}
+ </div>
+ </div>
+ );
+}
+
+function RecordRow({ kind, record, onRenamed }) {
+ const [editing, setEditing] = useState(false);
+ const [name, setName] = useState(record.name);
+ const [busy, setBusy] = useState(false);
+
+ // Keep the editable name in sync with the prop after a rename + reload so
+ // reopening the inline editor never shows the stale initial value. Only when
+ // not actively editing, so we don't clobber the user's in-progress text.
+ useEffect(() => {
+ if (!editing) setName(record.name);
+ }, [record.name, editing]);
+
+ const save = async () => {
+ if (!name.trim() || name === record.name) { setEditing(false); return; }
+ setBusy(true);
+ const update = kind === 'universe' ? updateUniverse : updatePipelineSeries;
+ const ok = await update(record.id, { name: name.trim() }, { silent: true })
+ .then(() => true).catch((err) => { toast.error(`Rename failed: ${err.message}`); return false; });
+ setBusy(false);
+ if (ok) { toast.success('Renamed'); setEditing(false); onRenamed(); }
+ };
+
+ const counts = record.counts;
+ return (
+ <div className="flex items-center justify-between gap-3 text-xs bg-port-bg border border-port-border rounded px-3 py-2">
+ <div className="min-w-0 flex-1">
+ {editing ? (
+ <div className="flex items-center gap-2">
+ <input autoFocus value={name} onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') save(); if (e.key === 'Escape') setEditing(false); }}
+ className="flex-1 px-2 py-1 bg-port-card border border-port-border rounded text-white" />
+ <button type="button" onClick={save} disabled={busy} className="text-port-success hover:opacity-80"><Check size={14} /></button>
+ <button type="button" onClick={() => { setEditing(false); setName(record.name); }} className="text-gray-500 hover:text-white"><X size={14} /></button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2">
+ <span className="text-white truncate">{record.name}</span>
+ <button type="button" onClick={() => setEditing(true)} className="text-gray-500 hover:text-white" title="Rename"><Pencil size={12} /></button>
+ </div>
+ )}
+ <div className="text-gray-500 mt-0.5 font-mono truncate">{record.id}</div>
+ </div>
+ <div className="text-gray-400 text-right whitespace-nowrap">
+ {counts && <div>{counts.characters}c · {counts.places}p · {counts.objects}o · {counts.categories} cats</div>}
+ {kind === 'universe' && <div>{record.linkedSeriesCount} series · {record.linkedCollectionItemCount} media</div>}
+ {kind === 'series' && <div>{record.seasonCount} seasons{record.hasArc ? ' · arc' : ''}</div>}
+ <div className="text-[10px]">updated {record.updatedAt?.slice(0, 10)}</div>
+ </div>
+ </div>
+ );
+}
+
+function MergeModal({ merge, setMerge, onExecute, onRepreview }) {
+ const { kind, records, survivorId, loserId, preview, choices, busy } = merge;
+ const conflicts = preview?.conflicts || [];
+ const cascade = preview?.cascade || {};
+ const multi = records.length > 2; // 3+ copies fold one pair at a time
+
+ const setChoice = (field, val) => setMerge((m) => ({ ...m, choices: { ...m.choices, [field]: val } }));
+ const swapSurvivor = (newSurvivorId) => {
+ // Keep the current loser unless it collides with the new survivor, then
+ // pick the first remaining record so survivor and loser always differ.
+ const keepLoser = loserId !== newSurvivorId && records.some((r) => r.id === loserId);
+ const newLoser = keepLoser ? loserId : records.find((r) => r.id !== newSurvivorId)?.id;
+ onRepreview(newSurvivorId, newLoser);
+ };
+ const loser = records.find((r) => r.id === loserId);
+
+ return (
+ <Modal open onClose={() => !busy && setMerge(null)} size="2xl" ariaLabel="Merge duplicates">
+ <div className="p-5 space-y-4">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2"><GitMerge size={18} /> Merge {kind}</h2>
+
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Keep (survivor)</label>
+ <div className="grid gap-2">
+ {records.map((r) => (
+ <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === survivorId ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400'}`}>
+ <input type="radio" name="survivor" checked={r.id === survivorId} onChange={() => swapSurvivor(r.id)} />
+ <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
+ {r.id === loserId && <span className="ml-auto text-[10px] text-port-error">→ folds in</span>}
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {multi ? (
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Fold in (this merge folds one copy at a time — repeat for the rest)</label>
+ <div className="grid gap-2">
+ {records.filter((r) => r.id !== survivorId).map((r) => (
+ <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === loserId ? 'border-port-error/60 bg-port-error/10 text-white' : 'border-port-border text-gray-400'}`}>
+ <input type="radio" name="loser" checked={r.id === loserId} onChange={() => onRepreview(survivorId, r.id)} />
+ <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
+ </label>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">Folding in &amp; tombstoning <span className="text-port-error">{loser?.name}</span> <span className="font-mono text-[10px]">{loser?.id.slice(0, 12)}</span>.</p>
+ )}
+
+ {busy && !preview && <div className="flex items-center gap-2 text-gray-400 text-sm"><Loader2 className="animate-spin" size={14} /> Building preview…</div>}
+
+ {preview && conflicts.length > 0 && (
+ <div>
+ <label className="block text-xs text-gray-400 mb-2">{conflicts.length} conflicting field(s) — pick which value wins:</label>
+ <div className="space-y-3">
+ {conflicts.map((c) => (
+ <div key={c.field} className="border border-port-border rounded p-3">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-medium text-white">{c.field}</span>
+ <div className="flex gap-1 text-[11px]">
+ <button type="button" onClick={() => setChoice(c.field, 'survivor')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'survivor' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Keep survivor</button>
+ <button type="button" onClick={() => setChoice(c.field, 'loser')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'loser' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Use folded</button>
+ </div>
+ </div>
+ <InlineDiff oldText={asText(c.survivorValue)} newText={asText(c.loserValue)} />
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {preview && conflicts.length === 0 && (
+ <div className="text-xs text-port-success">No conflicting fields — unique data from both will be unioned.</div>
+ )}
+
+ {preview && (
+ <div className="text-xs text-gray-400 border-t border-port-border pt-3">
+ Cascade: {kind === 'universe'
+ ? `${cascade.seriesToRepoint?.length || 0} child series re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`
+ : `${cascade.issuesToRepoint || 0} issues re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`}
+ </div>
+ )}
+
+ <div className="flex justify-end gap-2 pt-2">
+ <button type="button" onClick={() => setMerge(null)} disabled={busy} className="px-3 py-2 rounded border border-port-border text-gray-300 text-sm">Cancel</button>
+ <button type="button" onClick={onExecute} disabled={busy || !preview || survivorId === loserId}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium disabled:opacity-50">
+ {busy ? <Loader2 className="animate-spin" size={14} /> : <GitMerge size={14} />} Merge
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/sharing/DuplicatesTab.test.jsx b/client/src/components/sharing/DuplicatesTab.test.jsx
new file mode 100644
index 0000000000..748dafd5e0
--- /dev/null
+++ b/client/src/components/sharing/DuplicatesTab.test.jsx
@@ -0,0 +1,81 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ listUniverseDuplicates: vi.fn(),
+ listSeriesDuplicates: vi.fn(),
+ previewUniverseMerge: vi.fn(),
+ mergeUniverses: vi.fn(),
+ previewSeriesMerge: vi.fn(),
+ mergeSeries: vi.fn(),
+ updateUniverse: vi.fn(),
+ updatePipelineSeries: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('../ui/Modal', () => ({ default: ({ open, children }) => (open ? <div role="dialog">{children}</div> : null) }));
+vi.mock('../ui/InlineDiff', () => ({ default: ({ oldText, newText }) => <div data-testid="diff">{oldText}|{newText}</div> }));
+
+import * as api from '../../services/api';
+import DuplicatesTab from './DuplicatesTab';
+
+const uniGroup = {
+ normalizedName: 'clandestiny',
+ records: [
+ { id: 'u-new', name: 'Clandestiny', updatedAt: '2026-05-22T00:00:00Z', counts: { characters: 5, places: 2, objects: 1, categories: 4 }, linkedSeriesCount: 1, linkedCollectionItemCount: 3 },
+ { id: 'u-old', name: 'Clandestiny', updatedAt: '2026-05-11T00:00:00Z', counts: { characters: 1, places: 0, objects: 0, categories: 4 }, linkedSeriesCount: 0, linkedCollectionItemCount: 0 },
+ ],
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.listUniverseDuplicates.mockResolvedValue({ groups: [uniGroup] });
+ api.listSeriesDuplicates.mockResolvedValue({ series: [], orphans: [], orphanCount: 0 });
+});
+
+describe('DuplicatesTab', () => {
+ it('lists a universe duplicate group with both records', async () => {
+ render(<DuplicatesTab />);
+ await waitFor(() => expect(screen.getByText(/2 copies/)).toBeInTheDocument());
+ expect(screen.getAllByText('Clandestiny').length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('opens the merge modal, shows the conflict, and executes with field choices', async () => {
+ api.previewUniverseMerge.mockResolvedValue({
+ conflicts: [{ field: 'starterPrompt', survivorValue: 'A', loserValue: 'B' }],
+ cascade: { seriesToRepoint: [{ id: 's1' }], loserCollectionItemCount: 3 },
+ });
+ api.mergeUniverses.mockResolvedValue({ merged: true });
+ const user = userEvent.setup();
+ render(<DuplicatesTab />);
+ await waitFor(() => expect(screen.getByText(/2 copies/)).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /Merge…/ }));
+ await waitFor(() => expect(api.previewUniverseMerge).toHaveBeenCalledWith({ survivorId: 'u-new', loserId: 'u-old' }, expect.anything()));
+ // Conflict surfaced.
+ await waitFor(() => expect(screen.getByText('starterPrompt')).toBeInTheDocument());
+ expect(screen.getByText(/child series re-pointed/)).toBeInTheDocument();
+
+ // Execute — default choice is survivor.
+ await user.click(screen.getByRole('button', { name: /^Merge$/ }));
+ await waitFor(() => expect(api.mergeUniverses).toHaveBeenCalledWith(
+ { survivorId: 'u-new', loserId: 'u-old', fieldChoices: { starterPrompt: 'survivor' } },
+ expect.anything(),
+ ));
+ });
+
+ it('renames a record inline via the update API', async () => {
+ api.updateUniverse.mockResolvedValue({ id: 'u-old', name: 'Clandestiny (v2)' });
+ const user = userEvent.setup();
+ render(<DuplicatesTab />);
+ await waitFor(() => expect(screen.getByText(/2 copies/)).toBeInTheDocument());
+
+ const renameButtons = screen.getAllByTitle('Rename');
+ await user.click(renameButtons[0]);
+ const input = screen.getByDisplayValue('Clandestiny');
+ await user.clear(input);
+ await user.type(input, 'Clandestiny (v2)');
+ await user.keyboard('{Enter}');
+ await waitFor(() => expect(api.updateUniverse).toHaveBeenCalledWith('u-new', { name: 'Clandestiny (v2)' }, expect.anything()));
+ });
+});
diff --git a/client/src/pages/Sharing.jsx b/client/src/pages/Sharing.jsx
index 4155c47672..41834d4f1d 100644
--- a/client/src/pages/Sharing.jsx
+++ b/client/src/pages/Sharing.jsx
@@ -7,12 +7,15 @@
* that get stamped as the source on every outgoing share.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
+import { useParams, Link } from 'react-router-dom';
import {
- Share2, Plus, Trash2, Folder, Inbox, History, Save, Loader2, Check, X, Users, AlertCircle, RefreshCw,
+ Share2, Plus, Trash2, Folder, Inbox, History, Save, Loader2, Check, X, Users, AlertCircle, RefreshCw, Copy, GitMerge,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import FolderPicker from '../components/FolderPicker';
+import DuplicatesTab from '../components/sharing/DuplicatesTab';
+import ConflictsTab from '../components/sharing/ConflictsTab';
import socket from '../services/socket';
import {
listShareBuckets, createShareBucket, updateShareBucket, deleteShareBucket,
@@ -35,7 +38,54 @@ export function isLiveSubscription(item, now = Date.now()) {
return (now - receivedMs) < SUBSCRIPTION_LIVE_WINDOW_MS;
}
+// Top-level deep-linkable sections. Buckets is the bucket-management view;
+// Duplicates + Conflicts are the sync-hygiene review surfaces.
+const SECTIONS = [
+ { id: 'buckets', label: 'Buckets', icon: Folder, path: '/sharing' },
+ { id: 'duplicates', label: 'Duplicates', icon: Copy, path: '/sharing/duplicates' },
+ { id: 'conflicts', label: 'Conflicts', icon: GitMerge, path: '/sharing/conflicts' },
+];
+
+function SharingHeader({ active }) {
+ return (
+ <>
+ <div className="flex items-center gap-3 mb-4">
+ <Share2 className="w-6 h-6 text-port-accent" />
+ <h1 className="text-2xl font-bold text-white">Sharing</h1>
+ </div>
+ <nav className="flex items-center gap-1 mb-6 border-b border-port-border">
+ {SECTIONS.map(({ id, label, icon: Icon, path }) => (
+ <Link
+ key={id}
+ to={path}
+ className={`inline-flex items-center gap-2 px-3 py-2 text-sm border-b-2 -mb-px ${
+ active === id
+ ? 'border-port-accent text-white'
+ : 'border-transparent text-gray-400 hover:text-white'
+ }`}
+ >
+ <Icon size={14} /> {label}
+ </Link>
+ ))}
+ </nav>
+ </>
+ );
+}
+
export default function Sharing() {
+ const { section = 'buckets' } = useParams();
+ if (section === 'duplicates' || section === 'conflicts') {
+ return (
+ <div>
+ <SharingHeader active={section} />
+ {section === 'duplicates' ? <DuplicatesTab /> : <ConflictsTab />}
+ </div>
+ );
+ }
+ return <SharingBuckets />;
+}
+
+function SharingBuckets() {
const [buckets, setBuckets] = useState([]);
const [localSchemaVersion, setLocalSchemaVersion] = useState(null);
const [loading, setLoading] = useState(true);
@@ -213,11 +263,8 @@ export default function Sharing() {
return (
<div>
- <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
- <div className="flex items-center gap-3">
- <Share2 className="w-6 h-6 text-port-accent" />
- <h1 className="text-2xl font-bold text-white">Sharing</h1>
- </div>
+ <SharingHeader active="buckets" />
+ <div className="flex justify-end mb-4">
<button
type="button"
onClick={() => setShowAdd((v) => !v)}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index cac509e1e0..9c150fbe18 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -85,6 +85,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiWritersRoom.js` | Writers Room (folders + works + drafts). |
| `apiSharing.js` | Share buckets + federation sync. |
| `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). |
+| `apiSyncReview.js` | Sync hygiene: duplicate-record detection + smart merge (universe/series) and the non-blocking edit-conflict journal (list/resolve). Surfaced in Sharing → Duplicates / Conflicts. |
## Tools / integrations
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 7fd02f3486..7dc9b78087 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -44,6 +44,7 @@ export * from './apiUniverseBuilder.js';
export * from './apiPipeline.js';
export * from './apiSharing.js';
export * from './apiPeerSync.js';
+export * from './apiSyncReview.js';
export * from './apiCreativeDirector.js';
export * from './apiImporter.js';
export * from './apiVoice.js';
diff --git a/client/src/services/apiSyncReview.js b/client/src/services/apiSyncReview.js
new file mode 100644
index 0000000000..ff94d9cccf
--- /dev/null
+++ b/client/src/services/apiSyncReview.js
@@ -0,0 +1,41 @@
+import { request } from './apiCore.js';
+
+// ---- Duplicate resolution ----
+// Same-named-but-different-id Universes / Series that arrive via cross-install
+// sync. See server/services/duplicateDetection.js + recordMerge.js.
+
+export const listUniverseDuplicates = (options) =>
+ request('/universe-builder/duplicates', options);
+
+export const listSeriesDuplicates = (options) =>
+ request('/pipeline/series/duplicates', options);
+
+// Preview returns { survivorId, loserId, preview, conflicts, autoResolved, cascade }.
+export const previewUniverseMerge = (body, options) =>
+ request('/universe-builder/merge/preview', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const mergeUniverses = (body, options) =>
+ request('/universe-builder/merge', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const previewSeriesMerge = (body, options) =>
+ request('/pipeline/series/merge/preview', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const mergeSeries = (body, options) =>
+ request('/pipeline/series/merge', { method: 'POST', body: JSON.stringify(body), ...options });
+
+// ---- Conflict journal ----
+// Versions a cross-install LWW overwrite preserved instead of silently losing.
+// See server/services/conflictJournalResolver.js.
+
+export const listConflicts = (status, options) =>
+ request(`/conflict-journal${status ? `?status=${encodeURIComponent(status)}` : ''}`, options);
+
+export const getConflict = (id, options) =>
+ request(`/conflict-journal/${encodeURIComponent(id)}`, options);
+
+// body: { action: 'restore-all'|'merge-fields'|'discard', fields?: string[] }
+export const resolveConflict = (id, body, options) =>
+ request(`/conflict-journal/${encodeURIComponent(id)}/resolve`, { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const deleteConflict = (id, options) =>
+ request(`/conflict-journal/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
diff --git a/scripts/migrations/039-adopt-orphan-series-into-universes.js b/scripts/migrations/039-adopt-orphan-series-into-universes.js
new file mode 100644
index 0000000000..06d6569707
--- /dev/null
+++ b/scripts/migrations/039-adopt-orphan-series-into-universes.js
@@ -0,0 +1,150 @@
+/**
+ * Adopt orphan series (a series with no `universeId`) into a synthesized
+ * universe, enforcing the hierarchy invariant "a series lives in exactly one
+ * universe; a universe has many series".
+ *
+ * Why:
+ * PortOS now requires every series to belong to a universe (the create route
+ * rejects a missing universeId, updateSeries rejects un-linking, and
+ * deleteUniverse blocks while live series reference it). Legacy installs — and
+ * peers that shipped orphan series via share-bucket import before the rule
+ * existed — can still have series with `universeId: null` on disk. This
+ * migration gives each a home so the new guards never trip on legacy data.
+ *
+ * What it does:
+ * For each non-deleted series with no universeId, derive a STABLE universe id
+ * `uni-from-series-<sha1(seriesId)>` (same scheme as the long-standing
+ * migrateSeriesCanon CLI, so the two converge on the same orphan universe
+ * instead of minting two), create that universe if absent, and stamp the
+ * series' `universeId`.
+ *
+ * Dependency-light (fs + path + crypto only), per the migration convention —
+ * the deterministic-id helper and universe-id cap are inlined copies of
+ * server/services/universeBuilder.js / migrateSeriesCanon.js. KEEP IN SYNC.
+ *
+ * No new data.reference/ seed: this only populates a field on existing records
+ * and writes records into the already-shipped universes collection layout — it
+ * introduces no new file type or storage-layout change.
+ *
+ * Idempotent: a second run finds no orphans (they're now linked) → no-op. A
+ * retry after a partial run reuses the deterministic universe instead of
+ * duplicating.
+ */
+
+import { readFile, writeFile, mkdir, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { createHash } from 'node:crypto';
+
+// Record-shape version stamped INSIDE each universe (CURRENT_SCHEMA_VERSION in
+// universeBuilder.js). sanitizeTemplate backfills any missing fields on read,
+// so a minimal record at this version round-trips cleanly.
+const RECORD_SCHEMA_VERSION = 4;
+// Storage-layout version on data/universes/index.json (TYPE_SCHEMA_VERSION).
+const TYPE_SCHEMA_VERSION = 5;
+const SERIES_DIR = 'pipeline-series';
+const UNIVERSES_DIR = 'universes';
+
+// Mirror migrateSeriesCanon.deriveOrphanUniverseId — sha1 of the series id,
+// truncated to 32 hex chars. `uni-from-series-` (16) + 32 = 48 chars, within
+// UNIVERSE_ID_RE `[A-Za-z0-9-]{8,80}`.
+const deriveOrphanUniverseId = (seriesId) =>
+ `uni-from-series-${createHash('sha1').update(String(seriesId)).digest('hex').slice(0, 32)}`;
+
+const fileExists = (p) => stat(p).then(() => true, (e) => {
+ if (e.code === 'ENOENT') return false;
+ throw e;
+});
+const readJson = async (p) => {
+ const raw = await readFile(p, 'utf-8').catch((e) => { if (e.code === 'ENOENT') return null; throw e; });
+ if (raw == null) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+};
+const writeJson = (p, value) => writeFile(p, JSON.stringify(value, null, 2) + '\n');
+
+// Minimal v4 universe record. sanitizeTemplate normalizes the rest on first
+// read; the next universe-side write persists the full shape.
+const makeUniverseRecord = (id, series, now) => ({
+ id,
+ name: `${series.name} (adopted)`.slice(0, 100),
+ starterPrompt: (series.logline || (series.premise ? String(series.premise).slice(0, 500) : '') || ''),
+ categories: {},
+ compositeSheets: [],
+ influences: { embrace: [], avoid: [] },
+ characters: [],
+ places: [],
+ objects: [],
+ locked: {},
+ schemaVersion: RECORD_SCHEMA_VERSION,
+ createdAt: now,
+ updatedAt: now,
+ deleted: false,
+ deletedAt: null,
+});
+
+export default {
+ async up({ rootDir }) {
+ const dataDir = join(rootDir, 'data');
+ const seriesDir = join(dataDir, SERIES_DIR);
+ const universesDir = join(dataDir, UNIVERSES_DIR);
+
+ if (!(await fileExists(seriesDir))) {
+ console.log('🧬 migration 039: no pipeline-series dir — fresh install, no-op');
+ return { ok: true, reason: 'no-series' };
+ }
+
+ const entries = await readdir(seriesDir, { withFileTypes: true }).catch(() => []);
+ const orphans = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name === 'index.json' || entry.name.startsWith('.')) continue;
+ const rec = await readJson(join(seriesDir, entry.name, 'index.json'));
+ if (!rec || typeof rec !== 'object' || typeof rec.id !== 'string') continue;
+ if (rec.deleted === true) continue;
+ const linked = typeof rec.universeId === 'string' && rec.universeId.trim();
+ if (!linked) orphans.push(rec);
+ }
+
+ if (orphans.length === 0) {
+ console.log('🧬 migration 039: no orphan series — no-op');
+ return { ok: true, reason: 'no-orphans' };
+ }
+
+ // Ensure the universes type index exists (an install with orphan series but
+ // zero universes won't have one) so the store + verifyCollectionVersions
+ // can read what we write.
+ await mkdir(universesDir, { recursive: true });
+ const typeIndexPath = join(universesDir, 'index.json');
+ if (!(await fileExists(typeIndexPath))) {
+ await writeJson(typeIndexPath, {
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ type: 'universes',
+ updatedAt: new Date().toISOString(),
+ config: { runs: [] },
+ });
+ }
+
+ let created = 0;
+ let linked = 0;
+ for (const series of orphans) {
+ const now = new Date().toISOString();
+ const universeId = deriveOrphanUniverseId(series.id);
+ const recordDir = join(universesDir, universeId);
+ const recordPath = join(recordDir, 'index.json');
+ if (!(await fileExists(recordPath))) {
+ await mkdir(recordDir, { recursive: true });
+ await writeJson(recordPath, makeUniverseRecord(universeId, series, now));
+ created += 1;
+ console.log(`🌌 migration 039: created universe ${universeId} for orphan series "${series.name}" (${series.id})`);
+ }
+ // Stamp the link onto the series record + bump updatedAt so the link
+ // propagates via the normal LWW sync path on the next cycle.
+ await writeJson(
+ join(seriesDir, series.id, 'index.json'),
+ { ...series, universeId, updatedAt: now },
+ );
+ linked += 1;
+ }
+
+ console.log(`🧬 migration 039: adopted ${linked} orphan series into ${created} synthesized universe(s)`);
+ return { ok: true, reason: 'adopted', linked, created };
+ },
+};
diff --git a/scripts/migrations/039-adopt-orphan-series-into-universes.test.js b/scripts/migrations/039-adopt-orphan-series-into-universes.test.js
new file mode 100644
index 0000000000..194fabf7a2
--- /dev/null
+++ b/scripts/migrations/039-adopt-orphan-series-into-universes.test.js
@@ -0,0 +1,93 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { createHash } from 'node:crypto';
+
+import migration from './039-adopt-orphan-series-into-universes.js';
+
+const readJson = (p) => JSON.parse(readFileSync(p, 'utf-8'));
+const writeJson = (p, v) => writeFileSync(p, JSON.stringify(v, null, 2) + '\n');
+const derivedId = (seriesId) =>
+ `uni-from-series-${createHash('sha1').update(String(seriesId)).digest('hex').slice(0, 32)}`;
+
+describe('migration 039 — adopt orphan series into universes', () => {
+ let rootDir;
+ let seriesDir;
+ let universesDir;
+
+ const writeSeries = (rec) => {
+ const dir = join(seriesDir, rec.id);
+ mkdirSync(dir, { recursive: true });
+ writeJson(join(dir, 'index.json'), rec);
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-039-'));
+ seriesDir = join(rootDir, 'data', 'pipeline-series');
+ universesDir = join(rootDir, 'data', 'universes');
+ mkdirSync(seriesDir, { recursive: true });
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('adopts an orphan series into a deterministic synthesized universe', async () => {
+ writeSeries({ id: 'ser-1', name: 'Salt Run', logline: 'A heist', universeId: null, updatedAt: '2026-05-01T00:00:00Z' });
+
+ const res = await migration.up({ rootDir });
+ expect(res).toMatchObject({ ok: true, reason: 'adopted', linked: 1, created: 1 });
+
+ const uid = derivedId('ser-1');
+ const universe = readJson(join(universesDir, uid, 'index.json'));
+ expect(universe.id).toBe(uid);
+ expect(universe.name).toBe('Salt Run (adopted)');
+ expect(universe.starterPrompt).toBe('A heist');
+
+ const series = readJson(join(seriesDir, 'ser-1', 'index.json'));
+ expect(series.universeId).toBe(uid);
+ expect(series.updatedAt).not.toBe('2026-05-01T00:00:00Z'); // bumped
+
+ // Type index stamped so the store can read it.
+ expect(readJson(join(universesDir, 'index.json')).schemaVersion).toBe(5);
+ });
+
+ it('leaves already-linked series untouched', async () => {
+ writeSeries({ id: 'ser-2', name: 'Linked', universeId: 'u-existing', updatedAt: '2026-05-01T00:00:00Z' });
+ const res = await migration.up({ rootDir });
+ expect(res.reason).toBe('no-orphans');
+ expect(readJson(join(seriesDir, 'ser-2', 'index.json')).universeId).toBe('u-existing');
+ });
+
+ it('skips deleted orphan series', async () => {
+ writeSeries({ id: 'ser-3', name: 'Gone', universeId: null, deleted: true, deletedAt: '2026-05-01T00:00:00Z', updatedAt: '2026-05-01T00:00:00Z' });
+ const res = await migration.up({ rootDir });
+ expect(res.reason).toBe('no-orphans');
+ expect(existsSync(join(universesDir, derivedId('ser-3')))).toBe(false);
+ });
+
+ it('is idempotent — a second run is a no-op', async () => {
+ writeSeries({ id: 'ser-4', name: 'Once', universeId: null, updatedAt: '2026-05-01T00:00:00Z' });
+ await migration.up({ rootDir });
+ const second = await migration.up({ rootDir });
+ expect(second.reason).toBe('no-orphans');
+ });
+
+ it('reuses the deterministic universe on retry instead of duplicating', async () => {
+ writeSeries({ id: 'ser-5', name: 'Retry', universeId: null, updatedAt: '2026-05-01T00:00:00Z' });
+ const uid = derivedId('ser-5');
+ // Simulate a prior partial run: universe exists but series link never landed.
+ mkdirSync(join(universesDir, uid), { recursive: true });
+ writeJson(join(universesDir, uid, 'index.json'), { id: uid, name: 'Pre-existing', schemaVersion: 4 });
+
+ const res = await migration.up({ rootDir });
+ expect(res).toMatchObject({ linked: 1, created: 0 }); // reused, not recreated
+ expect(readJson(join(universesDir, uid, 'index.json')).name).toBe('Pre-existing'); // untouched
+ expect(readJson(join(seriesDir, 'ser-5', 'index.json')).universeId).toBe(uid);
+ });
+
+ it('no-op on a fresh install with no series dir', async () => {
+ rmSync(seriesDir, { recursive: true, force: true });
+ const res = await migration.up({ rootDir });
+ expect(res.reason).toBe('no-series');
+ });
+});
diff --git a/scripts/migrations/040-init-conflict-journal-store.js b/scripts/migrations/040-init-conflict-journal-store.js
new file mode 100644
index 0000000000..8e1202230d
--- /dev/null
+++ b/scripts/migrations/040-init-conflict-journal-store.js
@@ -0,0 +1,51 @@
+/**
+ * Initialize the conflict-journal collection store.
+ *
+ * The non-blocking conflict journal (server/lib/conflictJournal.js) archives
+ * the losing local version when a cross-install LWW merge would overwrite a
+ * record that BOTH sides edited independently. It is purely local runtime
+ * state (never synced to peers), stored at `data/conflict-journal/{id}/index.json`
+ * with a type-level `data/conflict-journal/index.json` stamping schemaVersion 1.
+ *
+ * The store self-initializes on first write, and the boot-time
+ * verifyCollectionVersions tolerates a missing index (reads as the expected
+ * version). This migration stamps the type index up front so an existing
+ * install lands in the same clean state as a fresh one — idempotent: a second
+ * run (or an install that already wrote a journal entry) is a no-op.
+ *
+ * Dependency-light (fs + path only), per the migration convention. No
+ * data.reference/ seed — an empty runtime store ships nothing.
+ */
+
+import { mkdir, readFile, writeFile, stat } from 'fs/promises';
+import { join } from 'path';
+
+const TYPE_SCHEMA_VERSION = 1;
+
+const fileExists = (p) => stat(p).then(() => true, (e) => { if (e.code === 'ENOENT') return false; throw e; });
+
+export default {
+ async up({ rootDir }) {
+ const typeDir = join(rootDir, 'data', 'conflict-journal');
+ const typeIndexPath = join(typeDir, 'index.json');
+
+ if (await fileExists(typeIndexPath)) {
+ const raw = await readFile(typeIndexPath, 'utf-8').catch(() => null);
+ const parsed = raw ? JSON.parse(raw) : null;
+ if (parsed && parsed.schemaVersion >= TYPE_SCHEMA_VERSION) {
+ console.log('🪢 migration 040: conflict-journal store already initialized — no-op');
+ return { ok: true, reason: 'already-applied' };
+ }
+ }
+
+ await mkdir(typeDir, { recursive: true });
+ await writeFile(typeIndexPath, JSON.stringify({
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ type: 'conflictJournal',
+ updatedAt: new Date().toISOString(),
+ config: {},
+ }, null, 2) + '\n');
+ console.log(`🪢 migration 040: stamped data/conflict-journal/index.json @ v${TYPE_SCHEMA_VERSION}`);
+ return { ok: true, reason: 'initialized' };
+ },
+};
diff --git a/server/index.js b/server/index.js
index 9e3d51bbeb..de257a087f 100644
--- a/server/index.js
+++ b/server/index.js
@@ -97,6 +97,7 @@ import mediaJobsRoutes from './routes/mediaJobs.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
import writersRoomRoutes from './routes/writersRoom.js';
import universeBuilderRoutes from './routes/universeBuilder.js';
+import conflictJournalRoutes from './routes/conflictJournal.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
@@ -144,6 +145,7 @@ import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from './lib/aiToolkit/index.js';
import { runMigrations } from '../scripts/run-migrations.js';
import { verifyCollectionVersions } from './lib/collectionStore.js';
+import { conflictJournalStore } from './lib/conflictJournal.js';
import { universeStore } from './services/universeBuilder.js';
import { seriesStore } from './services/pipeline/series.js';
import { issueStore } from './services/pipeline/issues.js';
@@ -202,7 +204,7 @@ await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {
// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security
// Model"); a hard exit on startup is worse than a noisy log the user can act
// on. Returns per-store statuses for downstream telemetry; we discard them.
-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore()]).catch(err => {
+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore()]).catch(err => {
console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);
});
@@ -446,6 +448,7 @@ app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/universe-builder', universeBuilderRoutes);
app.use('/api/pipeline', pipelineRoutes);
+app.use('/api/conflict-journal', conflictJournalRoutes);
app.use('/api/importer', importerRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
app.use('/api/loras', lorasRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index ddbf25ae42..65d88b1382 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -81,6 +81,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |
+| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply on the comparator result so an upgraded sender can't corrupt a downstream peer. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
new file mode 100644
index 0000000000..51f146d3cf
--- /dev/null
+++ b/server/lib/conflictJournal.js
@@ -0,0 +1,231 @@
+/**
+ * Non-blocking conflict journal.
+ *
+ * All cross-install merges are last-write-wins by `updatedAt`. When LWW would
+ * OVERWRITE a local record but BOTH sides edited it independently since the
+ * last time they were in sync (a true 3-way divergence), the losing local
+ * version is archived here BEFORE the overwrite — so convergence is preserved
+ * (peers still agree on the LWW winner, sync never wedges) AND no edit is
+ * silently lost (the user can review and restore from the Sharing → Conflicts
+ * tab).
+ *
+ * Divergence signal — per-record `syncBaseHash` (the content hash as of the
+ * last time this instance and a peer demonstrably held the same content):
+ *
+ * conflict := base != null
+ * && hLocal !== base // local diverged from the common base
+ * && hRemote !== base // remote also diverged from it
+ * && hLocal !== hRemote // and they actually differ
+ *
+ * `base == null` ⇒ treat as a clean update (conservative: we only ever MISS
+ * journaling the first divergence after this feature ships for a given record,
+ * never wedge and never false-positive on routine sequential updates).
+ *
+ * The base hash advances to the remote's hash on EVERY accepted overwrite
+ * (clean OR conflicting) — without that, the 60s snapshot loop would re-journal
+ * the same unresolved divergence every cycle.
+ *
+ * This store + the base-hash side store are LOCAL-ONLY: they are never enrolled
+ * in PEER_SUBSCRIBABLE_KINDS / snapshot categories / sanitizeStateForWire, so
+ * they can never cross the wire (no schema-version bump needed).
+ */
+
+import { join } from 'path';
+import { randomUUID, createHash } from 'crypto';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';
+import { createCollectionStore } from './collectionStore.js';
+import { canonicalStringify } from './objects.js';
+import { sanitizeRecordForWire } from './syncWire.js';
+
+const JOURNAL_TYPE_SCHEMA_VERSION = 1;
+const BASE_HASH_FILE = () => join(PATHS.data, 'sharing', 'sync_base_hashes.json');
+
+// ---- conflict-journal collection store ----
+
+let _store = null;
+const store = () => {
+ if (_store && _store.dir === join(PATHS.data, 'conflict-journal')) return _store;
+ _store = createCollectionStore({
+ dir: join(PATHS.data, 'conflict-journal'),
+ type: 'conflictJournal',
+ schemaVersion: JOURNAL_TYPE_SCHEMA_VERSION,
+ });
+ return _store;
+};
+export const conflictJournalStore = () => store();
+
+// ---- content hashing (matches the sender/receiver wire convention) ----
+
+/**
+ * sha256 of the canonical wire projection. Reuses sanitizeRecordForWire +
+ * canonicalStringify so the sender hashing what it pushes and the receiver
+ * hashing its local copy agree byte-for-byte. Returns null when the record has
+ * no wire form (ephemeral non-tombstone, or invalid) — callers treat a null
+ * hash as "cannot compare".
+ */
+export function contentHashForRecord(kind, record) {
+ const wire = sanitizeRecordForWire(kind, record);
+ if (!wire) return null;
+ return createHash('sha256').update(canonicalStringify(wire)).digest('hex');
+}
+
+// ---- base-hash side store (in-memory cache, batched write-through) ----
+
+let _baseHashes = null; // Map<`${kind}:${id}`, sha256>
+let _loadPromise = null;
+let _baseDirty = false;
+let _flushTail = Promise.resolve();
+
+const baseKey = (kind, id) => `${kind}:${id}`;
+
+async function ensureBaseLoaded() {
+ if (_baseHashes) return _baseHashes;
+ if (!_loadPromise) {
+ _loadPromise = (async () => {
+ const obj = await readJSONFile(BASE_HASH_FILE(), {}, { logError: false });
+ _baseHashes = new Map(obj && typeof obj === 'object' ? Object.entries(obj) : []);
+ return _baseHashes;
+ })();
+ }
+ return _loadPromise;
+}
+
+export async function getSyncBaseHash(kind, id) {
+ const map = await ensureBaseLoaded();
+ return map.get(baseKey(kind, id)) ?? null;
+}
+
+/** Set the base hash in memory (write-through deferred to flushBaseHashes). */
+export async function setSyncBaseHash(kind, id, hash) {
+ const map = await ensureBaseLoaded();
+ if (!hash) return;
+ if (map.get(baseKey(kind, id)) === hash) return;
+ map.set(baseKey(kind, id), hash);
+ _baseDirty = true;
+}
+
+/** Persist the base-hash map if dirty. Serialized so concurrent flushes can't
+ * interleave file writes. Call once after a merge's write loop. */
+export function flushBaseHashes() {
+ if (!_baseDirty) return _flushTail;
+ _flushTail = _flushTail.then(async () => {
+ if (!_baseDirty) return;
+ _baseDirty = false;
+ const map = await ensureBaseLoaded();
+ await ensureDir(join(PATHS.data, 'sharing'));
+ await atomicWrite(BASE_HASH_FILE(), Object.fromEntries(map));
+ }).catch((err) => {
+ _baseDirty = true; // retry on next flush
+ console.error(`❌ conflictJournal: base-hash flush failed: ${err?.message || err}`);
+ });
+ return _flushTail;
+}
+
+// ---- conflict detection + journaling ----
+
+/**
+ * Detect a true 3-way divergence for a record about to be overwritten.
+ * Returns `{ isConflict, baseHash, localHash, remoteHash }`.
+ */
+export async function detectConflict({ kind, id, local, remote }) {
+ const baseHash = await getSyncBaseHash(kind, id);
+ const localHash = contentHashForRecord(kind, local);
+ const remoteHash = contentHashForRecord(kind, remote);
+ const isConflict = baseHash != null && localHash != null && remoteHash != null
+ && localHash !== baseHash && remoteHash !== baseHash && localHash !== remoteHash;
+ return { isConflict, baseHash, localHash, remoteHash };
+}
+
+// User-authored content fields a restore/merge may write back, per kind. This
+// is the SINGLE SOURCE OF TRUTH — the resolver imports it for its merge-fields
+// allowlist, and diffSummary filters to it so the Conflicts UI only ever offers
+// fields the resolver will accept (server-owned fields like id/createdAt/
+// schemaVersion/locked/origin/deleted are neither restorable nor shown).
+export const RESTORABLE_FIELDS = Object.freeze({
+ universe: ['name', 'starterPrompt', 'logline', 'premise', 'styleNotes', 'categories', 'compositeSheets', 'influences', 'characters', 'places', 'objects'],
+ series: ['name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author', 'stylePromptOverride', 'stylePromptOverrideMode', 'targetFormat', 'issueCountTarget', 'arc', 'seasons'],
+});
+
+// Top-level shallow diff over the kind's restorable content fields — enough for
+// the UI to render "Name, Premise differ" with InlineDiff and offer each as a
+// selectable merge-field. Deep field diffing is a follow-up.
+const diffSummary = (kind, local, remote) => {
+ const fields = RESTORABLE_FIELDS[kind] || [];
+ const out = [];
+ for (const field of fields) {
+ const lv = local?.[field];
+ const rv = remote?.[field];
+ if (canonicalStringify(lv) === canonicalStringify(rv)) continue;
+ const present = (v) => v !== undefined;
+ out.push({
+ field,
+ localValue: lv,
+ remoteValue: rv,
+ changed: present(lv) && present(rv) ? 'both' : (present(rv) ? 'remote-only' : 'local-only'),
+ });
+ }
+ return out;
+};
+
+/**
+ * Archive a losing local version. Writes a `pending` journal entry; returns its
+ * id. Snapshots are stored in sanitized wire form so a later restore re-applies
+ * a clean shape.
+ */
+export async function journalConflict({ kind, id, local, remote, source, hashes }) {
+ const localSnapshot = sanitizeRecordForWire(kind, local) ?? local;
+ const remoteSnapshot = sanitizeRecordForWire(kind, remote) ?? remote;
+ const entry = {
+ id: randomUUID(),
+ recordKind: kind,
+ recordId: id,
+ detectedAt: new Date().toISOString(),
+ source: source || { via: 'unknown', peerId: null, bucketId: null },
+ baseHash: hashes?.baseHash ?? null,
+ localHash: hashes?.localHash ?? null,
+ remoteHash: hashes?.remoteHash ?? null,
+ localSnapshot,
+ remoteSnapshot,
+ localUpdatedAt: local?.updatedAt ?? null,
+ remoteUpdatedAt: remote?.updatedAt ?? null,
+ diffSummary: diffSummary(kind, localSnapshot, remoteSnapshot),
+ status: 'pending',
+ resolvedAt: null,
+ resolution: null,
+ };
+ await store().saveOne(entry.id, entry);
+ console.log(`🪢 conflictJournal: archived ${kind} ${String(id).slice(0, 12)} (source=${entry.source.via})`);
+ return entry.id;
+}
+
+/**
+ * The one call every merge makes RIGHT BEFORE its overwrite. Detects a true
+ * conflict, archives the losing local version if so, and advances the base hash
+ * to the remote's (in memory — caller flushes after its loop). NEVER throws into
+ * the merge — a journal failure logs and the merge proceeds (convergence wins).
+ *
+ * Skips journaling (but still advances base) when there is no local content to
+ * lose: an absent/ephemeral local, or a local tombstone being overwritten.
+ */
+export async function maybeJournalBeforeOverwrite({ kind, id, local, remote, source }) {
+ try {
+ const { isConflict, baseHash, localHash, remoteHash } = await detectConflict({ kind, id, local, remote });
+ const localIsTombstone = local?.deleted === true;
+ if (isConflict && localHash != null && !localIsTombstone) {
+ await journalConflict({ kind, id, local, remote, source, hashes: { baseHash, localHash, remoteHash } });
+ }
+ if (remoteHash != null) await setSyncBaseHash(kind, id, remoteHash);
+ } catch (err) {
+ console.error(`❌ conflictJournal: maybeJournalBeforeOverwrite(${kind}:${id}) failed (proceeding): ${err?.message || err}`);
+ }
+}
+
+// Test-only reset of the in-memory base-hash cache so suites that swap PATHS.data
+// between tests don't bleed state across the module-level cache.
+export function __resetBaseHashCacheForTests() {
+ _baseHashes = null;
+ _loadPromise = null;
+ _baseDirty = false;
+ _flushTail = Promise.resolve();
+ _store = null;
+}
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
new file mode 100644
index 0000000000..ef171822b1
--- /dev/null
+++ b/server/lib/conflictJournal.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from './mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'conflict-journal-test-'));
+
+vi.mock('./fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+const cj = await import('./conflictJournal.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+// Minimal universe-shaped records (sanitizeRecordForWire needs an id; universe
+// adds the soft-delete pair). Distinct content → distinct content hashes.
+const uni = (over = {}) => ({ id: 'u-1', name: 'X', starterPrompt: 'base', updatedAt: '2026-05-01T00:00:00Z', ...over });
+
+const pendingEntries = async () => cj.conflictJournalStore().loadAll();
+
+describe('conflictJournal', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ cj.__resetBaseHashCacheForTests();
+ });
+
+ it('contentHashForRecord is stable and null for an ephemeral non-tombstone', () => {
+ const h1 = cj.contentHashForRecord('universe', uni());
+ const h2 = cj.contentHashForRecord('universe', uni());
+ expect(h1).toBe(h2);
+ expect(cj.contentHashForRecord('universe', uni({ ephemeral: true }))).toBeNull();
+ });
+
+ it('no base → treated as clean (no journal), base seeded for next time', async () => {
+ const local = uni({ starterPrompt: 'local', updatedAt: '2026-05-01T00:00:00Z' });
+ const remote = uni({ starterPrompt: 'remote', updatedAt: '2026-05-02T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'sync' } });
+ await cj.flushBaseHashes();
+ expect(await pendingEntries()).toHaveLength(0);
+ expect(await cj.getSyncBaseHash('universe', 'u-1')).toBe(cj.contentHashForRecord('universe', remote));
+ });
+
+ it('clean sequential update (local == base) → no journal', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ // local untouched since base; remote is a newer edit.
+ const remote = uni({ starterPrompt: 'remote-edit', updatedAt: '2026-05-03T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local: base, remote, source: { via: 'sync' } });
+ expect(await pendingEntries()).toHaveLength(0);
+ });
+
+ it('true 3-way divergence → exactly one journal entry; convergence base advances', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ const local = uni({ starterPrompt: 'LOCAL edit', updatedAt: '2026-05-02T00:00:00Z' }); // diverged
+ const remote = uni({ starterPrompt: 'REMOTE edit', updatedAt: '2026-05-03T00:00:00Z' }); // diverged + newer
+
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'push', peerId: 'peer-A' } });
+ const entries = await pendingEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({ recordKind: 'universe', recordId: 'u-1', status: 'pending' });
+ expect(entries[0].localSnapshot.starterPrompt).toBe('LOCAL edit');
+ expect(entries[0].remoteSnapshot.starterPrompt).toBe('REMOTE edit');
+ expect(entries[0].diffSummary.some((d) => d.field === 'starterPrompt')).toBe(true);
+ // Base advanced to remote → an idempotent replay must NOT re-journal.
+ expect(await cj.getSyncBaseHash('universe', 'u-1')).toBe(cj.contentHashForRecord('universe', remote));
+ });
+
+ it('idempotent snapshot replay does not create a second entry', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ const local = uni({ starterPrompt: 'LOCAL', updatedAt: '2026-05-02T00:00:00Z' });
+ const remote = uni({ starterPrompt: 'REMOTE', updatedAt: '2026-05-03T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'sync' } });
+ // After the (simulated) overwrite, local == remote; replay the same remote.
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local: remote, remote, source: { via: 'sync' } });
+ expect(await pendingEntries()).toHaveLength(1);
+ });
+
+ it('diffSummary surfaces only restorable content fields, never server-owned ones', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ // Differ in a restorable field (starterPrompt) AND a non-restorable one
+ // (schemaVersion). Only the restorable field may be offered to the UI —
+ // otherwise merge-fields would reject the whole request server-side.
+ const local = uni({ starterPrompt: 'LOCAL', schemaVersion: 4, updatedAt: '2026-05-02T00:00:00Z' });
+ const remote = uni({ starterPrompt: 'REMOTE', schemaVersion: 5, updatedAt: '2026-05-03T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'sync' } });
+ const [entry] = await pendingEntries();
+ const fields = entry.diffSummary.map((d) => d.field);
+ expect(fields).toContain('starterPrompt');
+ expect(fields).not.toContain('schemaVersion');
+ expect(fields).not.toContain('id');
+ });
+
+ it('does NOT journal when the local side is a tombstone (no content to lose)', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ const localTombstone = uni({ deleted: true, deletedAt: '2026-05-02T00:00:00Z', updatedAt: '2026-05-02T00:00:00Z' });
+ const remote = uni({ starterPrompt: 'REMOTE', updatedAt: '2026-05-03T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local: localTombstone, remote, source: { via: 'sync' } });
+ expect(await pendingEntries()).toHaveLength(0);
+ });
+
+ it('journals when a remote DELETE would erase a diverged local edit', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ const local = uni({ starterPrompt: 'precious local edit', updatedAt: '2026-05-02T00:00:00Z' });
+ const remoteTombstone = uni({ deleted: true, deletedAt: '2026-05-03T00:00:00Z', updatedAt: '2026-05-03T00:00:00Z' });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote: remoteTombstone, source: { via: 'sync' } });
+ const entries = await pendingEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].localSnapshot.starterPrompt).toBe('precious local edit');
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 13c7034322..a828ac90d6 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -69,6 +69,7 @@ export * from './tuiPromptRunner.js';
// === File & I/O ===
export * from './collectionStore.js';
+export * from './conflictJournal.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './schemaVersions.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 09811ce929..382cf90182 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -22,6 +22,8 @@ export const NAV_COMMANDS = [
{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },
+ { id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },
+ { id: 'nav.create.sharing-conflicts', path: '/sharing/conflicts', label: 'Conflicts', section: 'Create', aliases: ['conflicts', 'sync-conflicts', 'edit-conflicts', 'conflict-journal'], keywords: ['conflict', 'overwrite', 'lost edit', 'restore', 'merge fields', 'last write wins', 'diverged', 'recover'] },
{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },
diff --git a/server/routes/conflictJournal.js b/server/routes/conflictJournal.js
new file mode 100644
index 0000000000..c06f81e80a
--- /dev/null
+++ b/server/routes/conflictJournal.js
@@ -0,0 +1,58 @@
+/**
+ * Conflict-journal routes — list/inspect/resolve the non-blocking edit-conflict
+ * journal. Surfaced in the client's Sharing → Conflicts tab.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as resolver from '../services/conflictJournalResolver.js';
+
+const router = Router();
+
+const SERVICE_ERROR_STATUS = {
+ [resolver.ERR_NOT_FOUND]: 404,
+ [resolver.ERR_VALIDATION]: 400,
+};
+const mapServiceError = (err) => {
+ const status = SERVICE_ERROR_STATUS[err?.code];
+ if (status) return new ServerError(err.message, { status, code: err.code });
+ return err;
+};
+
+// Entries are only ever 'pending' (on archive) or 'resolved' (after the user
+// restores/merges/discards); there is no 'dismissed' state — discard resolves
+// the entry and DELETE hard-removes it. Don't advertise a status the resolver
+// never produces.
+const listQuerySchema = z.object({
+ status: z.enum(['pending', 'resolved']).optional(),
+});
+
+const resolveSchema = z.object({
+ action: z.enum(['restore-all', 'merge-fields', 'discard']),
+ fields: z.array(z.string().min(1).max(64)).max(50).optional(),
+});
+
+router.get('/', asyncHandler(async (req, res) => {
+ const { status } = validateRequest(listQuerySchema, req.query ?? {});
+ res.json({ conflicts: await resolver.listConflicts({ status: status ?? null }) });
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const entry = await resolver.getConflict(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(entry);
+}));
+
+router.post('/:id/resolve', asyncHandler(async (req, res) => {
+ const body = validateRequest(resolveSchema, req.body ?? {});
+ const result = await resolver.resolveConflict(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const result = await resolver.deleteConflict(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/routes/conflictJournal.test.js b/server/routes/conflictJournal.test.js
new file mode 100644
index 0000000000..606e900761
--- /dev/null
+++ b/server/routes/conflictJournal.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const resolverMock = {
+ ERR_NOT_FOUND: 'CONFLICT_JOURNAL_NOT_FOUND',
+ ERR_VALIDATION: 'CONFLICT_JOURNAL_VALIDATION',
+ listConflicts: vi.fn(),
+ getConflict: vi.fn(),
+ resolveConflict: vi.fn(),
+ deleteConflict: vi.fn(),
+};
+vi.mock('../services/conflictJournalResolver.js', () => resolverMock);
+
+const conflictJournalRoutes = (await import('./conflictJournal.js')).default;
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/conflict-journal', conflictJournalRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('conflict-journal routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('GET / lists conflicts (optionally filtered by status)', async () => {
+ resolverMock.listConflicts.mockResolvedValue([{ id: 'e1', status: 'pending' }]);
+ const res = await request(makeApp()).get('/api/conflict-journal?status=pending');
+ expect(res.status).toBe(200);
+ expect(res.body.conflicts).toHaveLength(1);
+ expect(resolverMock.listConflicts).toHaveBeenCalledWith({ status: 'pending' });
+ });
+
+ it('GET / rejects an invalid status with 400', async () => {
+ const res = await request(makeApp()).get('/api/conflict-journal?status=bogus');
+ expect(res.status).toBe(400);
+ });
+
+ it('POST /:id/resolve validates the action enum', async () => {
+ const bad = await request(makeApp()).post('/api/conflict-journal/e1/resolve').send({ action: 'nope' });
+ expect(bad.status).toBe(400);
+
+ resolverMock.resolveConflict.mockResolvedValue({ id: 'e1', status: 'resolved', resolution: 'discard' });
+ const ok = await request(makeApp()).post('/api/conflict-journal/e1/resolve').send({ action: 'discard' });
+ expect(ok.status).toBe(200);
+ expect(resolverMock.resolveConflict).toHaveBeenCalledWith('e1', { action: 'discard' });
+ });
+
+ it('maps ERR_NOT_FOUND to 404', async () => {
+ resolverMock.getConflict.mockRejectedValue(Object.assign(new Error('nope'), { code: resolverMock.ERR_NOT_FOUND }));
+ const res = await request(makeApp()).get('/api/conflict-journal/missing');
+ expect(res.status).toBe(404);
+ });
+
+ it('DELETE /:id removes an entry', async () => {
+ resolverMock.deleteConflict.mockResolvedValue({ id: 'e1', deleted: true });
+ const res = await request(makeApp()).delete('/api/conflict-journal/e1');
+ expect(res.status).toBe(200);
+ expect(res.body.deleted).toBe(true);
+ });
+});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 84c035f697..a73baeded4 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -55,6 +55,8 @@ import {
} from '../services/pipeline/visualStages.js';
import { extractCanonFromProse } from '../services/universeCanon.js';
import { getSeriesCanon } from '../services/pipeline/seriesCanon.js';
+import { findDuplicateSeriesGroups, findSameNameSeries } from '../services/duplicateDetection.js';
+import { mergeSeries } from '../services/recordMerge.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
import { generateSeriesTitleLogo } from '../services/pipeline/seriesTitleLogo.js';
import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../services/pipeline/owners.js';
@@ -112,6 +114,8 @@ const SERVICE_ERROR_STATUS = {
[ERR_NO_RENDERED_PAGES]: 409,
[ERR_NO_VOLUME_COVER]: 409,
[ERR_NO_RENDERED_ISSUES]: 409,
+ // recordMerge validation (unresolved conflicts, bad ids, cross-universe).
+ MERGE_VALIDATION: 400,
};
const mapServiceError = (err) => {
@@ -843,7 +847,46 @@ router.get('/series', asyncHandler(async (_req, res) => {
router.post('/series', asyncHandler(async (req, res) => {
const body = validateRequest(seriesCreateSchema, req.body ?? {});
- res.status(201).json(await seriesSvc.createSeries(body));
+ // Hierarchy invariant: every series belongs to exactly one universe. Enforce
+ // it for all HTTP callers here (the UI already enforces it client-side).
+ // The schema stays permissive (nullable) so the importer + mergeSeriesFromSync,
+ // which call createSeries directly, can still land legacy orphans from peers.
+ if (!body.universeId || !String(body.universeId).trim()) {
+ throw new ServerError('A universe is required — a series must belong to a universe.', {
+ status: 400, code: seriesSvc.ERR_VALIDATION,
+ });
+ }
+ const created = await seriesSvc.createSeries(body);
+ // Non-blocking same-name warning, scoped within the universe (route layer
+ // only, so the importer's direct createSeries never pays for the scan).
+ const duplicateName = await findSameNameSeries(created.name, created.universeId, { excludeId: created.id });
+ res.status(201).json(duplicateName.length ? { ...created, _warnings: { duplicateName } } : created);
+}));
+
+// ---- Series duplicate resolution (static paths — keep BEFORE `/series/:id`) ----
+
+const seriesMergeSchema = z.object({
+ survivorId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),
+ loserId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),
+ fieldChoices: z.record(z.enum(['survivor', 'loser'])).optional().default({}),
+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });
+
+router.get('/series/duplicates', asyncHandler(async (_req, res) => {
+ res.json(await findDuplicateSeriesGroups());
+}));
+
+router.post('/series/merge/preview', asyncHandler(async (req, res) => {
+ const body = validateRequest(seriesMergeSchema, req.body ?? {});
+ const preview = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true })
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(preview);
+}));
+
+router.post('/series/merge', asyncHandler(async (req, res) => {
+ const body = validateRequest(seriesMergeSchema, req.body ?? {});
+ const result = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
}));
router.get('/series/:id', asyncHandler(async (req, res) => {
@@ -854,6 +897,10 @@ router.get('/series/:id', asyncHandler(async (req, res) => {
router.patch('/series/:id', asyncHandler(async (req, res) => {
const body = validateRequest(seriesPatchSchema, req.body ?? {});
const s = await seriesSvc.updateSeries(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ if ('name' in body || 'universeId' in body) {
+ const duplicateName = await findSameNameSeries(s.name, s.universeId, { excludeId: req.params.id });
+ if (duplicateName.length) { res.json({ ...s, _warnings: { duplicateName } }); return; }
+ }
res.json(s);
}));
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 7c200f6742..aa4a46257d 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -294,6 +294,7 @@ describe('pipeline routes', () => {
const app = makeApp();
const r = await request(app).post('/api/pipeline/series').send({
name: 'Salt Run',
+ universeId: 'u-test',
logline: 'A foundry city goes silent.',
premise: 'Long premise...',
styleNotes: 'moebius linework',
@@ -309,6 +310,32 @@ describe('pipeline routes', () => {
expect(r.status).toBe(400);
});
+ it('POST /series rejects a missing universe with 400 (hierarchy invariant)', async () => {
+ const app = makeApp();
+ const noUni = await request(app).post('/api/pipeline/series').send({ name: 'Orphan' });
+ expect(noUni.status).toBe(400);
+ const emptyUni = await request(app).post('/api/pipeline/series').send({ name: 'Orphan', universeId: ' ' });
+ expect(emptyUni.status).toBe(400);
+ const nullUni = await request(app).post('/api/pipeline/series').send({ name: 'Orphan', universeId: null });
+ expect(nullUni.status).toBe(400);
+ });
+
+ it('GET /series/duplicates returns grouped shape (static path not swallowed by /:id)', async () => {
+ const app = makeApp();
+ const res = await request(app).get('/api/pipeline/series/duplicates');
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveProperty('series');
+ expect(res.body).toHaveProperty('orphans');
+ });
+
+ it('POST /series/merge rejects identical survivor/loser ids with 400', async () => {
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/pipeline/series/merge')
+ .send({ survivorId: 'ser-1', loserId: 'ser-1' });
+ expect(res.status).toBe(400);
+ });
+
it('PATCH /series/:id 404s for unknown id', async () => {
const app = makeApp();
const r = await request(app).patch('/api/pipeline/series/ser-nope').send({ name: 'x' });
@@ -317,7 +344,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/issues creates an issue under the series', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Pilot' });
expect(r.status).toBe(201);
expect(r.body.id).toMatch(/^iss-/);
@@ -334,7 +361,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/:stageId/generate runs a text stage', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/idea/generate`).send({ seedInput: 'foundry mystery' });
expect(r.status).toBe(200);
@@ -344,7 +371,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/:stageId/generate rejects visual stages', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/generate`).send({});
expect(r.status).toBe(400);
@@ -354,7 +381,7 @@ describe('pipeline routes', () => {
describe('POST /issues/:id/stages/:stageId/restore', () => {
it('restores a prior runHistory snapshot and snapshots the displaced current state', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const issueId = iss.body.id;
// First run → no snapshot yet.
@@ -381,7 +408,7 @@ describe('pipeline routes', () => {
it('rejects when the runId is not in the current snapshot list', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/idea/restore`)
@@ -391,7 +418,7 @@ describe('pipeline routes', () => {
it('rejects non-text stages', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/restore`)
@@ -401,7 +428,7 @@ describe('pipeline routes', () => {
it('rejects empty runId via Zod', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/idea/restore`)
@@ -412,7 +439,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/visual enqueues an image job', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/visual`)
@@ -424,7 +451,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/episodeVideo/visual hands off to Creative Director', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/episodeVideo/visual`)
@@ -440,7 +467,7 @@ describe('pipeline routes', () => {
throw Object.assign(new Error('Storyboards stage has no scenes with descriptions.'), { code: 'PIPELINE_EPISODE_NO_STORYBOARDS' });
});
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/episodeVideo/visual`)
@@ -450,7 +477,7 @@ describe('pipeline routes', () => {
it('GET /issues/recent?limit=0 clamps to 1 (route forwards to service which owns coercion)', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'A' });
await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'B' });
const r = await request(app).get('/api/pipeline/issues/recent?limit=0');
@@ -462,8 +489,8 @@ describe('pipeline routes', () => {
it('GET /issues/recent returns the most-recently-updated issues with denormalized seriesName', async () => {
const app = makeApp();
- const ser1 = await request(app).post('/api/pipeline/series').send({ name: 'Alpha' });
- const ser2 = await request(app).post('/api/pipeline/series').send({ name: 'Beta' });
+ const ser1 = await request(app).post('/api/pipeline/series').send({ name: 'Alpha', universeId: 'u-test' });
+ const ser2 = await request(app).post('/api/pipeline/series').send({ name: 'Beta', universeId: 'u-test' });
const iss1 = await request(app).post(`/api/pipeline/series/${ser1.body.id}/issues`).send({ title: 'Old' });
// Bump iss1's updatedAt back so iss2 is unambiguously the most recent.
await new Promise((r) => setTimeout(r, 10));
@@ -481,7 +508,7 @@ describe('pipeline routes', () => {
// re-introduce stage runHistory on list payloads.
describe('list endpoints strip runHistory at the HTTP boundary', () => {
async function seedIssueWithHistory(app) {
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/idea/generate`).send({ seedInput: 'v1' });
const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/idea/generate`).send({ seedInput: 'v2' });
@@ -512,7 +539,7 @@ describe('pipeline routes', () => {
const app = makeApp();
// Tiny seed so the response is non-empty and we can assert the
// route's `stages`-dropping projection actually holds.
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'T' });
const spy = vi.spyOn(issuesSvc, 'listRecentIssues');
const r = await request(app).get('/api/pipeline/issues/recent?limit=5');
@@ -526,7 +553,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/scenes/:index/video returns the enqueued jobId', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/0/video`)
@@ -538,7 +565,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/scenes/:index/video rejects a non-integer index', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/nope/video`)
@@ -548,7 +575,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/scenes/:sceneIndex/shots/:shotIndex/render returns the enqueued jobId', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/0/shots/2/render`)
@@ -561,7 +588,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/scenes/:sceneIndex/shots/:shotIndex/render rejects bad indices', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/nope/shots/0/render`)
@@ -571,7 +598,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/pages/:p/panels/:n/refine-prompt returns the refined panel + changes', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/0/panels/0/refine-prompt`)
@@ -584,7 +611,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/scenes/:index/refine-prompt returns the refined scene', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/0/refine-prompt`)
@@ -596,7 +623,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/auto-run-text returns runId + sseUrl', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/auto-run-text`).send({});
expect(r.status).toBe(200);
@@ -614,7 +641,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/extract-scenes 400s when the source stage is empty', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
@@ -625,7 +652,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/storyboards/extract-scenes 409s when scenes already exist (no force)', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -704,7 +731,7 @@ describe('pipeline routes', () => {
});
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: { prose: { status: 'ready', output: 'Once upon a time, a paragraph happened.' } },
@@ -731,7 +758,7 @@ describe('pipeline routes', () => {
});
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -753,7 +780,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages 400s when comicScript is empty', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)
@@ -764,7 +791,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages 409s when comicPages already has pages (no force)', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -781,7 +808,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages parses comicScript output and persists pages', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const script = [
'## Page 1',
@@ -830,7 +857,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages with force=true replaces existing pages', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -848,7 +875,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages seeds blank cover.script from parsed coverConcept', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const script = [
'## Cover concept',
@@ -879,7 +906,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/extract-pages does not clobber an existing cover.script', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const script = [
'## Cover concept',
@@ -913,7 +940,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/:stageId/extract-canon 400s when stage is not comicScript or teleplay', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/prose/extract-canon`)
@@ -924,7 +951,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/:stageId/extract-canon 400s when the script stage is empty', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicScript/extract-canon`)
@@ -935,8 +962,12 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/:stageId/extract-canon 400s when series has no linked universe', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ // The POST /series route now requires a universe, but legacy/imported
+ // orphan series can still exist on disk — create one via the (permissive)
+ // service directly to exercise the extract-canon no-universe guard.
+ const seriesSvc = await import('../services/pipeline/series.js');
+ const ser = await seriesSvc.createSeries({ name: 'S', universeId: null });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: { comicScript: { status: 'ready', output: '## Page 1\n\n### Panel 1\n**Description:** A barkeep slides a glass.' } },
});
@@ -1053,7 +1084,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 400s for a non-integer pageIndex', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/pages/abc/render`)
@@ -1064,7 +1095,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render persists imageJobId + prompt onto the target page', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -1099,7 +1130,7 @@ describe('pipeline routes', () => {
// bubble a generic Error.
const visualStages = await import('../services/pipeline/visualStages.js');
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: { comicPages: { pages: [] } },
@@ -1117,7 +1148,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/cover/render returns jobId + prompt and persists cover on the issue', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)
@@ -1146,7 +1177,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/cover/render 400s when the body fails schema validation', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
// `width` must be an integer; sending a string triggers Zod validation failure.
const r = await request(app)
@@ -1165,7 +1196,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/cover/render target=final + useProofAsBase=true persists onto finalImage with fromProof:true, leaving the prior proof slot untouched', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
// Seed a prior proof via the render route (the PATCH /issues schema strips
// unknown cover fields, so proofImage can only land here via render).
@@ -1191,7 +1222,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render target=final + useProofAsBase=true persists onto pages[i].finalImage with fromProof:true, leaving the prior proof slot untouched', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -1220,7 +1251,7 @@ describe('pipeline routes', () => {
it('POST page+cover render schemas reject invalid `target` enum values with 400', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
// Zod enum on comicPageRenderSchema rejects before the service dispatches,
// so no pages-seeding is needed — validation happens on body parse.
@@ -1243,7 +1274,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/cover/render preserves persisted cover.script when body omits coverScript', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
// Seed the script via a first render carrying it.
const first = await request(app)
@@ -1262,7 +1293,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/cover/render clears cover.script when body carries empty string', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)
@@ -1277,7 +1308,7 @@ describe('pipeline routes', () => {
it('POST /issues/:id/stages/comicPages/back-cover/render preserves persisted backCover.script when body omits backCoverScript', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const first = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/back-cover/render`)
@@ -1299,7 +1330,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons/:seasonId/cover/render preserves persisted cover.script when body omits coverScript', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Vol 1' });
const first = await request(app)
.post(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}/cover/render`)
@@ -1320,7 +1351,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons/:seasonId/back-cover/render preserves persisted backCover.script when body omits backCoverScript', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Vol 1' });
const first = await request(app)
.post(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}/back-cover/render`)
@@ -1345,7 +1376,7 @@ describe('pipeline routes', () => {
it('GET /series/:id/seasons returns [] for a fresh series', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r = await request(app).get(`/api/pipeline/series/${ser.body.id}/seasons`);
expect(r.status).toBe(200);
expect(r.body).toEqual([]);
@@ -1359,7 +1390,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons creates a season and auto-numbers it', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r1 = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
expect(r1.status).toBe(201);
expect(r1.body.id).toMatch(/^sea-/);
@@ -1370,14 +1401,14 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons rejects entry with neither title nor number', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({});
expect(r.status).toBe(400);
});
it('PATCH /series/:id/seasons/:seasonId updates fields', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
const r = await request(app)
.patch(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}`)
@@ -1390,7 +1421,7 @@ describe('pipeline routes', () => {
it('PATCH /series/:id/seasons/:seasonId 404s for unknown season', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r = await request(app)
.patch(`/api/pipeline/series/${ser.body.id}/seasons/sea-nope`)
.send({ title: 'x' });
@@ -1399,7 +1430,7 @@ describe('pipeline routes', () => {
it('DELETE /series/:id/seasons/:seasonId un-groups child issues by default', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({ seasonId: sea.body.id, arcPosition: 1 });
@@ -1414,7 +1445,7 @@ describe('pipeline routes', () => {
it('DELETE /series/:id/seasons/:seasonId reassigns child issues to reassignTo sibling', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const a = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
const b = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Hiatus' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
@@ -1431,7 +1462,7 @@ describe('pipeline routes', () => {
it('DELETE /series/:id/seasons/:seasonId 400s when reassignTo points at non-existent sibling', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
const r = await request(app).delete(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}`)
.send({ reassignTo: 'sea-ghost' });
@@ -1440,7 +1471,7 @@ describe('pipeline routes', () => {
it('PATCH /issues/:id accepts seasonId + arcPosition', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`)
@@ -1452,7 +1483,7 @@ describe('pipeline routes', () => {
it('PATCH /issues/:id preserves per-stage locked flags through validation', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`)
.send({ stages: { idea: { locked: true } } });
@@ -1463,7 +1494,7 @@ describe('pipeline routes', () => {
it('PATCH /series/:id accepts arc payload', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const r = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
arc: { logline: 'Big-picture pitch', themes: ['legacy', 'betrayal'], status: 'draft' },
});
@@ -1479,6 +1510,7 @@ describe('pipeline routes', () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({
name: 'S',
+ universeId: 'u-test',
locked: { arcFields: { logline: true } },
});
const r = await request(app)
@@ -1494,7 +1526,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/arc/generate returns preview without committing by default', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run', universeId: 'u-test' });
arcGenerateSpy = vi.fn(async () => ({
arc: { logline: 'Whole-arc pitch', summary: 'sum', themes: ['legacy'], protagonistArc: 'P', status: 'draft' },
seasons: [{ id: 'sea-1', number: 1, title: 'Pilot' }],
@@ -1517,7 +1549,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/arc/generate with commit:true persists arc + seasons', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run', universeId: 'u-test' });
arcGenerateSpy = vi.fn(async () => ({
arc: { logline: 'Pitch', summary: 'sum', themes: [], protagonistArc: '', status: 'draft' },
seasons: [
@@ -1539,7 +1571,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons/:seasonId/episodes/generate returns preview without committing', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({
title: 'Pilot', synopsis: 'season synopsis',
});
@@ -1566,7 +1598,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons/:seasonId/episodes/generate with commit:true creates one issue per episode', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({
title: 'Pilot', synopsis: 'season synopsis',
});
@@ -1599,7 +1631,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/arc/verify forwards to the planner and returns issues', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
arcVerifySpy = vi.fn(async () => ({
issues: [
{ severity: 'high', location: 'season:2/episode:5', problem: 'character is dead in S1', suggestion: 'remove from S2' },
@@ -1614,7 +1646,7 @@ describe('pipeline routes', () => {
it('POST /series/:id/seasons/:seasonId/verify forwards to the volume verifier', async () => {
const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
volumeVerifySpy = vi.fn(async (_seriesId, seasonId) => ({
issues: [
{ severity: 'medium', location: 'episode:3', problem: 'beats plateau', suggestion: 'escalate ep 3' },
@@ -1632,7 +1664,7 @@ describe('pipeline routes', () => {
describe('audio stage routes', () => {
async function seedIssueWithStoryboards(app) {
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
stages: {
@@ -1726,7 +1758,7 @@ describe('pipeline routes', () => {
});
async function seedIssue(app) {
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
return iss.body;
}
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index c7144c4bae..44932c535a 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -33,6 +33,8 @@ import { autoSortOtherBuckets } from '../services/universeBuilderAutoSort.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
+import { findDuplicateUniverseGroups, findSameNameUniverses } from '../services/duplicateDetection.js';
+import { mergeUniverses } from '../services/recordMerge.js';
import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
import { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/modes.js';
@@ -44,11 +46,22 @@ const router = Router();
const SERVICE_ERROR_STATUS = {
[svc.ERR_NOT_FOUND]: 404,
[svc.ERR_VALIDATION]: 400,
+ // Block-until-empty: deleting a universe with live series → 409 (the
+ // lock-conflict idiom) so the client can show "move these N series first".
+ [svc.ERR_HAS_LIVE_SERIES]: 409,
+ // recordMerge validation (unresolved conflicts, bad ids).
+ MERGE_VALIDATION: 400,
};
const mapServiceError = (err) => {
const status = SERVICE_ERROR_STATUS[err?.code];
- if (status) return new ServerError(err.message, { status, code: err.code });
+ if (status) {
+ // Propagate the blocking-series list (if any) so the UI can list which
+ // series block the delete — rides in `context`, which the error handler
+ // serializes onto the response body.
+ const context = err?.blockingSeries ? { blockingSeries: err.blockingSeries } : undefined;
+ return new ServerError(err.message, { status, code: err.code, context });
+ }
return err;
};
@@ -354,7 +367,12 @@ router.get('/', asyncHandler(async (_req, res) => {
router.post('/', asyncHandler(async (req, res) => {
const body = validateRequest(createSchema, req.body ?? {});
- res.status(201).json(await svc.createUniverse(body));
+ const created = await svc.createUniverse(body);
+ // Non-blocking same-name warning (computed at the route layer so the importer,
+ // which calls the service directly, never pays for the scan). The UI surfaces
+ // it but may proceed — duplicates are resolved later via Sharing → Duplicates.
+ const duplicateName = await findSameNameUniverses(created.name, { excludeId: created.id });
+ res.status(201).json(duplicateName.length ? { ...created, _warnings: { duplicateName } } : created);
}));
// `expand` is a sub-resource — keep it ahead of `/:id` so the wildcard
@@ -386,6 +404,32 @@ router.get('/reference-sheet-variants', asyncHandler(async (_req, res) => {
res.json({ variants: listSheetVariants() });
}));
+// ---- Duplicate resolution (static paths — keep BEFORE `/:id`) ----
+
+const mergeSchema = z.object({
+ survivorId: z.string().trim().min(1).max(128),
+ loserId: z.string().trim().min(1).max(128),
+ fieldChoices: z.record(z.enum(['survivor', 'loser'])).optional().default({}),
+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });
+
+router.get('/duplicates', asyncHandler(async (_req, res) => {
+ res.json({ groups: await findDuplicateUniverseGroups() });
+}));
+
+router.post('/merge/preview', asyncHandler(async (req, res) => {
+ const body = validateRequest(mergeSchema, req.body ?? {});
+ const preview = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true })
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(preview);
+}));
+
+router.post('/merge', asyncHandler(async (req, res) => {
+ const body = validateRequest(mergeSchema, req.body ?? {});
+ const result = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
const w = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
// Lazy stale-reference-sheet collapse: nulls out any character.referenceSheetImageRef
@@ -402,6 +446,11 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.patch('/:id', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.body ?? {});
const w = await svc.updateUniverse(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ // Re-check the same-name warning when the rename actually changed the name.
+ if ('name' in body) {
+ const duplicateName = await findSameNameUniverses(w.name, { excludeId: req.params.id });
+ if (duplicateName.length) { res.json({ ...w, _warnings: { duplicateName } }); return; }
+ }
res.json(w);
}));
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index a86e86bc7a..0a76e01d96 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -149,6 +149,11 @@ vi.mock('../services/mediaCollections.js', () => ({
// cascade pattern above (behavior is covered in mediaCollections.test.js).
unlinkCollectionsForUniverse: vi.fn(async () => []),
universeCollectionNameFor: (name) => `Universe: ${name || ''}`.slice(0, 80),
+ // Read by duplicateDetection (linked-collection item counts) + recordMerge.
+ listCollections: vi.fn(async () => []),
+ findCollectionByUniverseId: vi.fn(async () => null),
+ bulkUpdateCollectionItems: vi.fn(async () => ({})),
+ deleteCollection: vi.fn(async () => ({})),
ERR_DUPLICATE: 'DUPLICATE',
NAME_MAX_LENGTH: 80,
}));
@@ -866,4 +871,19 @@ describe('universe-builder routes', () => {
expect(res.body.variants[1].id).toBe('blueprint');
});
});
+
+ describe('duplicate resolution routes', () => {
+ it('GET /duplicates returns { groups: [] } (static path not swallowed by /:id)', async () => {
+ const res = await request(buildApp()).get('/api/universe-builder/duplicates');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ groups: [] });
+ });
+
+ it('POST /merge rejects identical survivor/loser ids with 400', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/merge')
+ .send({ survivorId: 'u-1', loserId: 'u-1' });
+ expect(res.status).toBe(400);
+ });
+ });
});
diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.js
new file mode 100644
index 0000000000..8350525f78
--- /dev/null
+++ b/server/services/conflictJournalResolver.js
@@ -0,0 +1,107 @@
+/**
+ * Resolve entries in the non-blocking conflict journal (server/lib/conflictJournal.js).
+ *
+ * Each entry archives a local version that LWW overwrote. Resolution:
+ * - restore-all — re-apply the archived local snapshot's restorable fields as
+ * a fresh edit (bumped updatedAt) so it wins LWW and
+ * re-propagates to peers.
+ * - merge-fields — overlay only the chosen fields from the snapshot onto the
+ * CURRENT live record (it may have moved since detection).
+ * - discard — keep the current record; just mark the entry resolved.
+ *
+ * Writes ALWAYS go through the normal `update*` service path (never the record
+ * file directly) so updatedAt bumps and the change propagates via the existing
+ * push pipeline.
+ *
+ * NOTE — restore-all is an ADDITIVE overlay, not a byte-for-byte rollback.
+ * updateUniverse merges some fields per-key rather than replacing them wholesale
+ * (notably `categories`: a partial patch unions keys so an unrelated category
+ * isn't wiped — see universeBuilder.js mergedCategories). So restoring a snapshot
+ * re-applies the archived values for every restorable field, but a category the
+ * snapshot lacked that the live record gained since detection is preserved, not
+ * removed. This is intentional: union-on-restore can't silently destroy data the
+ * journal never captured. The UI labels it "restore" (re-apply mine), not a
+ * destructive "revert to exact snapshot."
+ */
+
+import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.js';
+import { updateUniverse } from './universeBuilder.js';
+import { updateSeries } from './pipeline/series.js';
+
+export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';
+export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+// RESTORABLE_FIELDS (the user-authored content fields a restore/merge may write
+// per kind; id/createdAt/server-owned fields are never overlaid) is owned by
+// conflictJournal.js so diffSummary and this validator stay in lockstep.
+
+const pick = (obj, fields) => {
+ const out = {};
+ for (const f of fields) if (obj && f in obj) out[f] = obj[f];
+ return out;
+};
+
+const store = () => conflictJournalStore();
+
+export async function listConflicts({ status = null } = {}) {
+ const all = await store().loadAll();
+ const filtered = status ? all.filter((e) => e.status === status) : all;
+ return [...filtered].sort((a, b) => (b.detectedAt || '').localeCompare(a.detectedAt || ''));
+}
+
+export async function getConflict(id) {
+ const entry = await store().loadOne(id);
+ if (!entry) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);
+ return entry;
+}
+
+// Apply a content patch through the right service's normal update path.
+async function applyToRecord(kind, recordId, patch) {
+ if (kind === 'universe') {
+ // Mutator form bypasses the literal-patch reference-sheet preservation
+ // guard — the restored snapshot is the trusted writer here.
+ await updateUniverse(recordId, () => patch);
+ } else if (kind === 'series') {
+ await updateSeries(recordId, patch);
+ } else {
+ throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);
+ }
+}
+
+/**
+ * Resolve a conflict entry. `action` ∈ restore-all | merge-fields | discard.
+ * `fields` (merge-fields only) selects which snapshot fields to overlay.
+ */
+export async function resolveConflict(id, { action, fields = [] } = {}) {
+ const entry = await getConflict(id);
+ if (entry.status !== 'pending') throw makeErr(`Conflict already ${entry.status}`, ERR_VALIDATION);
+ const allowed = RESTORABLE_FIELDS[entry.recordKind];
+ if (!allowed) throw makeErr(`Unsupported conflict kind: ${entry.recordKind}`, ERR_VALIDATION);
+ const snapshot = entry.localSnapshot || {};
+
+ if (action === 'restore-all') {
+ await applyToRecord(entry.recordKind, entry.recordId, pick(snapshot, allowed));
+ } else if (action === 'merge-fields') {
+ if (!Array.isArray(fields) || fields.length === 0) {
+ throw makeErr('merge-fields requires a non-empty `fields` array', ERR_VALIDATION);
+ }
+ const invalid = fields.filter((f) => !allowed.includes(f));
+ if (invalid.length) throw makeErr(`Not restorable: ${invalid.join(', ')}`, ERR_VALIDATION);
+ await applyToRecord(entry.recordKind, entry.recordId, pick(snapshot, fields));
+ } else if (action !== 'discard') {
+ throw makeErr(`Unknown resolution action: ${action}`, ERR_VALIDATION);
+ }
+
+ const resolved = { ...entry, status: 'resolved', resolution: action, resolvedAt: new Date().toISOString() };
+ await store().saveOne(id, resolved);
+ console.log(`🪢 conflictJournal: resolved ${id.slice(0, 12)} via ${action}`);
+ return resolved;
+}
+
+/** Permanently remove a journal entry (the "dismiss / clear" action). */
+export async function deleteConflict(id) {
+ await getConflict(id); // 404 if missing
+ await store().deleteOne(id);
+ return { id, deleted: true };
+}
diff --git a/server/services/conflictJournalResolver.test.js b/server/services/conflictJournalResolver.test.js
new file mode 100644
index 0000000000..3dc30a435e
--- /dev/null
+++ b/server/services/conflictJournalResolver.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mockNoPeerSync, mockNoPeers, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'cj-resolver-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+vi.mock('./instances.js', () => mockNoPeers());
+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${String(++uuidCounter).padStart(8, '0')}` };
+});
+
+const resolver = await import('./conflictJournalResolver.js');
+const universeSvc = await import('./universeBuilder.js');
+const cj = await import('../lib/conflictJournal.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+// Seed a pending journal entry whose localSnapshot holds the "lost" values.
+const seedEntry = async (recordId, localSnapshot) => {
+ const id = `entry-${++uuidCounter}`;
+ await cj.conflictJournalStore().saveOne(id, {
+ id, recordKind: 'universe', recordId, detectedAt: '2026-05-01T00:00:00Z',
+ source: { via: 'sync' }, baseHash: 'b', localHash: 'l', remoteHash: 'r',
+ localSnapshot, remoteSnapshot: {}, localUpdatedAt: null, remoteUpdatedAt: null,
+ diffSummary: [], status: 'pending', resolvedAt: null, resolution: null,
+ });
+ return id;
+};
+
+describe('conflictJournalResolver', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ uuidCounter = 0;
+ cj.__resetBaseHashCacheForTests();
+ });
+
+ it('restore-all re-applies the archived snapshot content (bumps updatedAt)', async () => {
+ const u = await universeSvc.createUniverse({ name: 'Clandestiny', starterPrompt: 'REMOTE won' });
+ const entryId = await seedEntry(u.id, { id: u.id, name: 'Clandestiny', starterPrompt: 'MY local prompt' });
+
+ const resolved = await resolver.resolveConflict(entryId, { action: 'restore-all' });
+ expect(resolved.status).toBe('resolved');
+ expect(resolved.resolution).toBe('restore-all');
+
+ const fresh = await universeSvc.getUniverse(u.id);
+ expect(fresh.starterPrompt).toBe('MY local prompt');
+ expect(fresh.updatedAt >= u.updatedAt).toBe(true);
+ });
+
+ it('merge-fields overlays only the chosen fields onto the current record', async () => {
+ const u = await universeSvc.createUniverse({ name: 'Keep', starterPrompt: 'REMOTE prompt', logline: 'remote logline' });
+ const entryId = await seedEntry(u.id, { id: u.id, name: 'Keep', starterPrompt: 'local prompt', logline: 'local logline' });
+
+ await resolver.resolveConflict(entryId, { action: 'merge-fields', fields: ['logline'] });
+ const fresh = await universeSvc.getUniverse(u.id);
+ expect(fresh.logline).toBe('local logline'); // overlaid
+ expect(fresh.starterPrompt).toBe('REMOTE prompt'); // untouched
+ });
+
+ it('merge-fields rejects fields outside the restorable allowlist', async () => {
+ const u = await universeSvc.createUniverse({ name: 'X' });
+ const entryId = await seedEntry(u.id, { id: u.id, name: 'X' });
+ await expect(resolver.resolveConflict(entryId, { action: 'merge-fields', fields: ['id'] }))
+ .rejects.toMatchObject({ code: resolver.ERR_VALIDATION });
+ });
+
+ it('discard marks resolved without touching the record', async () => {
+ const u = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'REMOTE' });
+ const entryId = await seedEntry(u.id, { id: u.id, name: 'X', starterPrompt: 'local' });
+ await resolver.resolveConflict(entryId, { action: 'discard' });
+ expect((await universeSvc.getUniverse(u.id)).starterPrompt).toBe('REMOTE');
+ expect((await resolver.getConflict(entryId)).status).toBe('resolved');
+ });
+
+ it('re-resolving an already-resolved entry fails', async () => {
+ const u = await universeSvc.createUniverse({ name: 'X' });
+ const entryId = await seedEntry(u.id, { id: u.id, name: 'X' });
+ await resolver.resolveConflict(entryId, { action: 'discard' });
+ await expect(resolver.resolveConflict(entryId, { action: 'discard' }))
+ .rejects.toMatchObject({ code: resolver.ERR_VALIDATION });
+ });
+
+ it('listConflicts filters by status; deleteConflict removes the entry', async () => {
+ const u = await universeSvc.createUniverse({ name: 'X' });
+ const e1 = await seedEntry(u.id, { id: u.id, name: 'X' });
+ expect(await resolver.listConflicts({ status: 'pending' })).toHaveLength(1);
+ await resolver.deleteConflict(e1);
+ expect(await resolver.listConflicts()).toHaveLength(0);
+ await expect(resolver.getConflict(e1)).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });
+ });
+});
diff --git a/server/services/duplicateDetection.js b/server/services/duplicateDetection.js
new file mode 100644
index 0000000000..08ece28d36
Binary files /dev/null and b/server/services/duplicateDetection.js differ
diff --git a/server/services/duplicateDetection.test.js b/server/services/duplicateDetection.test.js
new file mode 100644
index 0000000000..c5f2ef3d84
--- /dev/null
+++ b/server/services/duplicateDetection.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mockNoPeerSync, mockNoPeers, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'dup-detect-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+vi.mock('./instances.js', () => mockNoPeers());
+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${String(++uuidCounter).padStart(8, '0')}` };
+});
+
+const universeSvc = await import('./universeBuilder.js');
+const seriesSvc = await import('./pipeline/series.js');
+const dup = await import('./duplicateDetection.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('duplicateDetection', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ uuidCounter = 0;
+ });
+
+ describe('findDuplicateUniverseGroups', () => {
+ it('groups universes by normalized (case/whitespace-insensitive) name', async () => {
+ await universeSvc.createUniverse({ name: 'Clandestiny' });
+ await universeSvc.createUniverse({ name: ' clandestiny ' });
+ await universeSvc.createUniverse({ name: 'Echoes of the Choir' });
+
+ const groups = await dup.findDuplicateUniverseGroups();
+ expect(groups).toHaveLength(1);
+ expect(groups[0].normalizedName).toBe('clandestiny');
+ expect(groups[0].records).toHaveLength(2);
+ // Each record carries counts for the survivor-suggestion UI.
+ expect(groups[0].records[0].counts).toHaveProperty('characters');
+ });
+
+ it('excludes deleted and ephemeral universes', async () => {
+ const a = await universeSvc.createUniverse({ name: 'Dup' });
+ await universeSvc.createUniverse({ name: 'Dup' });
+ const eph = await universeSvc.createUniverse({ name: 'Dup', ephemeral: true });
+ // Three "Dup" exist, but deleting one and ephemeral-marking another leaves
+ // only a single live non-ephemeral → no duplicate group.
+ await universeSvc.deleteUniverse(a.id);
+ expect(eph.ephemeral).toBe(true);
+ const groups = await dup.findDuplicateUniverseGroups();
+ expect(groups).toEqual([]);
+ });
+
+ it('reports linkedSeriesCount per universe', async () => {
+ const u1 = await universeSvc.createUniverse({ name: 'WithSeries' });
+ await universeSvc.createUniverse({ name: 'WithSeries' });
+ await seriesSvc.createSeries({ name: 'A', universeId: u1.id });
+ await seriesSvc.createSeries({ name: 'B', universeId: u1.id });
+ const groups = await dup.findDuplicateUniverseGroups();
+ const rec = groups[0].records.find((r) => r.id === u1.id);
+ expect(rec.linkedSeriesCount).toBe(2);
+ });
+ });
+
+ describe('findDuplicateSeriesGroups', () => {
+ it('groups same-name series WITHIN a universe, not across universes', async () => {
+ const u1 = await universeSvc.createUniverse({ name: 'U1' });
+ const u2 = await universeSvc.createUniverse({ name: 'U2' });
+ await seriesSvc.createSeries({ name: 'Salt Run', universeId: u1.id });
+ await seriesSvc.createSeries({ name: 'Salt Run', universeId: u1.id }); // dup within u1
+ await seriesSvc.createSeries({ name: 'Salt Run', universeId: u2.id }); // NOT a dup (diff universe)
+
+ const { series } = await dup.findDuplicateSeriesGroups();
+ expect(series).toHaveLength(1);
+ expect(series[0].universeId).toBe(u1.id);
+ expect(series[0].records).toHaveLength(2);
+ });
+
+ it('surfaces orphan series in a separate marked bucket (never merged across null)', async () => {
+ // Orphans can only be created via the service (route forbids it).
+ await seriesSvc.createSeries({ name: 'Lonely', universeId: null });
+ await seriesSvc.createSeries({ name: 'Lonely', universeId: null });
+ const { series, orphans, orphanCount } = await dup.findDuplicateSeriesGroups();
+ expect(series).toEqual([]);
+ expect(orphanCount).toBe(2);
+ expect(orphans).toHaveLength(1);
+ expect(orphans[0].normalizedName).toBe('lonely');
+ });
+ });
+
+ describe('same-name create warning helpers', () => {
+ it('findSameNameUniverses excludes the record itself', async () => {
+ const a = await universeSvc.createUniverse({ name: 'Solo' });
+ expect(await dup.findSameNameUniverses('Solo', { excludeId: a.id })).toEqual([]);
+ await universeSvc.createUniverse({ name: 'Solo' });
+ const hits = await dup.findSameNameUniverses('Solo', { excludeId: a.id });
+ expect(hits).toHaveLength(1);
+ });
+
+ it('findSameNameSeries scopes within a universe and ignores orphans', async () => {
+ const u1 = await universeSvc.createUniverse({ name: 'U' });
+ const s1 = await seriesSvc.createSeries({ name: 'Twin', universeId: u1.id });
+ await seriesSvc.createSeries({ name: 'Twin', universeId: u1.id });
+ const hits = await dup.findSameNameSeries('Twin', u1.id, { excludeId: s1.id });
+ expect(hits).toHaveLength(1);
+ // No universe → never warns (orphans aren't duplicate-checked).
+ expect(await dup.findSameNameSeries('Twin', null, {})).toEqual([]);
+ });
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index ae8cb45ef4..e50f5112ed 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -649,6 +649,55 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {
});
}
+/**
+ * Reassign every live issue from `fromSeriesId` to `toSeriesId` — used by the
+ * series-merge engine (recordMerge.js) so a duplicate series' issues survive
+ * the merge instead of being orphaned under the tombstoned loser.
+ *
+ * Moved issues land UN-GROUPED (`seasonId: null`): seasons are series-scoped,
+ * so the loser's season ids don't exist on the survivor. The survivor's
+ * seasons were unioned by number separately; re-homing issues to specific
+ * survivor seasons is left to the user. A single renumber pass on the survivor
+ * sequences the combined set. Returns `{ reassigned }`.
+ *
+ * Serialized on the SURVIVOR's issues queue so the renumber can't race a
+ * concurrent survivor edit. Tombstoned issues are skipped (moving them would
+ * bump updatedAt and lose the originator's delete LWW race).
+ */
+export function reassignIssuesToSeries(fromSeriesId, toSeriesId) {
+ if (!isStr(fromSeriesId) || !isStr(toSeriesId) || fromSeriesId === toSeriesId) {
+ return Promise.reject(makeErr('reassignIssuesToSeries: fromSeriesId and toSeriesId must differ', ERR_VALIDATION));
+ }
+ // This reads/mutates issues belonging to BOTH series (it moves source issues
+ // and renumbers the destination), so serialize on both per-series queues, not
+ // just the destination — otherwise a concurrent edit/renumber on the source
+ // (e.g. a peer-sync merge landing on the loser mid-merge) could interleave and
+ // be lost. Acquire in sorted order so a future two-series caller can't deadlock.
+ const [first, second] = [fromSeriesId, toSeriesId].sort();
+ const body = async () => {
+ const state = await readState();
+ const now = new Date().toISOString();
+ const moved = [];
+ for (let i = 0; i < state.issues.length; i += 1) {
+ const iss = state.issues[i];
+ if (iss.seriesId !== fromSeriesId || iss.deleted) continue;
+ const merged = sanitizeIssue({ ...iss, seriesId: toSeriesId, seasonId: null, updatedAt: now });
+ if (!merged) continue;
+ state.issues[i] = merged;
+ moved.push(merged);
+ }
+ if (moved.length === 0) return { reassigned: 0 };
+ await renumberInline(state, toSeriesId, null);
+ // Persist every issue now tagged to the survivor (the moved ones + any the
+ // survivor already had, whose numbers may have shifted in the renumber).
+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === toSeriesId));
+ emitRecordUpdated('series', toSeriesId);
+ emitRecordUpdated('series', fromSeriesId);
+ return { reassigned: moved.length };
+ };
+ return queueSeriesIssuesWrite(first, () => queueSeriesIssuesWrite(second, body));
+}
+
/**
* Insert an issue with a caller-supplied id (used by the share-bucket importer
* so re-imports of the same issue LWW-merge onto the same local row).
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index aa882376c2..b1153affcf 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -19,6 +19,9 @@ 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 {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+} from '../../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';
@@ -275,6 +278,15 @@ export async function updateSeries(id, patch = {}) {
const cur = await store().loadOne(id);
if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ // Hierarchy invariant: a series lives in exactly one universe. Reject
+ // clearing the link once it's set — moving to a *different* non-empty
+ // universe is fine, and a legacy orphan (cur.universeId === null) is still
+ // allowed to receive its first link. The importer / mergeSeriesFromSync
+ // land legacy orphans via the service directly (not this guard), so peer
+ // fidelity is preserved.
+ if ('universeId' in patch && cur.universeId && !trimTo(patch.universeId, UNIVERSE_ID_MAX)) {
+ throw makeErr('Cannot unlink a series from its universe — move it to another universe instead.', ERR_VALIDATION);
+ }
// Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.
const mergedLlm = 'llm' in patch
? { ...(cur.llm || {}), ...(patch.llm || {}) }
@@ -469,7 +481,7 @@ async function cascadeDeleteSideEffects(id) {
* returns `{ applied, count }` where `count` is the number of series actually
* changed/added.
*/
-export async function mergeSeriesFromSync(remoteSeries) {
+export async function mergeSeriesFromSync(remoteSeries, { source = { via: 'sync', peerId: null } } = {}) {
if (!Array.isArray(remoteSeries)) return { applied: false, count: 0 };
// Series IDs that transitioned to deleted via this merge — cascade fires
// after the write queue releases (mirrors local-delete contract).
@@ -492,6 +504,8 @@ export async function mergeSeriesFromSync(remoteSeries) {
// See universeBuilder.mergeUniversesFromSync — no local means no
// cascade work, regardless of inbound tombstone state.
await store().saveOneNow(sanitized.id, sanitized);
+ // Seed the base hash so a FUTURE divergence on this record is detected.
+ await setSyncBaseHash('series', sanitized.id, contentHashForRecord('series', sanitized));
changed++;
} else if (local.ephemeral === true) {
// Local-ephemeral series are immune to inbound merges. See
@@ -501,6 +515,19 @@ export async function mergeSeriesFromSync(remoteSeries) {
const localTs = local.updatedAt || '';
const remoteTs = sanitized.updatedAt || '';
if (remoteTs > localTs) {
+ // Hierarchy invariant on the sync path: an older peer (or a peer that
+ // cleared the link before the rule shipped) can push a newer series
+ // payload with universeId:null. updateSeries refuses to unlink, but
+ // this merge writes directly — so preserve the local link here too,
+ // or LWW would silently orphan a linked series. A *move* to a
+ // different non-empty universe still applies. Mirrors the importer's
+ // mergeOne guard.
+ if (!sanitized.deleted && !sanitized.universeId && local.universeId) {
+ sanitized.universeId = local.universeId;
+ }
+ // Non-blocking conflict journal — archive the losing local version on
+ // a true 3-way divergence; always advances the base hash. Never throws.
+ await maybeJournalBeforeOverwrite({ kind: 'series', id: sanitized.id, local, remote: sanitized, source });
await store().saveOneNow(sanitized.id, sanitized);
if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);
changed++;
@@ -508,6 +535,7 @@ export async function mergeSeriesFromSync(remoteSeries) {
}
});
}
+ await flushBaseHashes();
const result = changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };
for (const id of transitionedToDeleted) {
await cascadeDeleteSideEffects(id);
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index f808a922d7..c7f5a18696 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -79,6 +79,48 @@ describe('pipeline series service', () => {
await expect(svc.updateSeries('ser-nope', { name: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ it('updateSeries rejects clearing universeId once a series is linked (hierarchy invariant)', async () => {
+ const s = await svc.createSeries({ name: 'Linked', universeId: 'u-1' });
+ await expect(svc.updateSeries(s.id, { universeId: '' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.updateSeries(s.id, { universeId: null })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.updateSeries(s.id, { universeId: ' ' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ // Link survived the rejected clears.
+ expect((await svc.getSeries(s.id)).universeId).toBe('u-1');
+ });
+
+ it('updateSeries allows MOVING a linked series to a different universe', async () => {
+ const s = await svc.createSeries({ name: 'Mover', universeId: 'u-1' });
+ const moved = await svc.updateSeries(s.id, { universeId: 'u-2' });
+ expect(moved.universeId).toBe('u-2');
+ });
+
+ it('mergeSeriesFromSync preserves the local universe link when an older peer pushes an orphan payload', async () => {
+ const s = await svc.createSeries({ name: 'Linked', universeId: 'uni-A' });
+ // Older peer pushes a NEWER series record that lost its universe link.
+ const orphanPayload = { ...s, universeId: null, name: 'Linked (peer edit)', updatedAt: '2999-01-01T00:00:00.000Z' };
+ const res = await svc.mergeSeriesFromSync([orphanPayload]);
+ expect(res.applied).toBe(true);
+ const after = await svc.getSeries(s.id);
+ expect(after.name).toBe('Linked (peer edit)'); // remote edit applied
+ expect(after.universeId).toBe('uni-A'); // …but the link was preserved
+ });
+
+ it('mergeSeriesFromSync still applies a MOVE to a different non-empty universe', async () => {
+ const s = await svc.createSeries({ name: 'Mover', universeId: 'uni-A' });
+ const movePayload = { ...s, universeId: 'uni-B', updatedAt: '2999-01-01T00:00:00.000Z' };
+ await svc.mergeSeriesFromSync([movePayload]);
+ expect((await svc.getSeries(s.id)).universeId).toBe('uni-B');
+ });
+
+ it('updateSeries allows first-linking a legacy orphan (universeId null → set)', async () => {
+ // createSeries via the service is permissive (importer path); simulate a
+ // legacy orphan, then assign its first universe.
+ const s = await svc.createSeries({ name: 'Orphan', universeId: null });
+ expect(s.universeId).toBe(null);
+ const linked = await svc.updateSeries(s.id, { universeId: 'u-3' });
+ expect(linked.universeId).toBe('u-3');
+ });
+
it('deleteSeries drops the record and is idempotent only on second call', async () => {
const s = await svc.createSeries({ name: 'Salt Run' });
await svc.deleteSeries(s.id);
diff --git a/server/services/recordMerge.js b/server/services/recordMerge.js
new file mode 100644
index 0000000000..b0429bcaf4
--- /dev/null
+++ b/server/services/recordMerge.js
@@ -0,0 +1,373 @@
+/**
+ * Smart-merge engine for duplicate Universes and Series.
+ *
+ * "Merge" folds a LOSER record's unique data into a SURVIVOR, resolves
+ * genuinely-conflicting scalar fields via a caller-supplied `fieldChoices` map
+ * (the UI renders each conflict with InlineDiff and picks survivor|loser),
+ * re-points the loser's children to the survivor, then tombstones the loser so
+ * the deletion propagates to peers via the existing LWW + tombstone machinery.
+ *
+ * List-shaped fields are UNIONED (no data loss):
+ * - universe.categories — variations deduped by id OR normalizeLabelKey(label)
+ * - universe.compositeSheets — by id OR label
+ * - universe.characters/places/objects — via storyBible.mergeExtractedBible
+ * (dedupes by name + aliases, the same identity the importer uses)
+ * - universe.influences.{embrace,avoid} — case-insensitive dedupe
+ * - series.seasons — by season `number`
+ * - imageRefs[] on matched variations/sheets — unioned so render history survives
+ *
+ * `dryRun: true` returns the proposed unioned record + the conflicting-field
+ * list + a cascade summary WITHOUT writing — that's the preview the UI shows.
+ *
+ * Cascade ordering is load-bearing: re-point children BEFORE tombstoning the
+ * loser, so nothing is orphaned and (for universes) the block-until-empty
+ * delete guard doesn't trip.
+ */
+
+import {
+ getUniverse, updateUniverse, deleteUniverse,
+ normalizeLabelKey,
+ VARIATIONS_PER_CATEGORY_MAX, COMPOSITE_SHEETS_MAX, INFLUENCES_PER_LIST_MAX, IMAGE_REFS_PER_ENTRY_MAX,
+} from './universeBuilder.js';
+import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
+import { canonicalStringify } from '../lib/objects.js';
+import { getSeries, updateSeries, deleteSeries, listSeries } from './pipeline/series.js';
+import { reassignIssuesToSeries, listIssues } from './pipeline/issues.js';
+import {
+ findCollectionByUniverseId, findOrCreateUniverseCollection,
+ findCollectionBySeriesId, findOrCreateSeriesCollection,
+ bulkUpdateCollectionItems, deleteCollection,
+} from './mediaCollections.js';
+
+// Own error code (both the universe-builder and pipeline routers map it to
+// 400). get*() NOT_FOUND errors propagate with their own per-record codes,
+// which each router already maps to 404.
+export const ERR_VALIDATION = 'MERGE_VALIDATION';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+// ---- pure union helpers (exported for unit tests) ----
+
+const lc = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+
+// Union two imageRefs arrays (survivor first), dedupe by value, cap to the
+// per-entry limit keeping the newest tail (matches the sanitizer's policy).
+const unionImageRefs = (a = [], b = []) => {
+ const seen = new Set();
+ const out = [];
+ for (const ref of [...(Array.isArray(a) ? a : []), ...(Array.isArray(b) ? b : [])]) {
+ const key = typeof ref === 'string' ? ref : JSON.stringify(ref);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(ref);
+ }
+ return out.length > IMAGE_REFS_PER_ENTRY_MAX ? out.slice(-IMAGE_REFS_PER_ENTRY_MAX) : out;
+};
+
+// Identity keys for a variation/sheet. Cross-install duplicates routinely
+// carry DIFFERENT ids for the same conceptual entry (each install minted its
+// own id), so id-only matching would leave obvious same-label dupes side by
+// side after a merge. Match by id first, then fall back to normalized label
+// (mirrors universeBuilderRefine.js's label-keyed merge). Returns both keys so
+// the loser can match a survivor by either.
+const entryIdKey = (e) => (e?.id ? `id:${e.id}` : null);
+const entryLabelKey = (e) => {
+ const norm = normalizeLabelKey(e?.label);
+ return norm ? `label:${norm}` : null;
+};
+
+/**
+ * Union two variation (or composite-sheet) arrays: survivor entries first,
+ * loser-uniques appended; on identity match keep the survivor entry but union
+ * its imageRefs. A loser entry matches a survivor by id OR by normalized label
+ * (so cross-install entries with different ids but the same label still fold).
+ * Caps to `max`.
+ */
+export const unionEntryList = (survivor = [], loser = [], max = VARIATIONS_PER_CATEGORY_MAX) => {
+ const out = [];
+ const byId = new Map();
+ const byLabel = new Map();
+ for (const e of Array.isArray(survivor) ? survivor : []) {
+ const copy = { ...e };
+ const idKey = entryIdKey(copy);
+ const labelKey = entryLabelKey(copy);
+ if (idKey) byId.set(idKey, copy);
+ if (labelKey && !byLabel.has(labelKey)) byLabel.set(labelKey, copy);
+ out.push(copy);
+ }
+ for (const e of Array.isArray(loser) ? loser : []) {
+ const idKey = entryIdKey(e);
+ const labelKey = entryLabelKey(e);
+ const match = (idKey && byId.get(idKey)) || (labelKey && byLabel.get(labelKey));
+ if (match) {
+ match.imageRefs = unionImageRefs(match.imageRefs, e.imageRefs);
+ } else if (out.length < max) {
+ const copy = { ...e };
+ out.push(copy);
+ if (idKey) byId.set(idKey, copy);
+ if (labelKey && !byLabel.has(labelKey)) byLabel.set(labelKey, copy);
+ }
+ }
+ return out.slice(0, max);
+};
+
+/** Union two `categories` keyed maps. */
+export const unionCategories = (survivor = {}, loser = {}) => {
+ const out = {};
+ const keys = new Set([...Object.keys(survivor || {}), ...Object.keys(loser || {})]);
+ for (const key of keys) {
+ const s = survivor?.[key];
+ const l = loser?.[key];
+ if (s && l) {
+ out[key] = { ...s, variations: unionEntryList(s.variations, l.variations) };
+ } else {
+ out[key] = s || l;
+ }
+ }
+ return out;
+};
+
+/** Union two `influences` objects ({embrace[],avoid[]}), case-insensitive dedupe. */
+export const unionInfluences = (survivor = {}, loser = {}) => {
+ const mergeList = (a = [], b = []) => {
+ const seen = new Set();
+ const out = [];
+ for (const v of [...(Array.isArray(a) ? a : []), ...(Array.isArray(b) ? b : [])]) {
+ const key = lc(v);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(v);
+ if (out.length >= INFLUENCES_PER_LIST_MAX) break;
+ }
+ return out;
+ };
+ return {
+ embrace: mergeList(survivor?.embrace, loser?.embrace),
+ avoid: mergeList(survivor?.avoid, loser?.avoid),
+ };
+};
+
+// Union series seasons by `number`: survivor seasons first; loser seasons whose
+// number isn't already present get appended.
+const unionSeasons = (survivor = [], loser = []) => {
+ const out = [];
+ const numbers = new Set();
+ for (const s of Array.isArray(survivor) ? survivor : []) {
+ out.push(s);
+ if (Number.isFinite(s?.number)) numbers.add(s.number);
+ }
+ for (const l of Array.isArray(loser) ? loser : []) {
+ if (Number.isFinite(l?.number) && numbers.has(l.number)) continue;
+ out.push(l);
+ if (Number.isFinite(l?.number)) numbers.add(l.number);
+ }
+ return out;
+};
+
+const isEmptyScalar = (v) => v === null || v === undefined || (typeof v === 'string' && v.trim() === '')
+ || (Array.isArray(v) && v.length === 0);
+
+/**
+ * Resolve a set of scalar fields between survivor + loser.
+ * Returns `{ values, conflicts, autoResolved }`:
+ * - conflicts: both sides non-empty AND differ → caller must supply a choice.
+ * - autoResolved: only one side non-empty → take it (no prompt needed).
+ * - equal / both-empty → survivor value, silently.
+ * `fieldChoices` is `{ [field]: 'survivor' | 'loser' }`.
+ */
+const resolveScalars = (fields, survivor, loser, fieldChoices = {}) => {
+ const values = {};
+ const conflicts = [];
+ const autoResolved = [];
+ for (const field of fields) {
+ const sv = survivor[field];
+ const lv = loser[field];
+ const sEmpty = isEmptyScalar(sv);
+ const lEmpty = isEmptyScalar(lv);
+ if (sEmpty && lEmpty) { values[field] = sv ?? lv ?? ''; continue; }
+ if (sEmpty !== lEmpty) {
+ values[field] = sEmpty ? lv : sv;
+ if (sEmpty) autoResolved.push({ field, from: 'loser' });
+ continue;
+ }
+ // Both non-empty. Compare with canonicalStringify (sorted-key) so an
+ // object-valued scalar like `series.arc` doesn't surface a false conflict
+ // when both sides are semantically identical but key-ordered differently.
+ if (canonicalStringify(sv) === canonicalStringify(lv)) { values[field] = sv; continue; }
+ const choice = fieldChoices[field];
+ if (choice === 'loser') values[field] = lv;
+ else if (choice === 'survivor') values[field] = sv;
+ else { conflicts.push({ field, survivorValue: sv, loserValue: lv }); values[field] = sv; }
+ }
+ return { values, conflicts, autoResolved };
+};
+
+const UNIVERSE_SCALARS = ['name', 'starterPrompt', 'logline', 'premise', 'styleNotes'];
+const SERIES_SCALARS = [
+ 'name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author',
+ 'stylePromptOverride', 'stylePromptOverrideMode', 'targetFormat', 'issueCountTarget', 'arc',
+];
+
+/** Build the unioned universe patch + conflict report from survivor + loser. */
+export const buildUniverseUnion = (survivor, loser, fieldChoices = {}) => {
+ const { values, conflicts, autoResolved } = resolveScalars(UNIVERSE_SCALARS, survivor, loser, fieldChoices);
+ const record = {
+ ...values,
+ categories: unionCategories(survivor.categories, loser.categories),
+ compositeSheets: unionEntryList(survivor.compositeSheets, loser.compositeSheets, COMPOSITE_SHEETS_MAX),
+ influences: unionInfluences(survivor.influences, loser.influences),
+ characters: mergeExtractedBible(survivor.characters, loser.characters, BIBLE_KIND.CHARACTER),
+ places: mergeExtractedBible(survivor.places, loser.places, BIBLE_KIND.PLACE),
+ objects: mergeExtractedBible(survivor.objects, loser.objects, BIBLE_KIND.OBJECT),
+ };
+ return { record, conflicts, autoResolved };
+};
+
+/** Build the unioned series patch + conflict report from survivor + loser. */
+export const buildSeriesUnion = (survivor, loser, fieldChoices = {}) => {
+ const { values, conflicts, autoResolved } = resolveScalars(SERIES_SCALARS, survivor, loser, fieldChoices);
+ const record = {
+ ...values,
+ seasons: unionSeasons(survivor.seasons, loser.seasons),
+ };
+ return { record, conflicts, autoResolved };
+};
+
+const requireResolved = (conflicts) => {
+ if (conflicts.length > 0) {
+ throw makeErr(
+ `Unresolved conflicting field(s): ${conflicts.map((c) => c.field).join(', ')}`,
+ ERR_VALIDATION,
+ );
+ }
+};
+
+// ---- universe merge ----
+
+/**
+ * Merge two duplicate universes. `dryRun` returns a preview without writing.
+ * On execute: writes the unioned survivor, re-points the loser's child series
+ * + media collection, then tombstones the loser.
+ */
+export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { dryRun = false } = {}) {
+ if (!survivorId || !loserId || survivorId === loserId) {
+ throw makeErr('survivorId and loserId must be distinct', ERR_VALIDATION);
+ }
+ const survivor = await getUniverse(survivorId);
+ const loser = await getUniverse(loserId);
+
+ const { record, conflicts, autoResolved } = buildUniverseUnion(survivor, loser, fieldChoices);
+
+ // Cascade preview: which series re-point, how many collection items fold.
+ const childSeries = (await listSeries()).filter((s) => s.universeId === loserId);
+ const loserCollection = await findCollectionByUniverseId(loserId);
+ const cascade = {
+ seriesToRepoint: childSeries.map((s) => ({ id: s.id, name: s.name })),
+ loserCollectionItemCount: loserCollection ? (loserCollection.items || []).length : 0,
+ };
+
+ if (dryRun) {
+ return { survivorId, loserId, preview: { ...survivor, ...record }, conflicts, autoResolved, cascade };
+ }
+ requireResolved(conflicts);
+
+ // 1. Write the unioned survivor (mutator form bypasses the literal-patch
+ // imageRef / reference-sheet preservation guards — our union already has
+ // the merged refs and must win verbatim).
+ await updateUniverse(survivorId, () => record);
+
+ // 2. Re-point child series to the survivor BEFORE tombstoning the loser, so
+ // the block-until-empty delete guard doesn't trip and nothing is orphaned.
+ for (const s of childSeries) {
+ await updateSeries(s.id, { universeId: survivorId });
+ }
+
+ // 3. Fold the loser's auto-collection into the survivor's. The deterministic
+ // id `uc-<survivorId>` is already taken, so items are folded (not renamed)
+ // then the loser's now-empty bucket is tombstoned.
+ if (loserCollection && (loserCollection.items || []).length > 0) {
+ const survivorCollection = await findOrCreateUniverseCollection({ universeId: survivorId, universeName: record.name || survivor.name });
+ await bulkUpdateCollectionItems(survivorCollection.id, {
+ add: loserCollection.items.map((it) => ({ kind: it.kind, ref: it.ref })),
+ });
+ }
+ if (loserCollection) {
+ await deleteCollection(loserCollection.id).catch((err) => {
+ console.error(`❌ mergeUniverses: deleting loser collection ${loserCollection.id} failed: ${err?.message || err}`);
+ });
+ }
+
+ // 4. Tombstone the loser (children re-pointed → guard passes).
+ await deleteUniverse(loserId);
+
+ console.log(`🧬 mergeUniverses: folded ${loserId} into ${survivorId} (${cascade.seriesToRepoint.length} series re-pointed, ${cascade.loserCollectionItemCount} collection items)`);
+ return { survivorId, loserId, merged: true, cascade };
+}
+
+// ---- series merge ----
+
+/**
+ * Merge two duplicate series (must be in the same universe — the caller scopes
+ * candidates that way). `dryRun` returns a preview without writing. On execute:
+ * writes the unioned survivor, re-points the loser's issues + media collection,
+ * then tombstones the loser.
+ */
+export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryRun = false } = {}) {
+ if (!survivorId || !loserId || survivorId === loserId) {
+ throw makeErr('survivorId and loserId must be distinct', ERR_VALIDATION);
+ }
+ const survivor = await getSeries(survivorId);
+ const loser = await getSeries(loserId);
+ const survivorUniverseId = survivor.universeId || null;
+ const loserUniverseId = loser.universeId || null;
+ if (!survivorUniverseId || !loserUniverseId) {
+ // Orphan series are surfaced separately as "never merged"; merging two
+ // unrelated orphans (both universeId null) would fold issues/collections
+ // across unrelated works. Require linking into a universe first.
+ throw makeErr('Orphan series (no universe) cannot be merged — link them into a universe first', ERR_VALIDATION);
+ }
+ if (survivorUniverseId !== loserUniverseId) {
+ throw makeErr('Series can only be merged within the same universe', ERR_VALIDATION);
+ }
+
+ const { record, conflicts, autoResolved } = buildSeriesUnion(survivor, loser, fieldChoices);
+
+ const loserCollection = await findCollectionBySeriesId(loserId);
+ // Issues are reassigned to the survivor un-grouped; count for the preview.
+ const loserIssues = await listIssues({ seriesId: loserId });
+ const cascade = {
+ issuesToRepoint: loserIssues.length,
+ loserCollectionItemCount: loserCollection ? (loserCollection.items || []).length : 0,
+ };
+
+ if (dryRun) {
+ return { survivorId, loserId, preview: { ...survivor, ...record }, conflicts, autoResolved, cascade };
+ }
+ requireResolved(conflicts);
+
+ // 1. Write the unioned survivor.
+ await updateSeries(survivorId, record);
+
+ // 2. Re-point the loser's issues to the survivor (un-grouped) before tombstone.
+ if (loserIssues.length > 0) {
+ await reassignIssuesToSeries(loserId, survivorId);
+ }
+
+ // 3. Fold the loser's series-collection into the survivor's, then tombstone it.
+ if (loserCollection && (loserCollection.items || []).length > 0) {
+ const survivorCollection = await findOrCreateSeriesCollection({ seriesId: survivorId, seriesName: record.name || survivor.name });
+ await bulkUpdateCollectionItems(survivorCollection.id, {
+ add: loserCollection.items.map((it) => ({ kind: it.kind, ref: it.ref })),
+ });
+ }
+ if (loserCollection) {
+ await deleteCollection(loserCollection.id).catch((err) => {
+ console.error(`❌ mergeSeries: deleting loser collection ${loserCollection.id} failed: ${err?.message || err}`);
+ });
+ }
+
+ // 4. Tombstone the loser.
+ await deleteSeries(loserId);
+
+ console.log(`🧬 mergeSeries: folded ${loserId} into ${survivorId} (${cascade.issuesToRepoint} issues re-pointed, ${cascade.loserCollectionItemCount} collection items)`);
+ return { survivorId, loserId, merged: true, cascade };
+}
diff --git a/server/services/recordMerge.test.js b/server/services/recordMerge.test.js
new file mode 100644
index 0000000000..e3b43427ef
--- /dev/null
+++ b/server/services/recordMerge.test.js
@@ -0,0 +1,216 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mockNoPeerSync, mockNoPeers, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'record-merge-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+vi.mock('./instances.js', () => mockNoPeers());
+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${String(++uuidCounter).padStart(8, '0')}` };
+});
+
+const merge = await import('./recordMerge.js');
+const universeSvc = await import('./universeBuilder.js');
+const seriesSvc = await import('./pipeline/series.js');
+const issuesSvc = await import('./pipeline/issues.js');
+const collectionsSvc = await import('./mediaCollections.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('recordMerge — pure union helpers', () => {
+ it('unionEntryList dedupes by id, unions imageRefs on match, appends uniques', () => {
+ const out = merge.unionEntryList(
+ [{ id: 'v1', label: 'A', imageRefs: ['a.png'] }],
+ [
+ { id: 'v1', label: 'A', imageRefs: ['b.png'] }, // matches v1 → union refs
+ { id: 'v2', label: 'B', imageRefs: ['c.png'] }, // unique → appended
+ ],
+ );
+ expect(out).toHaveLength(2);
+ expect(out[0].imageRefs).toEqual(['a.png', 'b.png']);
+ expect(out[1].id).toBe('v2');
+ });
+
+ it('unionEntryList matches by normalized label when id is absent', () => {
+ const out = merge.unionEntryList(
+ [{ label: 'Crystal Canyon', prompt: 'x' }],
+ [{ label: ' crystal canyon ', prompt: 'y' }],
+ );
+ expect(out).toHaveLength(1); // same label-key → not duplicated
+ });
+
+ it('unionEntryList folds same-label entries even when ids differ (cross-install dupes)', () => {
+ const out = merge.unionEntryList(
+ [{ id: 'local-1', label: 'Crystal Canyon', imageRefs: ['a.png'] }],
+ [{ id: 'remote-9', label: ' crystal canyon ', imageRefs: ['b.png'] }],
+ );
+ expect(out).toHaveLength(1); // different ids, same label → one entry
+ expect(out[0].id).toBe('local-1'); // survivor entry kept
+ expect(out[0].imageRefs).toEqual(['a.png', 'b.png']); // refs unioned
+ });
+
+ it('unionCategories merges keyed map, unioning shared keys and adding loser-only keys', () => {
+ const out = merge.unionCategories(
+ { landscapes: { kind: 'places', variations: [{ id: 'a', label: 'A' }] } },
+ {
+ landscapes: { kind: 'places', variations: [{ id: 'b', label: 'B' }] },
+ outfits: { kind: 'objects', variations: [{ id: 'c', label: 'C' }] },
+ },
+ );
+ expect(Object.keys(out).sort()).toEqual(['landscapes', 'outfits']);
+ expect(out.landscapes.variations).toHaveLength(2);
+ });
+
+ it('unionInfluences case-insensitively dedupes embrace/avoid', () => {
+ const out = merge.unionInfluences(
+ { embrace: ['Moebius'], avoid: ['blurry'] },
+ { embrace: ['moebius', 'noir'], avoid: ['lowres'] },
+ );
+ expect(out.embrace).toEqual(['Moebius', 'noir']);
+ expect(out.avoid).toEqual(['blurry', 'lowres']);
+ });
+
+ it('buildUniverseUnion reports a scalar conflict when both sides differ', () => {
+ const { conflicts, autoResolved, record } = merge.buildUniverseUnion(
+ { name: 'Dup', starterPrompt: 'A', logline: '', categories: {}, influences: {}, characters: [], places: [], objects: [] },
+ { name: 'Dup', starterPrompt: 'B', logline: 'only-loser', categories: {}, influences: {}, characters: [], places: [], objects: [] },
+ );
+ expect(conflicts).toEqual([{ field: 'starterPrompt', survivorValue: 'A', loserValue: 'B' }]);
+ // logline present only on loser → auto-resolved to loser's value.
+ expect(record.logline).toBe('only-loser');
+ expect(autoResolved).toContainEqual({ field: 'logline', from: 'loser' });
+ });
+
+ it('buildUniverseUnion applies fieldChoices to resolve conflicts', () => {
+ const { conflicts, record } = merge.buildUniverseUnion(
+ { name: 'Dup', starterPrompt: 'A', categories: {}, influences: {}, characters: [], places: [], objects: [] },
+ { name: 'Dup', starterPrompt: 'B', categories: {}, influences: {}, characters: [], places: [], objects: [] },
+ { starterPrompt: 'loser' },
+ );
+ expect(conflicts).toEqual([]);
+ expect(record.starterPrompt).toBe('B');
+ });
+});
+
+describe('recordMerge — mergeUniverses (integration)', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ uuidCounter = 0;
+ });
+
+ const seed = async () => {
+ const survivor = await universeSvc.createUniverse({
+ name: 'Clandestiny', starterPrompt: 'A',
+ influences: { embrace: ['moebius'], avoid: [] },
+ categories: { landscapes: { variations: [{ label: 'Canyon', prompt: 'c' }] } },
+ });
+ const loser = await universeSvc.createUniverse({
+ name: 'Clandestiny', starterPrompt: 'A',
+ influences: { embrace: ['noir'], avoid: [] },
+ categories: { outfits: { variations: [{ label: 'Cloak', prompt: 'k' }] } },
+ });
+ return { survivor, loser };
+ };
+
+ it('dryRun previews union + cascade without writing', async () => {
+ const { survivor, loser } = await seed();
+ await seriesSvc.createSeries({ name: 'Child', universeId: loser.id });
+
+ const preview = await merge.mergeUniverses(survivor.id, loser.id, {}, { dryRun: true });
+ expect(preview.cascade.seriesToRepoint).toHaveLength(1);
+ // Union carries the survivor's landscapes + the loser's outfits (plus any
+ // default buckets createUniverse seeds).
+ expect(Object.keys(preview.preview.categories)).toEqual(expect.arrayContaining(['landscapes', 'outfits']));
+ // Nothing was written: loser still live, child still under loser.
+ expect((await universeSvc.getUniverse(loser.id)).deleted).toBeFalsy();
+ });
+
+ it('executes: unions canon, re-points child series + collection, tombstones loser', async () => {
+ const { survivor, loser } = await seed();
+ const child = await seriesSvc.createSeries({ name: 'Child', universeId: loser.id });
+
+ // Loser owns a collection with an item; survivor's collection starts empty.
+ const loserCol = await collectionsSvc.findOrCreateUniverseCollection({ universeId: loser.id, universeName: 'Clandestiny' });
+ await collectionsSvc.bulkUpdateCollectionItems(loserCol.id, { add: [{ kind: 'image', ref: 'loser-pic.png' }] });
+
+ const result = await merge.mergeUniverses(survivor.id, loser.id, {});
+ expect(result.merged).toBe(true);
+
+ // Survivor gained the loser's unique category + influence.
+ const merged = await universeSvc.getUniverse(survivor.id);
+ expect(Object.keys(merged.categories)).toEqual(expect.arrayContaining(['landscapes', 'outfits']));
+ expect(merged.influences.embrace).toEqual(expect.arrayContaining(['moebius', 'noir']));
+
+ // Child series re-pointed to survivor.
+ expect((await seriesSvc.getSeries(child.id)).universeId).toBe(survivor.id);
+
+ // Loser tombstoned.
+ await expect(universeSvc.getUniverse(loser.id)).rejects.toMatchObject({ code: universeSvc.ERR_NOT_FOUND });
+
+ // Loser's collection item folded into the survivor's collection.
+ const survivorCol = await collectionsSvc.findCollectionByUniverseId(survivor.id);
+ expect(survivorCol.items.map((i) => i.ref)).toContain('loser-pic.png');
+ });
+
+ it('refuses to execute with an unresolved scalar conflict', async () => {
+ const survivor = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'survivor-prompt' });
+ const loser = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'loser-prompt' });
+ await expect(merge.mergeUniverses(survivor.id, loser.id, {})).rejects.toMatchObject({ code: 'MERGE_VALIDATION' });
+ // With a choice it succeeds.
+ const ok = await merge.mergeUniverses(survivor.id, loser.id, { starterPrompt: 'loser' });
+ expect(ok.merged).toBe(true);
+ expect((await universeSvc.getUniverse(survivor.id)).starterPrompt).toBe('loser-prompt');
+ });
+});
+
+describe('recordMerge — mergeSeries (integration)', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ uuidCounter = 0;
+ });
+
+ it('re-points the loser series issues to the survivor and tombstones the loser', async () => {
+ const u = await universeSvc.createUniverse({ name: 'U' });
+ const survivor = await seriesSvc.createSeries({ name: 'Twin', universeId: u.id });
+ const loser = await seriesSvc.createSeries({ name: 'Twin', universeId: u.id });
+ await issuesSvc.createIssue({ seriesId: loser.id, title: 'Loser Issue' });
+
+ const result = await merge.mergeSeries(survivor.id, loser.id, {});
+ expect(result.merged).toBe(true);
+ expect(result.cascade.issuesToRepoint).toBe(1);
+
+ // The issue now belongs to the survivor.
+ const survivorIssues = await issuesSvc.listIssues({ seriesId: survivor.id });
+ expect(survivorIssues).toHaveLength(1);
+ expect(survivorIssues[0].title).toBe('Loser Issue');
+
+ // Loser tombstoned.
+ await expect(seriesSvc.getSeries(loser.id)).rejects.toMatchObject({ code: seriesSvc.ERR_NOT_FOUND });
+ });
+
+ it('rejects merging series from different universes', async () => {
+ const u1 = await universeSvc.createUniverse({ name: 'U1' });
+ const u2 = await universeSvc.createUniverse({ name: 'U2' });
+ const a = await seriesSvc.createSeries({ name: 'S', universeId: u1.id });
+ const b = await seriesSvc.createSeries({ name: 'S', universeId: u2.id });
+ await expect(merge.mergeSeries(a.id, b.id, {})).rejects.toMatchObject({ code: 'MERGE_VALIDATION' });
+ });
+
+ it('rejects merging two orphan series (null === null is not a valid scope)', async () => {
+ // Orphans are surfaced separately as "never merged"; merging two unrelated
+ // orphans would fold issues/collections across unrelated works.
+ const a = await seriesSvc.createSeries({ name: 'Orphan', universeId: null });
+ const b = await seriesSvc.createSeries({ name: 'Orphan', universeId: null });
+ await expect(merge.mergeSeries(a.id, b.id, {})).rejects.toMatchObject({ code: 'MERGE_VALIDATION' });
+ });
+});
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index a1f0abff07..9a15d01a48 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -40,6 +40,7 @@ import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { mergePeerAnnotations } from '../mediaAnnotations.js';
import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
+import { maybeJournalBeforeOverwrite, flushBaseHashes, setSyncBaseHash, contentHashForRecord } from '../../lib/conflictJournal.js';
function isSelfAuthored(senderInstanceId, localInstanceId) {
return !!localInstanceId
@@ -440,10 +441,41 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
failedInserts.push(`${kind}:${record.id}`);
return false;
});
- if (insertOk) applied++;
+ if (insertOk) {
+ applied++;
+ // Seed the conflict-journal base hash for a freshly-imported record so
+ // its FIRST cross-install divergence is journaled (the sync merge paths
+ // seed on their insert branch too; without this a bucket-imported
+ // record has base==null and the first conflict would be missed). Hash
+ // the STORED record so the base matches a future `local` hash exactly.
+ if (kind === 'universe' || kind === 'series') {
+ const stored = await getFn(record.id).catch(() => null);
+ if (stored) await setSyncBaseHash(kind, record.id, contentHashForRecord(kind, stored));
+ }
+ }
return;
}
if (remoteWins(existing.updatedAt, record.updatedAt)) {
+ // A remote series that arrived without a universe link (an orphan on the
+ // sender — older peer, or a record whose link was cleared before the
+ // hierarchy rule shipped) must NOT clear the local link: updateSeries now
+ // refuses to unlink a linked series and would throw, aborting the whole
+ // manifest. Preserve the existing link (a *move* to a different non-empty
+ // universe still applies). Mirrors the legacy-canon re-stamp above, but
+ // for every series — not just ones carrying legacy canon arrays.
+ if (kind === 'series' && !record.universeId && existing.universeId) {
+ record = { ...record, universeId: existing.universeId };
+ }
+ // Non-blocking conflict journal for the two synced top-level kinds — a
+ // share-bucket import that LWW-overwrites a locally-diverged record
+ // archives the losing local version first. Issues ride LWW silently
+ // (child-issue conflict journaling is a v1 follow-up).
+ if (kind === 'universe' || kind === 'series') {
+ await maybeJournalBeforeOverwrite({
+ kind, id: record.id, local: existing, remote: record,
+ source: { via: 'share-bucket', bucketId: bucket.id, peerId: manifest.senderInstanceId ?? null },
+ });
+ }
await withReexportSuppressed(suppressKind, suppressId, () => updateFn(existing.id, record));
overridden.push({ kind, id: record.id, label });
applied++;
@@ -586,6 +618,9 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
});
}
+ // Persist the batched conflict-journal base-hash updates accumulated above.
+ await flushBaseHashes();
+
return {
applied,
overridden,
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 0b2aa57a91..129f156295 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -202,6 +202,49 @@ describe('sharing round-trip', () => {
expect(afterOverride.name).toBe('Test Series (renamed)');
});
+ it('a remote orphan series (universeId null) preserves the local universe link instead of aborting the import', async () => {
+ const bucket = await buckets.createBucket({ name: 'OrphanLinkBucket', path: tempBucket, mode: 'auto-merge' });
+ const u = await universeSvc.createUniverse({ name: 'Linked Universe' });
+ const s = await series.createSeries({ name: 'Linked Series', universeId: u.id });
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+
+ // Rewrite the exported series record to look like an ORPHAN (no universeId)
+ // with a newer updatedAt — mimics an older/cleared peer. Before the fix this
+ // tripped updateSeries's "cannot unlink" guard and threw, aborting the whole
+ // manifest import; now the importer preserves the local link.
+ const seriesRecPath = join(tempBucket, 'records', 'series', `${s.id}.json`);
+ const rec = JSON.parse(readFileSync(seriesRecPath, 'utf-8'));
+ rec.universeId = null;
+ rec.updatedAt = '2999-01-01T00:00:00.000Z';
+ writeFileSync(seriesRecPath, JSON.stringify(rec, null, 2));
+
+ simulateRemoteSender(tempBucket, exp.filename);
+ const r = await importer.processManifest(bucket.id, exp.filename);
+ expect(r.processed).toBe(true);
+ expect(r.outcome.recordImportFailures).toBeFalsy();
+
+ // Link preserved (not unlinked), and the series survived the import.
+ const after = await series.getSeries(s.id);
+ expect(after.universeId).toBe(u.id);
+ });
+
+ it('seeds a conflict-journal base hash when a series is first imported (so its first divergence is journaled)', async () => {
+ const bucket = await buckets.createBucket({ name: 'BaseSeedBucket', path: tempBucket, mode: 'auto-merge' });
+ const u = await universeSvc.createUniverse({ name: 'Seed Universe' });
+ const s = await series.createSeries({ name: 'Seed Series', universeId: u.id });
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+
+ // Drop the local copy so the import is a fresh INSERT (the branch that
+ // previously skipped base-hash seeding).
+ await series.deleteSeries(s.id);
+ simulateRemoteSender(tempBucket, exp.filename);
+ await importer.processManifest(bucket.id, exp.filename);
+
+ const baseHashPath = join(tempData, 'sharing', 'sync_base_hashes.json');
+ const baseHashes = JSON.parse(readFileSync(baseHashPath, 'utf-8'));
+ expect(baseHashes[`series:${s.id}`]).toBeTruthy();
+ });
+
it('re-importing the same manifest is a no-op (cursor dedup)', async () => {
const bucket = await buckets.createBucket({ name: 'D', path: tempBucket, mode: 'auto-merge' });
const s = await series.createSeries({ name: 'X' });
@@ -1693,10 +1736,17 @@ describe('sharing round-trip', () => {
const { hasBeenProcessed, readCursor } = await import('./manifest.js');
const bucket = await buckets.createBucket({ name: 'TombstonedUniViaSeriesBucket', path: tempBucket, mode: 'auto-merge' });
- // Create universe + linked series, then delete the universe.
+ // Create universe + linked series, then tombstone the universe. Local
+ // deleteUniverse is blocked while a live series references it (the
+ // hierarchy invariant), but this orphan-link-to-tombstone state still
+ // arises in production: a PEER deletes the universe (it had no series
+ // there) and the delete-tombstone arrives via sync while we hold an
+ // independently-created linked series. Reproduce that via the merge path.
const uni = await universeSvc.createUniverse({ name: 'Gone Universe' });
const s = await series.createSeries({ name: 'Linked Series', logline: 'x', universeId: uni.id });
- await universeSvc.deleteUniverse(uni.id);
+ await universeSvc.mergeUniversesFromSync([
+ { ...uni, deleted: true, deletedAt: new Date().toISOString(), updatedAt: new Date(Date.now() + 60_000).toISOString() },
+ ]);
// Hand-write a collection manifest referencing the series id (the exporter
// normally resolves series→universe, but a legacy peer may emit seriesId).
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index baee26d022..770bed3c7f 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -46,6 +46,7 @@ import { peerFetch } from '../../lib/peerHttpClient.js';
import { getOrComputeImageSha256, sidecarGenParamsHash } from '../../lib/assetHash.js';
import { generateThumbnail } from '../../lib/ffmpeg.js';
import { sanitizeRecordForWire } from '../../lib/syncWire.js';
+import { setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';
import { collectAssetReferences } from './exporter.js';
import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';
import { pullSidecarForImage } from './sidecarSync.js';
@@ -934,6 +935,19 @@ export async function pushRecordToPeer(sub, options = {}) {
if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {
await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});
}
+ // Conflict-journal base hash: this record's content now lives on the peer too
+ // (the record always lands even when assets are still pulling), so stamp the
+ // shared-state base for the two journaled kinds. This is the symmetric
+ // convergence point to the receiver advancing its base in mergeXxxFromSync —
+ // it keeps a peer's echo (reverse-subscription push-back) from later looking
+ // like a divergence. Best-effort; never block the push result on it — the
+ // stamp + filesystem flush run fire-and-forget so a slow disk can't delay the
+ // push loop. The `.catch()` keeps the rejection from escaping as unhandled.
+ if ((sub.recordKind === 'universe' || sub.recordKind === 'series') && payload.record) {
+ setSyncBaseHash(sub.recordKind, sub.recordId, contentHashForRecord(sub.recordKind, payload.record))
+ .then(() => flushBaseHashes())
+ .catch((err) => console.log(`⚠️ peerSync: base-hash stamp after push failed: ${err?.message || err}`));
+ }
return {
pushed: true,
hash,
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index eb8be22e10..97237a0163 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -38,11 +38,18 @@ import {
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+} from '../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';
import {
clearPendingSheetSlot, clearPendingSheetSlotsForUniverse,
} from './universeCharacterSheetSlot.js';
+// Hierarchy guard: a universe can't be deleted while live series reference it.
+// series.js does NOT import universeBuilder (one-directional), so this static
+// import is cycle-safe — unlike canonUsage.js, which back-imports this module.
+import { listSeries } from './pipeline/series.js';
// RECORD-shape schema version, stamped INSIDE each universe record. Distinct
// from the type-level (storage layout) schemaVersion carried by
@@ -92,6 +99,10 @@ export const universeStore = () => store();
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
export const ERR_DUPLICATE = 'DUPLICATE';
+// Raised by deleteUniverse when live series still reference the universe. The
+// thrown error carries `blockingSeries: [{id,name}]` so the route can tell the
+// user which series to move or delete first. Maps to HTTP 409.
+export const ERR_HAS_LIVE_SERIES = 'UNIVERSE_HAS_LIVE_SERIES';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
// Universe ids are bare UUIDs (no prefix). Accept any reasonable alphanumeric
@@ -1254,6 +1265,21 @@ export async function deleteUniverse(id) {
// the receiving peer when a soft-delete arrives via mergeUniversesFromSync
// so a synced delete doesn't leave orphan media-collection locks.
const s = store();
+ // Hierarchy invariant (block-until-empty): refuse to delete a universe that
+ // still has live (non-deleted) series — the user must move or delete those
+ // series first. Filter listSeries() inline rather than calling
+ // canonUsage.listLinkedSeriesNames (canonUsage back-imports this module → a
+ // require cycle). This runs OUTSIDE the record queue: a read-only pre-check,
+ // and the queued write below re-validates existence anyway.
+ const blockingSeries = (await listSeries())
+ .filter((ser) => ser.universeId === id)
+ .map((ser) => ({ id: ser.id, name: ser.name }));
+ if (blockingSeries.length > 0) {
+ throw Object.assign(
+ makeErr(`Universe has ${blockingSeries.length} live series — move or delete them first`, ERR_HAS_LIVE_SERIES),
+ { blockingSeries },
+ );
+ }
await s.queueRecordWrite(id, async () => {
const cur = await s.loadOne(id);
if (!cur) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
@@ -1329,7 +1355,7 @@ async function cascadeDeleteSideEffects(id) {
* number of universes actually changed/added by this merge — NOT the total
* post-merge count — so callers summing across categories don't over-report.
*/
-export async function mergeUniversesFromSync(remoteUniverses) {
+export async function mergeUniversesFromSync(remoteUniverses, { source = { via: 'sync', peerId: null } } = {}) {
if (!Array.isArray(remoteUniverses)) return { applied: false, count: 0 };
// Records that transitioned to deleted via this merge get their orphan
// cascade fired after the write queue releases — matches the side-effect
@@ -1370,6 +1396,9 @@ export async function mergeUniversesFromSync(remoteUniverses) {
// spuriously tear down share-bucket subscriptions.
await ensureDir(s.recordDir(sanitized.id));
await atomicWrite(s.recordPath(sanitized.id), sanitized);
+ // No local counterpart to lose — nothing to journal, but seed the base
+ // hash so a FUTURE divergence on this record is detected.
+ await setSyncBaseHash('universe', sanitized.id, contentHashForRecord('universe', sanitized));
changed += 1;
return;
}
@@ -1384,6 +1413,11 @@ export async function mergeUniversesFromSync(remoteUniverses) {
const localTs = local.updatedAt || '';
const remoteTs = sanitized.updatedAt || '';
if (remoteTs > localTs) {
+ // Non-blocking conflict journal: archive the about-to-be-lost local
+ // version when BOTH sides diverged from the last synced base. Always
+ // advances the base hash (clean or conflict) so the next snapshot
+ // cycle doesn't re-journal the same divergence. Never throws.
+ await maybeJournalBeforeOverwrite({ kind: 'universe', id: sanitized.id, local, remote: sanitized, source });
await ensureDir(s.recordDir(sanitized.id));
await atomicWrite(s.recordPath(sanitized.id), sanitized);
if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);
@@ -1392,6 +1426,8 @@ export async function mergeUniversesFromSync(remoteUniverses) {
}));
}
await Promise.all(writeTasks);
+ // Persist the batched base-hash updates accumulated above in one write.
+ await flushBaseHashes();
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. Same critical-
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index c5f585a1c3..6e6a4675d8 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -565,6 +565,25 @@ describe("universeBuilder service", () => {
expect(await svc.listRuns(w.id)).toEqual([]);
});
+ it("deleteUniverse is BLOCKED while live series reference it (hierarchy invariant)", async () => {
+ const seriesSvc = await import("./pipeline/series.js");
+ const w = await seedWorld();
+ const ser = await seriesSvc.createSeries({ name: "Child Arc", universeId: w.id });
+
+ // Block: the universe still has a live child series.
+ await expect(svc.deleteUniverse(w.id)).rejects.toMatchObject({
+ code: svc.ERR_HAS_LIVE_SERIES,
+ blockingSeries: [{ id: ser.id, name: "Child Arc" }],
+ });
+ // Universe is untouched.
+ expect(await svc.listUniverses()).toHaveLength(1);
+
+ // Once the child is gone, the delete succeeds.
+ await seriesSvc.deleteSeries(ser.id);
+ await expect(svc.deleteUniverse(w.id)).resolves.toMatchObject({ id: w.id });
+ expect(await svc.listUniverses()).toEqual([]);
+ });
+
it("deleteUniverse unlinks linked media collections (releases the rename-lock)", async () => {
const collections = await import("./mediaCollections.js");
const w = await seedWorld();