Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: opaque merge modal background + AI-assisted field merge for duplicate Universes/Series
[._.]/ Adam Eivyca7e88b006fc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 082bcff006..5b8a8a041d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@ TBD## Fixed+- **Universe / Series merge modal: opaque background + AI-assisted field merge.** The merge dialog (Sharing → Duplicates and the inline Universes-page resolver) had a transparent panel that bled into the underlying list, making the conflict editor hard to read. It now uses the standard `port-card` card chrome with the same `max-h-[85vh] overflow-y-auto` scroll envelope as the rest of the app's modals. Alongside that, conflicting *text* fields (e.g. two divergent `starterPrompt`s on a duplicate "Clandestiny") gain a **Merge with AI** button: the configured AI provider receives both values plus the survivor's style context (logline / style notes / embrace influences) and returns one unified value per field, which the modal renders in an editable textarea and ships as `fieldOverrides`. Each row keeps the original Keep-survivor / Use-folded picker — switching back discards the AI value for that row. Non-text conflicts (numeric, object-shaped) skip AI and stay on the manual picker. New routes: `POST /api/universe-builder/merge/ai-resolve` and `POST /api/pipeline/series/merge/ai-resolve`.- **Ollama model installs no longer die on a transient "EOF".** Pulling a model from the Local LLMs page could fail with a bare `EOF` status and leave the model uninstalled. Ollama streams pull progress as NDJSON, and a transient network hiccup between Ollama and the model registry/CDN surfaces mid-stream as an `{"error":"EOF"}` frame (or the response read dropping outright). PortOS gave up on the first occurrence — even though the `ollama` CLI silently retries these and the pull is resumable (partial blobs are kept). `pullModel` now retries the transient/EOF class up to 3 attempts with a linear backoff, continuing from the partial download rather than restarting; non-transient errors (bad model name, missing manifest) still fail fast. The install banner shows a "retrying after network error" notice during the backoff instead of stalling.- **TUI agents no longer try (and fail) to `/quit` at the end of a run.** The spawned-agent completion workflow used to tell the agent to write its `.agent-done` sentinel and then run `/quit`. In current Claude Code, `/quit` is a UI command that can't be invoked programmatically — so the agent attempted `Skill(quit)`, hit an error, and printed a confusing "please run /quit yourself" message before idling. The prompt now treats the sentinel as the sole done signal (PortOS finalizes the run within 2s of seeing it and closes the session itself) and explicitly tells the agent not to run `/quit`.- **Tabbed sub-nav strips no longer drift vertically on mobile.** The horizontally-scrolling sub-nav tabs (Media Gen and every other page that uses the shared `TabPills` primitive) could be dragged diagonally/vertically on iOS, producing an uneven, wonky scroll. Both `TabPills` scroll containers now set `touch-action: pan-x` so touch gestures pan the strip horizontally while vertical drags pass through to normal page scrolling.diff --git a/client/src/components/sharing/DuplicatesTab.jsx b/client/src/components/sharing/DuplicatesTab.jsxindex 257693fb34..25511c1e61 100644--- a/client/src/components/sharing/DuplicatesTab.jsx+++ b/client/src/components/sharing/DuplicatesTab.jsx@@ -37,7 +37,7 @@ export default function DuplicatesTab() {useEffect(() => { load(); }, [load]);- const { merge, setMerge, openMerge, runPreview, executeMerge } = useRecordMerge({ onMerged: load });+ const { merge, setMerge, openMerge, runPreview, executeMerge, runAIMerge, updateOverride } = useRecordMerge({ onMerged: load });const groupKey = (kind, normalizedName, scope = '') => `${kind}:${scope}:${normalizedName}`;@@ -83,6 +83,7 @@ export default function DuplicatesTab() {<MergeModalmerge={merge} setMerge={setMerge} onExecute={executeMerge}onRepreview={(survivorId, loserId) => runPreview(merge.kind, survivorId, loserId, merge.records)}+ onAIMerge={runAIMerge} onUpdateOverride={updateOverride}/>)}</div>diff --git a/client/src/components/sharing/DuplicatesTab.test.jsx b/client/src/components/sharing/DuplicatesTab.test.jsxindex 748dafd5e0..a291543cc0 100644--- a/client/src/components/sharing/DuplicatesTab.test.jsx+++ b/client/src/components/sharing/DuplicatesTab.test.jsx@@ -9,10 +9,12 @@ vi.mock('../../services/api', () => ({mergeUniverses: vi.fn(),previewSeriesMerge: vi.fn(),mergeSeries: vi.fn(),+ aiResolveUniverseMerge: vi.fn(),+ aiResolveSeriesMerge: vi.fn(),updateUniverse: vi.fn(),updatePipelineSeries: vi.fn(),}));-vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: 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> }));@@ -64,6 +66,46 @@ describe('DuplicatesTab', () => {));});+ it('Merge with AI populates an editable override and ships it as fieldOverrides on submit', async () => {+ api.previewUniverseMerge.mockResolvedValue({+ conflicts: [{ field: 'starterPrompt', survivorValue: 'A', loserValue: 'B' }],+ cascade: { seriesToRepoint: [], loserCollectionItemCount: 0 },+ });+ api.aiResolveUniverseMerge.mockResolvedValue({+ merged: { starterPrompt: 'Unified A+B' }, skipped: [], llm: { provider: 'codex', model: null }, runId: 'r1',+ });+ 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(screen.getByText('starterPrompt')).toBeInTheDocument());++ // Click Merge with AI — the AI-resolve API is called with the conflict field list.+ await user.click(screen.getByRole('button', { name: /Merge with AI/ }));+ await waitFor(() => expect(api.aiResolveUniverseMerge).toHaveBeenCalledWith(+ { survivorId: 'u-new', loserId: 'u-old', fields: ['starterPrompt'] },+ expect.anything(),+ ));++ // The AI-merged value is rendered in an editable textarea and the row+ // automatically switches to the "AI merged" choice.+ const ta = await screen.findByLabelText('AI-merged starterPrompt');+ expect(ta.value).toBe('Unified A+B');+ await user.clear(ta);+ await user.type(ta, 'Hand-tweaked unified');++ // Execute — survivor/loser choice is dropped (server's enum doesn't accept 'ai'),+ // override is sent as fieldOverrides.+ await user.click(screen.getByRole('button', { name: /^Merge$/ }));+ await waitFor(() => expect(api.mergeUniverses).toHaveBeenCalledWith(+ { survivorId: 'u-new', loserId: 'u-old', fieldChoices: {}, fieldOverrides: { starterPrompt: 'Hand-tweaked unified' } },+ 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();diff --git a/client/src/components/sharing/MergeModal.jsx b/client/src/components/sharing/MergeModal.jsxindex 10d15ccf23..df1064af61 100644--- a/client/src/components/sharing/MergeModal.jsx+++ b/client/src/components/sharing/MergeModal.jsx@@ -1,14 +1,15 @@/**- * Merge modal for duplicate Universes / Series. Renders the survivor picker,- * the per-field conflict resolver (survivor vs. folded value), and the cascade- * summary, then fires the merge. Driven entirely by the `merge` state object- * managed by `useRecordMerge` — shared between Sharing → Duplicates- * (DuplicatesTab) and the inline resolver on the Universes page.+ * Merge modal for duplicate Universes / Series. Survivor picker + per-field+ * conflict resolver (survivor / folded / AI-merged) + cascade summary. Driven+ * by the `merge` state object from `useRecordMerge`. The AI path synthesizes+ * a unified value per text conflict that's editable in-place and shipped as+ * `fieldOverrides`; switching back to survivor/folded discards the override.*/-import { Loader2, GitMerge } from 'lucide-react';+import { Loader2, GitMerge, Sparkles } from 'lucide-react';import Modal from '../ui/Modal';import InlineDiff from '../ui/InlineDiff';+import { MERGE_CHOICE } from '../../hooks/useRecordMerge';// Conflict values can be strings or structured (arrays/objects). Render strings// as-is so InlineDiff can word-diff them; pretty-print everything else.@@ -17,11 +18,17 @@ const asText = (v) => {return typeof v === 'string' ? v : JSON.stringify(v, null, 2);};-export default function MergeModal({ merge, setMerge, onExecute, onRepreview }) {- const { kind, records, survivorId, loserId, preview, choices, busy } = merge;+// Only string-vs-string conflicts can be AI-merged. The server enforces the+// same filter but we use it here too so the per-field "AI" button is only+// shown when it would actually run.+const isStringConflict = (c) => typeof c?.survivorValue === 'string' && typeof c?.loserValue === 'string';++export default function MergeModal({ merge, setMerge, onExecute, onRepreview, onAIMerge, onUpdateOverride }) {+ const { kind, records, survivorId, loserId, preview, choices, overrides = {}, busy, aiBusy } = merge;const conflicts = preview?.conflicts || [];const cascade = preview?.cascade || {};const multi = records.length > 2; // 3+ copies fold one pair at a time+ const aiEligible = conflicts.some(isStringConflict);const setChoice = (field, val) => setMerge((m) => ({ ...m, choices: { ...m.choices, [field]: val } }));const swapSurvivor = (newSurvivorId) => {@@ -35,7 +42,7 @@ export default function MergeModal({ merge, setMerge, onExecute, onRepreview })return (<Modal open onClose={() => !busy && setMerge(null)} size="2xl" ariaLabel="Merge duplicates">- <div className="p-5 space-y-4">+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4 max-h-[85vh] overflow-y-auto"><h2 className="text-lg font-semibold text-white flex items-center gap-2"><GitMerge size={18} /> Merge {kind}</h2><div>@@ -71,20 +78,53 @@ export default function MergeModal({ merge, setMerge, onExecute, onRepreview }){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="flex items-center justify-between mb-2 gap-2">+ <label className="block text-xs text-gray-400">{conflicts.length} conflicting field(s) — pick which value wins:</label>+ {onAIMerge && aiEligible && (+ <button+ type="button"+ onClick={onAIMerge}+ disabled={aiBusy || busy}+ title="Use the configured AI provider to synthesize a unified value per text-string field"+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded border border-port-accent/60 text-port-accent text-xs font-medium hover:bg-port-accent/10 disabled:opacity-50"+ >+ {aiBusy ? <Loader2 className="animate-spin" size={12} /> : <Sparkles size={12} />} Merge with AI+ </button>+ )}+ </div><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>+ {conflicts.map((c) => {+ const choice = choices[c.field];+ const canAI = isStringConflict(c);+ const showOverride = choice === MERGE_CHOICE.AI;+ return (+ <div key={c.field} className="border border-port-border rounded p-3 bg-port-bg/40">+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">+ <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, MERGE_CHOICE.SURVIVOR)} className={`px-2 py-0.5 rounded ${choice === MERGE_CHOICE.SURVIVOR ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Keep survivor</button>+ <button type="button" onClick={() => setChoice(c.field, MERGE_CHOICE.LOSER)} className={`px-2 py-0.5 rounded ${choice === MERGE_CHOICE.LOSER ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Use folded</button>+ {canAI && typeof overrides[c.field] === 'string' && (+ <button type="button" onClick={() => setChoice(c.field, MERGE_CHOICE.AI)} className={`inline-flex items-center gap-1 px-2 py-0.5 rounded ${choice === MERGE_CHOICE.AI ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>+ <Sparkles size={10} /> AI merged+ </button>+ )}+ </div></div>+ {showOverride ? (+ <textarea+ value={overrides[c.field] || ''}+ onChange={(e) => onUpdateOverride?.(c.field, e.target.value)}+ rows={Math.min(10, Math.max(3, (overrides[c.field] || '').split('\n').length + 1))}+ className="w-full px-2 py-1.5 rounded bg-port-bg border border-port-border text-sm text-white font-mono leading-snug"+ aria-label={`AI-merged ${c.field}`}+ />+ ) : (+ <InlineDiff oldText={asText(c.survivorValue)} newText={asText(c.loserValue)} />+ )}</div>- <InlineDiff oldText={asText(c.survivorValue)} newText={asText(c.loserValue)} />- </div>- ))}+ );+ })}</div></div>)}@@ -103,7 +143,7 @@ export default function MergeModal({ merge, setMerge, onExecute, onRepreview })<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}+ <button type="button" onClick={onExecute} disabled={busy || aiBusy || !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>diff --git a/client/src/hooks/useRecordMerge.js b/client/src/hooks/useRecordMerge.jsindex 85f705b022..86edcc26dc 100644--- a/client/src/hooks/useRecordMerge.js+++ b/client/src/hooks/useRecordMerge.js@@ -2,26 +2,22 @@ import { useState, useCallback } from 'react';import toast from '../components/ui/Toast';import {previewUniverseMerge, mergeUniverses, previewSeriesMerge, mergeSeries,+ aiResolveUniverseMerge, aiResolveSeriesMerge,} from '../services/api';+// `choices[field]` value space. SURVIVOR/LOSER mirror the server's Zod enum;+// AI is client-only and means "use the value at overrides[field]" (populated+// by runAIMerge, editable via updateOverride). Kept as a const so the modal+// and the executeMerge wire-payload filter agree on the legal set.+export const MERGE_CHOICE = { SURVIVOR: 'survivor', LOSER: 'loser', AI: 'ai' };+// Orchestrates the duplicate-record merge flow (Universe or Series): open →-// dry-run preview → resolve field conflicts → execute. The returned `merge`-// state object drives <MergeModal>; `openMerge`/`runPreview`/`executeMerge`-// are the handlers it (and the trigger button) call. `onMerged` runs after a-// successful merge so the caller can refresh its list (the loser is tombstoned).-//-// Shared between Sharing → Duplicates (DuplicatesTab) and the inline resolver-// on the Universes page so both surface identical merge behavior.-//-// Usage:-// const { merge, setMerge, openMerge, runPreview, executeMerge } =-// useRecordMerge({ onMerged: reload });-// <DuplicateGroup kind="universe" group={g} onMerge={openMerge} ... />-// {merge && <MergeModal merge={merge} setMerge={setMerge}-// onExecute={executeMerge}-// onRepreview={(s, l) => runPreview(merge.kind, s, l, merge.records)} />}+// dry-run preview → resolve field conflicts → execute. Drives <MergeModal>+// from both Sharing → Duplicates (DuplicatesTab) and the inline resolver on+// the Universes page. `onMerged` refreshes the caller's list after the loser+// is tombstoned.export function useRecordMerge({ onMerged } = {}) {- // { kind, records, survivorId, loserId, preview, choices, busy }+ // { kind, records, survivorId, loserId, preview, choices, overrides, aiBusy, busy }const [merge, setMerge] = useState(null);const runPreview = useCallback(async (kind, survivorId, loserId, records) => {@@ -29,7 +25,7 @@ export function useRecordMerge({ onMerged } = {}) {// 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, kind, survivorId, loserId, records: records || m.records, preview: null, choices: {}, overrides: {}, busy: true,} : m));const previewFn = kind === 'universe' ? previewUniverseMerge : previewSeriesMerge;const result = await previewFn({ survivorId, loserId }, { silent: true }).catch((err) => {@@ -40,6 +36,7 @@ export function useRecordMerge({ onMerged } = {}) {...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'])),+ overrides: {},busy: false,} : m));}, []);@@ -47,16 +44,80 @@ export function useRecordMerge({ onMerged } = {}) {const openMerge = useCallback(async (kind, records) => {const survivorId = records[0].id;const loserId = records[1].id;- setMerge({ kind, records, survivorId, loserId, preview: null, choices: {}, busy: true });+ setMerge({ kind, records, survivorId, loserId, preview: null, choices: {}, overrides: {}, busy: true });await runPreview(kind, survivorId, loserId, records);}, [runPreview]);+ // Synthesize a unified value per conflicting text field via the configured+ // AI provider; populate `overrides[field]` + flip `choices[field]` to AI so+ // the modal renders the editable textarea. Skipped fields (non-string) stay+ // on their existing survivor/loser choice.+ //+ // Staleness: if the user swaps survivor/loser (re-preview) while the AI call+ // is in flight, the survivorId/loserId/kind snapshot below will no longer+ // match the latest state — drop the response on the floor in that case so a+ // late AI result doesn't write overrides for the wrong pair.+ const runAIMerge = useCallback(async () => {+ if (!merge?.preview) return;+ const { kind, survivorId, loserId, preview } = merge;+ const fields = (preview.conflicts || []).map((c) => c.field);+ if (fields.length === 0) return;+ setMerge((m) => (m ? { ...m, aiBusy: true } : m));+ const resolveFn = kind === 'universe' ? aiResolveUniverseMerge : aiResolveSeriesMerge;+ const result = await resolveFn({ survivorId, loserId, fields }, { silent: true }).catch((err) => {+ toast.error(`AI merge failed: ${err.message}`);+ return null;+ });+ let applied = false;+ setMerge((m) => {+ if (!m) return m;+ if (!result) return { ...m, aiBusy: false };+ if (m.kind !== kind || m.survivorId !== survivorId || m.loserId !== loserId) {+ return { ...m, aiBusy: false };+ }+ const merged = result.merged || {};+ const nextOverrides = { ...m.overrides };+ const nextChoices = { ...m.choices };+ for (const [field, value] of Object.entries(merged)) {+ if (typeof value !== 'string') continue;+ nextOverrides[field] = value;+ nextChoices[field] = MERGE_CHOICE.AI;+ }+ applied = true;+ return { ...m, aiBusy: false, overrides: nextOverrides, choices: nextChoices };+ });+ if (!applied) return;+ if (result?.skipped?.length) {+ toast.warning(`AI skipped ${result.skipped.length} non-text field(s) — pick those manually.`);+ } else {+ toast.success('AI merged the conflicting fields — review and edit before applying.');+ }+ }, [merge]);++ const updateOverride = useCallback((field, value) => {+ setMerge((m) => (m ? { ...m, overrides: { ...m.overrides, [field]: value } } : m));+ }, []);+const executeMerge = useCallback(async () => {if (!merge) return;- const { kind, survivorId, loserId, choices } = merge;+ const { kind, survivorId, loserId, choices, overrides } = merge;+ const fieldOverrides = {};+ const fieldChoices = {};+ for (const [field, c] of Object.entries(choices || {})) {+ if (c === MERGE_CHOICE.AI && typeof overrides?.[field] === 'string') {+ fieldOverrides[field] = overrides[field];+ } else if (c === MERGE_CHOICE.SURVIVOR || c === MERGE_CHOICE.LOSER) {+ fieldChoices[field] = c;+ }+ }setMerge((m) => (m ? { ...m, busy: true } : m));const run = kind === 'universe' ? mergeUniverses : mergeSeries;- const ok = await run({ survivorId, loserId, fieldChoices: choices }, { silent: true })+ // Only include `fieldOverrides` when populated — keeps the wire payload+ // identical to pre-AI-merge clients on the common "no AI used" path.+ const payload = Object.keys(fieldOverrides).length > 0+ ? { survivorId, loserId, fieldChoices, fieldOverrides }+ : { survivorId, loserId, fieldChoices };+ const ok = await run(payload, { silent: true }).then(() => true).catch((err) => { toast.error(`Merge failed: ${err.message}`); return false; });if (ok) {@@ -68,5 +129,5 @@ export function useRecordMerge({ onMerged } = {}) {}}, [merge, onMerged]);- return { merge, setMerge, openMerge, runPreview, executeMerge };+ return { merge, setMerge, openMerge, runPreview, executeMerge, runAIMerge, updateOverride };}diff --git a/client/src/pages/Universes.jsx b/client/src/pages/Universes.jsxindex 39a2bf0141..28ce7a4717 100644--- a/client/src/pages/Universes.jsx+++ b/client/src/pages/Universes.jsx@@ -176,7 +176,7 @@ export default function Universes() {return loadDuplicates();}, [loadDuplicates]);- const { merge, setMerge, openMerge, runPreview, executeMerge } = useRecordMerge({ onMerged: refresh });+ const { merge, setMerge, openMerge, runPreview, executeMerge, runAIMerge, updateOverride } = useRecordMerge({ onMerged: refresh });// "Keep both" hides a group for the session; the records are legitimately// distinct. Filtered against the live group list so a newly-merged group that@@ -360,6 +360,7 @@ export default function Universes() {<MergeModalmerge={merge} setMerge={setMerge} onExecute={executeMerge}onRepreview={(survivorId, loserId) => runPreview(merge.kind, survivorId, loserId, merge.records)}+ onAIMerge={runAIMerge} onUpdateOverride={updateOverride}/>)}</div>diff --git a/client/src/services/apiSyncReview.js b/client/src/services/apiSyncReview.jsindex ff94d9cccf..30324fda43 100644--- a/client/src/services/apiSyncReview.js+++ b/client/src/services/apiSyncReview.js@@ -23,6 +23,16 @@ export const previewSeriesMerge = (body, options) =>export const mergeSeries = (body, options) =>request('/pipeline/series/merge', { method: 'POST', body: JSON.stringify(body), ...options });+// AI-assisted merge: asks the configured AI provider to synthesize a single+// unified text per conflict field, returning { merged: { [field]: string },+// skipped, llm, runId }. The caller applies `merged` as `fieldOverrides` on+// the subsequent merge/preview + merge calls.+export const aiResolveUniverseMerge = (body, options) =>+ request('/universe-builder/merge/ai-resolve', { method: 'POST', body: JSON.stringify(body), ...options });++export const aiResolveSeriesMerge = (body, options) =>+ request('/pipeline/series/merge/ai-resolve', { 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.diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex a73baeded4..03e781cec0 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -57,6 +57,7 @@ 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 { mergeFieldsWithAI } from '../services/recordMergeAI.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';@@ -869,6 +870,18 @@ 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({}),+ // Free-form per-field values that win over the survivor/loser binary —+ // populated by the AI-merge flow (a third unified option) and optionally+ // tweaked by the user before submit.+ fieldOverrides: z.record(z.string()).optional().default({}),+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++const seriesMergeAIResolveSchema = 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),+ fields: z.array(z.string().trim().min(1).max(64)).min(1).max(20),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });router.get('/series/duplicates', asyncHandler(async (_req, res) => {@@ -877,18 +890,38 @@ router.get('/series/duplicates', asyncHandler(async (_req, res) => {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 })+ const preview = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides }).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)+ const result = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices, { fieldOverrides: body.fieldOverrides }).catch((err) => { throw mapServiceError(err); });res.json(result);}));+// Ask the configured AI provider to merge specific conflicting text fields+// into a single unified value per field. Same shape as the universe-side+// /universe-builder/merge/ai-resolve route.+router.post('/series/merge/ai-resolve', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesMergeAIResolveSchema, req.body ?? {});+ const [survivor, loser] = await Promise.all([+ seriesSvc.getSeries(body.survivorId).catch((err) => { throw mapServiceError(err); }),+ seriesSvc.getSeries(body.loserId).catch((err) => { throw mapServiceError(err); }),+ ]);+ const result = await mergeFieldsWithAI({+ kind: 'series',+ survivor,+ loser,+ fields: body.fields,+ providerId: body.providerId,+ model: body.model,+ });+ res.json(result);+}));+router.get('/series/:id', asyncHandler(async (req, res) => {const s = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(s);diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 44932c535a..80f041a6db 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -35,6 +35,7 @@ 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 { mergeFieldsWithAI } from '../services/recordMergeAI.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';@@ -410,6 +411,18 @@ 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({}),+ // Free-form per-field values that win over the survivor/loser binary —+ // populated by the AI-merge flow (a third unified option) and optionally+ // tweaked by the user before submit.+ fieldOverrides: z.record(z.string()).optional().default({}),+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++const mergeAIResolveSchema = z.object({+ survivorId: z.string().trim().min(1).max(128),+ loserId: z.string().trim().min(1).max(128),+ fields: z.array(z.string().trim().min(1).max(64)).min(1).max(20),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });router.get('/duplicates', asyncHandler(async (_req, res) => {@@ -418,18 +431,39 @@ router.get('/duplicates', asyncHandler(async (_req, res) => {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 })+ const preview = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides }).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)+ const result = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { fieldOverrides: body.fieldOverrides }).catch((err) => { throw mapServiceError(err); });res.json(result);}));+// Ask the configured AI provider to merge specific conflicting text fields+// into a single unified value per field. Returns `{ merged, skipped, llm, runId }`+// — the client applies `merged` as `fieldOverrides` on the subsequent+// /merge or /merge/preview call. No record state is mutated here.+router.post('/merge/ai-resolve', asyncHandler(async (req, res) => {+ const body = validateRequest(mergeAIResolveSchema, req.body ?? {});+ const [survivor, loser] = await Promise.all([+ svc.getUniverse(body.survivorId).catch((err) => { throw mapServiceError(err); }),+ svc.getUniverse(body.loserId).catch((err) => { throw mapServiceError(err); }),+ ]);+ const result = await mergeFieldsWithAI({+ kind: 'universe',+ survivor,+ loser,+ fields: body.fields,+ providerId: body.providerId,+ model: body.model,+ });+ 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.referenceSheetImageRefdiff --git a/server/services/recordMerge.js b/server/services/recordMerge.jsindex b0429bcaf4..ccd380203f 100644--- a/server/services/recordMerge.js+++ b/server/services/recordMerge.js@@ -173,14 +173,28 @@ const isEmptyScalar = (v) => v === null || v === undefined || (typeof v === 'str* - autoResolved: only one side non-empty → take it (no prompt needed).* - equal / both-empty → survivor value, silently.* `fieldChoices` is `{ [field]: 'survivor' | 'loser' }`.+ * `fieldOverrides` is `{ [field]: any }` — if a field appears here, the value+ * is taken verbatim and the survivor/loser binary is ignored (used by the+ * AI-merge flow which produces a unified third option, editable by the user).+ * Overrides skip the conflict gate even when both sides differ, so an explicit+ * AI/user-edited value flows through without a redundant 'survivor'|'loser'+ * choice.*/-const resolveScalars = (fields, survivor, loser, fieldChoices = {}) => {+const resolveScalars = (fields, survivor, loser, fieldChoices = {}, fieldOverrides = {}) => {const values = {};const conflicts = [];const autoResolved = [];for (const field of fields) {const sv = survivor[field];const lv = loser[field];+ // Explicit override wins outright. Use Object.prototype.hasOwnProperty so+ // an empty-string override (user cleared the AI-merged value to mean+ // "blank this field") is honored instead of falling through to the+ // survivor/loser picker.+ if (Object.prototype.hasOwnProperty.call(fieldOverrides, field)) {+ values[field] = fieldOverrides[field];+ continue;+ }const sEmpty = isEmptyScalar(sv);const lEmpty = isEmptyScalar(lv);if (sEmpty && lEmpty) { values[field] = sv ?? lv ?? ''; continue; }@@ -208,8 +222,8 @@ const SERIES_SCALARS = [];/** 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);+export const buildUniverseUnion = (survivor, loser, fieldChoices = {}, fieldOverrides = {}) => {+ const { values, conflicts, autoResolved } = resolveScalars(UNIVERSE_SCALARS, survivor, loser, fieldChoices, fieldOverrides);const record = {...values,categories: unionCategories(survivor.categories, loser.categories),@@ -223,8 +237,8 @@ export const buildUniverseUnion = (survivor, loser, fieldChoices = {}) => {};/** 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);+export const buildSeriesUnion = (survivor, loser, fieldChoices = {}, fieldOverrides = {}) => {+ const { values, conflicts, autoResolved } = resolveScalars(SERIES_SCALARS, survivor, loser, fieldChoices, fieldOverrides);const record = {...values,seasons: unionSeasons(survivor.seasons, loser.seasons),@@ -248,14 +262,14 @@ const requireResolved = (conflicts) => {* 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 } = {}) {+export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { dryRun = false, fieldOverrides = {} } = {}) {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);+ const { record, conflicts, autoResolved } = buildUniverseUnion(survivor, loser, fieldChoices, fieldOverrides);// Cascade preview: which series re-point, how many collection items fold.const childSeries = (await listSeries()).filter((s) => s.universeId === loserId);@@ -311,7 +325,7 @@ export async function mergeUniverses(survivorId, loserId, fieldChoices = {}, { d* 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 } = {}) {+export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryRun = false, fieldOverrides = {} } = {}) {if (!survivorId || !loserId || survivorId === loserId) {throw makeErr('survivorId and loserId must be distinct', ERR_VALIDATION);}@@ -329,7 +343,7 @@ export async function mergeSeries(survivorId, loserId, fieldChoices = {}, { dryRthrow makeErr('Series can only be merged within the same universe', ERR_VALIDATION);}- const { record, conflicts, autoResolved } = buildSeriesUnion(survivor, loser, fieldChoices);+ const { record, conflicts, autoResolved } = buildSeriesUnion(survivor, loser, fieldChoices, fieldOverrides);const loserCollection = await findCollectionBySeriesId(loserId);// Issues are reassigned to the survivor un-grouped; count for the preview.diff --git a/server/services/recordMerge.test.js b/server/services/recordMerge.test.jsindex e3b43427ef..9264e367e2 100644--- a/server/services/recordMerge.test.js+++ b/server/services/recordMerge.test.js@@ -98,6 +98,28 @@ describe('recordMerge — pure union helpers', () => {expect(conflicts).toEqual([]);expect(record.starterPrompt).toBe('B');});++ it('buildUniverseUnion fieldOverrides beat survivor/loser binary even when both differ', () => {+ const { conflicts, record } = merge.buildUniverseUnion(+ { name: 'Dup', starterPrompt: 'A', categories: {}, influences: {}, characters: [], places: [], objects: [] },+ { name: 'Dup', starterPrompt: 'B', categories: {}, influences: {}, characters: [], places: [], objects: [] },+ { starterPrompt: 'survivor' }, // ignored — override wins+ { starterPrompt: 'A + B unified' },+ );+ expect(conflicts).toEqual([]);+ expect(record.starterPrompt).toBe('A + B unified');+ });++ it('buildUniverseUnion fieldOverrides honor empty-string clears', () => {+ const { conflicts, record } = merge.buildUniverseUnion(+ { name: 'Dup', starterPrompt: 'A', categories: {}, influences: {}, characters: [], places: [], objects: [] },+ { name: 'Dup', starterPrompt: 'B', categories: {}, influences: {}, characters: [], places: [], objects: [] },+ {},+ { starterPrompt: '' }, // explicit clear via override+ );+ expect(conflicts).toEqual([]);+ expect(record.starterPrompt).toBe('');+ });});describe('recordMerge — mergeUniverses (integration)', () => {diff --git a/server/services/recordMergeAI.js b/server/services/recordMergeAI.jsnew file mode 100644index 0000000000..7d5b7ade34--- /dev/null+++ b/server/services/recordMergeAI.js@@ -0,0 +1,163 @@+/**+ * AI-assisted field merge for the duplicate-record merge flow. Synthesizes+ * one unified text per conflicting field; the UI ships the result as+ * `fieldOverrides` (consumed by `recordMerge.js#resolveScalars`). Pure+ * preview — no record state is mutated here.+ *+ * Only fields where BOTH sides are non-empty strings are sent to the LLM;+ * non-string conflicts (objects, numbers) fall through to the manual picker.+ */++import { ServerError } from '../lib/errorHandler.js';+import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { stripPromptControlChars, buildUniverseStyleContext } from './universeBuilder.js';++export const ERR_NO_PROVIDER = 'MERGE_AI_NO_PROVIDER';+export const ERR_NO_MERGEABLE_FIELDS = 'MERGE_AI_NO_MERGEABLE_FIELDS';+export const ERR_INVALID_JSON = 'LLM_INVALID_JSON';++const MAX_FIELD_CHARS = 4000;++const isMergeableString = (v) => typeof v === 'string' && v.trim().length > 0;++const buildPrompt = ({ kind, survivor, loser, fields }) => {+ const fieldBlocks = fields.map(({ field, survivorValue, loserValue }) => {+ const a = stripPromptControlChars(String(survivorValue)).slice(0, MAX_FIELD_CHARS);+ const b = stripPromptControlChars(String(loserValue)).slice(0, MAX_FIELD_CHARS);+ return `## ${field}\n### A\n${a}\n\n### B\n${b}`;+ }).join('\n\n');++ const survivorName = stripPromptControlChars(String(survivor?.name || 'Record A'));+ const loserName = stripPromptControlChars(String(loser?.name || 'Record B'));++ // Universe-kind merges include the survivor's style context so the LLM+ // synthesizes in-voice (matches the canonical pattern in+ // universeBuilderAutoSort). Series records have no equivalent helper, so+ // the prompt stays context-free in that branch.+ const styleSection = kind === 'universe' ? buildUniverseStyleContext(survivor, { escape: true }) : '';++ return `You are helping merge two duplicate ${kind} records that share a name but were edited independently. For each conflicting field, produce ONE unified value that preserves the substantive, distinct ideas from both inputs, removes redundancy, and reads naturally. Do NOT invent new facts; only synthesize what is already in A or B.++# Records+- A: "${survivorName}"+- B: "${loserName}"+${styleSection}+# Fields to merge+${fieldBlocks}++# Output contract+Return ONLY a JSON object of the form:+{ "merged": { "<field>": "<unified text>", ... } }+- Include EVERY field listed above as a key under "merged".+- Each value is a plain string — no markdown, no nested objects.+- No commentary, no code fences.`;+};++const isMergedShape = (o, expectedFields) => {+ if (!o || typeof o !== 'object') return false;+ if (!o.merged || typeof o.merged !== 'object') return false;+ return expectedFields.some((f) => typeof o.merged[f] === 'string');+};++/**+ * Run an AI-assisted merge over `fields` (subset of conflicting field names).+ * Returns `{ merged: { [field]: string }, llm: { provider, model }, runId, skipped }`.+ * `skipped` lists fields that were dropped because they weren't both non-empty+ * strings (caller renders them with the regular survivor/loser picker).+ *+ * @param {object} args+ * @param {'universe'|'series'} args.kind+ * @param {object} args.survivor — full survivor record+ * @param {object} args.loser — full loser record+ * @param {string[]} args.fields — conflict field names to attempt to merge+ * @param {string} [args.providerId]+ * @param {string} [args.model]+ */+export async function mergeFieldsWithAI({ kind, survivor, loser, fields, providerId, model }) {+ if (!survivor || !loser) {+ throw new ServerError('survivor and loser records are required', { status: 400, code: 'MERGE_AI_VALIDATION' });+ }+ if (!Array.isArray(fields) || fields.length === 0) {+ throw new ServerError('fields[] is required', { status: 400, code: 'MERGE_AI_VALIDATION' });+ }++ const mergeable = [];+ const skipped = [];+ for (const field of fields) {+ if (typeof field !== 'string' || !field) continue;+ const sv = survivor[field];+ const lv = loser[field];+ if (isMergeableString(sv) && isMergeableString(lv)) {+ mergeable.push({ field, survivorValue: sv, loserValue: lv });+ } else {+ skipped.push(field);+ }+ }+ if (mergeable.length === 0) {+ throw new ServerError(+ 'No mergeable text fields — AI merge only handles non-empty string conflicts',+ { status: 422, code: ERR_NO_MERGEABLE_FIELDS },+ );+ }++ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, {+ message: 'No AI provider available for AI-assisted merge',+ code: ERR_NO_PROVIDER,+ });++ const prompt = buildPrompt({ kind, survivor, loser, fields: mergeable });+ console.log(`🧬 mergeFieldsWithAI — kind=${kind} fields=${mergeable.map((f) => f.field).join(',')} via ${provider.name}/${selectedModel || 'default'}`);++ const expectedFields = mergeable.map((f) => f.field);+ const { text: raw, runId } = await runPromptThroughProvider({+ provider,+ model: selectedModel,+ prompt,+ source: 'record-merge-ai',+ });++ // Empty / non-string LLM responses route through the same typed error as+ // malformed JSON so the UI shows a single actionable message instead of a+ // generic 500. extractJson would also throw, but the message would be a+ // less useful "no matching JSON found".+ if (!raw || typeof raw !== 'string') {+ throw new ServerError(+ 'LLM returned an empty response for AI merge. Try a different model or rerun.',+ { status: 502, code: ERR_INVALID_JSON },+ );+ }++ const { value, lastError, lastPreview } = extractJsonShared(raw, {+ shapePredicate: (o) => isMergedShape(o, expectedFields),+ });+ if (!value || !value.merged || typeof value.merged !== 'object') {+ throw new ServerError(+ 'LLM returned invalid JSON for AI merge',+ {+ status: 502,+ code: ERR_INVALID_JSON,+ context: {+ details: {+ reason: lastError?.message || 'no matching JSON found',+ preview: lastPreview || '',+ },+ },+ },+ );+ }++ const merged = {};+ for (const field of expectedFields) {+ const v = value.merged[field];+ if (typeof v === 'string') merged[field] = v;+ }++ return {+ merged,+ skipped,+ llm: { provider: provider.id, model: selectedModel || null },+ runId,+ };+}diff --git a/server/services/recordMergeAI.test.js b/server/services/recordMergeAI.test.jsnew file mode 100644index 0000000000..864122e968--- /dev/null+++ b/server/services/recordMergeAI.test.js@@ -0,0 +1,159 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the prompt runner so the test never tries to spawn a CLI / API provider.+const resolveProviderAndModelMock = vi.fn();+const runPromptThroughProviderMock = vi.fn();+vi.mock('../lib/promptRunner.js', () => ({+ assertProvider: (provider, { message, code, status = 503 } = {}) => {+ if (provider) return;+ const err = new Error(message || 'No AI provider available');+ if (code) { err.status = status; err.code = code; }+ throw err;+ },+ resolveProviderAndModel: (...a) => resolveProviderAndModelMock(...a),+ runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),+}));++// universeBuilder.js pulls in fileUtils + collectionStore; stub those so the+// service import doesn't try to touch real disk just to read+// stripPromptControlChars.+vi.mock('../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null),+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn(async (_p, fallback) => fallback),+}));+vi.mock('./instances.js', async () => {+ const { mockNoPeers } = await import('../lib/mockPathsDataRoot.js');+ return mockNoPeers();+});+vi.mock('./sharing/peerSync.js', async () => {+ const { mockNoPeerSync } = await import('../lib/mockPathsDataRoot.js');+ return mockNoPeerSync();+});++const { mergeFieldsWithAI } = await import('./recordMergeAI.js');++const PROVIDER = { id: 'codex', name: 'Codex', type: 'cli' };++beforeEach(() => {+ resolveProviderAndModelMock.mockReset();+ runPromptThroughProviderMock.mockReset();+ resolveProviderAndModelMock.mockResolvedValue({ provider: PROVIDER, selectedModel: 'gpt-5-codex' });+});++describe('mergeFieldsWithAI', () => {+ it('returns the parsed `merged` map when the LLM responds with valid JSON', async () => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({ merged: { starterPrompt: 'Unified prompt', logline: 'Unified logline' } }),+ runId: 'run-1',+ });++ const result = await mergeFieldsWithAI({+ kind: 'universe',+ survivor: { name: 'Dup', starterPrompt: 'A', logline: 'L1' },+ loser: { name: 'Dup', starterPrompt: 'B', logline: 'L2' },+ fields: ['starterPrompt', 'logline'],+ });++ expect(result.merged).toEqual({ starterPrompt: 'Unified prompt', logline: 'Unified logline' });+ expect(result.skipped).toEqual([]);+ expect(result.runId).toBe('run-1');+ expect(result.llm).toEqual({ provider: 'codex', model: 'gpt-5-codex' });++ const promptArg = runPromptThroughProviderMock.mock.calls[0][0].prompt;+ expect(promptArg).toContain('starterPrompt');+ expect(promptArg).toContain('A');+ expect(promptArg).toContain('B');+ });++ it('skips non-string fields (e.g. number / object scalars) and reports them in `skipped`', async () => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({ merged: { starterPrompt: 'Unified' } }),+ runId: 'run-2',+ });++ const result = await mergeFieldsWithAI({+ kind: 'series',+ survivor: { starterPrompt: 'A', issueCountTarget: 6, arc: { beats: [] } },+ loser: { starterPrompt: 'B', issueCountTarget: 12, arc: { beats: ['x'] } },+ fields: ['starterPrompt', 'issueCountTarget', 'arc'],+ });++ expect(result.merged).toEqual({ starterPrompt: 'Unified' });+ expect(result.skipped).toEqual(['issueCountTarget', 'arc']);+ });++ it('skips empty-string fields — AI merge only handles non-empty text on BOTH sides', async () => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({ merged: { logline: 'Unified' } }),+ runId: 'run-3',+ });++ const result = await mergeFieldsWithAI({+ kind: 'universe',+ survivor: { starterPrompt: 'A', logline: 'L1' },+ loser: { starterPrompt: ' ', logline: 'L2' }, // whitespace-only counts as empty+ fields: ['starterPrompt', 'logline'],+ });++ expect(result.merged).toEqual({ logline: 'Unified' });+ expect(result.skipped).toContain('starterPrompt');+ });++ it('throws MERGE_AI_NO_MERGEABLE_FIELDS when no field has both sides as non-empty strings', async () => {+ await expect(mergeFieldsWithAI({+ kind: 'universe',+ survivor: { starterPrompt: '' },+ loser: { starterPrompt: 'B' },+ fields: ['starterPrompt'],+ })).rejects.toMatchObject({ code: 'MERGE_AI_NO_MERGEABLE_FIELDS' });++ // No LLM call should have been made.+ expect(runPromptThroughProviderMock).not.toHaveBeenCalled();+ });++ it('throws MERGE_AI_NO_PROVIDER when no provider is configured', async () => {+ resolveProviderAndModelMock.mockResolvedValueOnce({ provider: null, selectedModel: null });++ await expect(mergeFieldsWithAI({+ kind: 'universe',+ survivor: { starterPrompt: 'A' },+ loser: { starterPrompt: 'B' },+ fields: ['starterPrompt'],+ })).rejects.toMatchObject({ code: 'MERGE_AI_NO_PROVIDER' });+ });++ it('throws LLM_INVALID_JSON when the LLM returns garbage', async () => {+ runPromptThroughProviderMock.mockResolvedValue({ text: 'not json at all', runId: 'run-bad' });++ await expect(mergeFieldsWithAI({+ kind: 'universe',+ survivor: { starterPrompt: 'A' },+ loser: { starterPrompt: 'B' },+ fields: ['starterPrompt'],+ })).rejects.toMatchObject({ code: 'LLM_INVALID_JSON' });+ });++ it('passes providerId + model through to resolveProviderAndModel', async () => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({ merged: { starterPrompt: 'Unified' } }),+ runId: 'run-4',+ });++ await mergeFieldsWithAI({+ kind: 'universe',+ survivor: { starterPrompt: 'A' },+ loser: { starterPrompt: 'B' },+ fields: ['starterPrompt'],+ providerId: 'claude-code',+ model: 'claude-opus-4-7',+ });++ expect(resolveProviderAndModelMock).toHaveBeenCalledWith({+ providerId: 'claude-code',+ model: 'claude-opus-4-7',+ });+ });+});