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

retain failed prose→canon extraction and add provider/model retry

[._.]/ Adam Eivy84d67996299f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9846ebca97..1c05dee722 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -54,6 +54,7 @@
## Fixed
+- **[canon-extraction-failure-retry] Failed prose→canon extraction is now retained and retryable with a different model.** When a pipeline issue's prose finishes, PortOS auto-extracts characters / places / objects into the linked universe. A provider failure (e.g. Codex safety-refusing the `object` kind, a Claude `401`, or a malformed-JSON response) used to be swallowed — and because all three kinds ran in one `Promise.all`, a single failing kind discarded the characters + places that *did* extract. Now extraction is per-kind resilient: the kinds that succeed are merged, the rest are flagged, and the outcome (`ok` / `partial` / `failed` + which kinds failed, the error, and the provider/model used) is persisted on the prose stage so it survives a reload. The Nouns stage surfaces a banner for partial/failed extractions and adds a provider/model picker next to "Extract from prose" (defaulting to the series' configured LLM) so you can keep retrying different models until the failed kinds come through — the entries that already landed are kept. The manual extract now routes through the pipeline endpoint (which accepts `prose` alongside `comicScript`/`teleplay` and a `model` override) so both the auto and manual paths stamp the same marker.
- **[catalog-character-sheet-enrichment] Catalog character stats now display.** The catalog detail page's read-only stats list read each stat's `.key` field, but the storyBible canon shape stores stats as `{ label, value }` — so every stat rendered with a blank label. The new editable stat editor and the read path both standardize on `.label`, so stats finally show (and edit) correctly.
- **[browser-navigate-ssrf-guard] SSRF guard on the browser navigate route.** `POST /api/browser/navigate` validated its URL with a bare `z.string().url()`, so `file://`, loopback, link-local, and cloud-metadata (`169.254.169.254`) targets were reachable — a redirect or agent-driven navigation could turn it into local-file exfiltration or a metadata-endpoint hit. It now reuses the catalog ingest guard (`isSafeIngestUrl`): http(s) only, with loopback / link-local / metadata hosts blocked (including IPv4-mapped-IPv6 bypass forms like `[::ffff:127.0.0.1]`). Private/LAN and Tailscale hosts stay allowed; `localhost`/`127.x` are now blocked, so navigate a local app by its LAN IP/hostname. Bad input also returns a clean 400 instead of a 500. The shared host guard was also hardened against two literal bypasses (deprecated IPv4-compatible IPv6 like `[::127.0.0.1]`, and trailing-FQDN-dot hosts like `localhost.`), which strengthens catalog URL ingest as well.
- **[catalog round-trip + cast multi-role] Catalog export → re-import keeps ref links, scraps, and non-primary payload keys; Cast unlink is role-precise.** Re-importing a JSON export bundle through Bulk Import now recreates the bundle's slice membership: the parser carries the bundle's own `ref` plus each row's `roleForExportedRef`, and the route falls back to them when no explicit `defaults.*Ref` override is supplied — so a re-imported slice is no longer invisible to "Appears in" and to future slice exports. The markdown parser now recognizes the ` ```json ` payload fence and the `### Scraps` subsection as body terminators and round-trips them into `payload.*` / a sibling `scraps[]` instead of polluting the primary description/summary with fence text. The Cast (from Catalog) panel's unlink now removes only the `(ingredient, role)` row that was unlinked, not every row sharing the ingredient id — correct when the same ingredient is linked to one record under multiple roles.
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index c2a11aaf1c..6fa4f251b7 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -16,14 +16,16 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Library, Loader2, Users, MapPin, Package,
- Settings as SettingsIcon, ChevronDown, ChevronRight,
+ Settings as SettingsIcon, ChevronDown, ChevronRight, AlertTriangle,
} from 'lucide-react';
import toast from '../../ui/Toast';
import {
getUniverse, updateUniverse,
- extractUniverseCanon, refineUniverseCharacter,
+ refineUniverseCharacter,
getUniverseSeriesNames,
} from '../../../services/apiUniverseBuilder';
+import { extractPipelineCanonFromScript } from '../../../services/apiPipeline';
+import { getProviders } from '../../../services/apiProviders';
import { getSettings, patchSettingsSlice, generateImage } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import {
@@ -70,7 +72,7 @@ const KINDS = [
},
];
-export default function NounsStage({ issue, series }) {
+export default function NounsStage({ issue, series, onStageUpdate }) {
const mountedRef = useMounted();
const prose = (issue.stages?.prose?.output || '').trim();
const proseReady = prose.length > 0;
@@ -200,6 +202,39 @@ export default function NounsStage({ issue, series }) {
const [extracting, setExtracting] = useState(false);
+ // Provider/model picker for the extraction run. Seeded from the series'
+ // configured LLM but overridable per attempt so the user can keep trying
+ // different models until extraction succeeds (e.g. after a Codex safety
+ // refusal or a malformed-JSON response). Empty string = "series default".
+ const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
+ const [extractProvider, setExtractProvider] = useState(series?.llm?.provider || '');
+ const [extractModel, setExtractModel] = useState(series?.llm?.model || '');
+ useEffect(() => {
+ getProviders()
+ .then((data) => {
+ if (!mountedRef.current) return;
+ setProviders(data?.providers || []);
+ setActiveProviderId(data?.activeProvider || null);
+ })
+ .catch(() => { /* dropdowns fall back to the series-default label */ });
+ }, [mountedRef]);
+
+ // Persisted outcome of the last prose→canon extraction. Read straight from
+ // the issue prop — it survives reload and is refreshed via `onStageUpdate`
+ // after a retry (success or failure), so no local mirror/effect is needed.
+ const canonExtraction = issue.stages?.prose?.canonExtraction || null;
+
+ // Models offered for the currently-picked extraction provider (or the series
+ // default when none is explicitly picked). Mirrors SeriesLlmPicker.
+ const seriesDefaultProviderId = series?.llm?.provider || activeProviderId;
+ const providerLabel = (pid) => providers.find((p) => p.id === pid)?.name || pid || 'Active provider';
+ const extractProviderModels = useMemo(() => {
+ const p = providers.find((x) => x.id === extractProvider)
+ || providers.find((x) => x.id === seriesDefaultProviderId);
+ return p?.models || [];
+ }, [providers, extractProvider, seriesDefaultProviderId]);
+
// Per-character in-flight refine. Tracking by id (not a single bool) so
// the user can fire refines in serial without the spinner jumping cards.
const [refiningCharacterId, setRefiningCharacterId] = useState(null);
@@ -220,15 +255,45 @@ export default function NounsStage({ issue, series }) {
const handleExtract = async () => {
if (!universe || !proseReady) return;
setExtracting(true);
- const result = await extractUniverseCanon(universe.id, { corpus: prose })
- .catch((err) => { toast.error(err.message || 'Extraction failed'); return null; });
+ // Route through the pipeline endpoint (not the universe one) so the server
+ // stamps the prose stage's canonExtraction marker — single source of truth
+ // shared with the post-prose auto-extract. Pass the picker's provider/model
+ // so a retry can use a different model than the one that just failed.
+ const result = await extractPipelineCanonFromScript(issue.id, 'prose', {
+ providerOverride: extractProvider || undefined,
+ model: extractModel || undefined,
+ }, { silent: true }).catch((err) => {
+ // A hard failure (every kind threw) is stamped `failed` server-side
+ // before the throw — mirror that onto the parent issue so the banner
+ // updates without a refetch and the user sees what to retry.
+ if (mountedRef.current) {
+ const failedMarker = {
+ status: 'failed',
+ error: err.message || 'Extraction failed',
+ failedKinds: KINDS.map((k) => k.singular),
+ provider: extractProvider, model: extractModel,
+ extracted: { characters: 0, places: 0, objects: 0 },
+ at: new Date().toISOString(),
+ };
+ onStageUpdate?.('prose', { ...issue.stages?.prose, canonExtraction: failedMarker });
+ toast.error(err.message || 'Extraction failed');
+ }
+ return null;
+ });
if (mountedRef.current) setExtracting(false);
if (!result || !mountedRef.current) return;
if (result.universe) setUniverse(result.universe);
- const counts = KINDS
- .map((k) => `${result.universe?.[k.key]?.length ?? 0} ${k.key}`)
- .join(', ');
- toast.success(`Bibles updated — ${counts}`);
+ // Propagate the stamped prose stage (with the fresh canonExtraction marker)
+ // up so the banner + retry-label update without a refetch.
+ if (result.issue?.stages?.prose) onStageUpdate?.('prose', result.issue.stages.prose, result.issue);
+ const e = result.extracted || {};
+ const counts = `${e.characters || 0} characters, ${e.places || 0} places, ${e.objects || 0} objects`;
+ if (result.canonExtraction?.status === 'partial') {
+ const failed = (result.canonExtraction.failedKinds || []).join(', ') || 'some kinds';
+ toast.error(`Extracted ${counts}, but ${failed} failed — pick a different model and retry`);
+ } else {
+ toast.success(`Bibles updated — ${counts}`);
+ }
};
// Queue a reference render. The filename ISN'T persisted onto the entry's
@@ -375,7 +440,7 @@ export default function NounsStage({ issue, series }) {
that universe.
</p>
</div>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<button
type="button"
onClick={openSettings}
@@ -384,6 +449,37 @@ export default function NounsStage({ issue, series }) {
>
<SettingsIcon size={12} /> Image gen
</button>
+ {/* Per-attempt provider/model override. Empty = series default, so a
+ first extract behaves exactly as before; the user only reaches for
+ these when retrying after a provider failure. */}
+ <select
+ value={extractProvider}
+ onChange={(e) => { setExtractProvider(e.target.value); setExtractModel(''); }}
+ disabled={extracting}
+ title="AI provider for extraction"
+ aria-label="Extraction provider"
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40"
+ >
+ <option value="">Series default ({providerLabel(seriesDefaultProviderId)})</option>
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ <select
+ value={extractModel}
+ onChange={(e) => setExtractModel(e.target.value)}
+ disabled={extracting || extractProviderModels.length === 0}
+ title="Model for extraction"
+ aria-label="Extraction model"
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40 max-w-[160px]"
+ >
+ <option value="">Default model</option>
+ {extractProviderModels.map((m) => {
+ const mid = typeof m === 'string' ? m : m.id;
+ const label = typeof m === 'string' ? m : (m.name || m.id);
+ return <option key={mid} value={mid}>{label}</option>;
+ })}
+ </select>
<button
type="button"
onClick={handleExtract}
@@ -392,11 +488,15 @@ export default function NounsStage({ issue, series }) {
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-40"
>
{extracting ? <Loader2 size={14} className="animate-spin" /> : <Library size={14} />}
- Extract from prose
+ {canonExtraction && canonExtraction.status !== 'ok' ? 'Retry extraction' : 'Extract from prose'}
</button>
</div>
</header>
+ {canonExtraction && canonExtraction.status !== 'ok' ? (
+ <CanonExtractionBanner extraction={canonExtraction} />
+ ) : null}
+
{!proseReady ? (
<p className="text-sm text-gray-400 italic">
Generate the prose stage first, then come back here to extract and curate the nouns.
@@ -436,6 +536,39 @@ export default function NounsStage({ issue, series }) {
);
}
+// Persisted failure/partial banner for the prose→canon extraction. `partial`
+// (some kinds landed, others failed — e.g. Codex safety-refused `object`) is a
+// warning; `failed` (nothing extracted) is an error. Both name the failed
+// kinds + the provider/model used and tell the user to retry with a different
+// model via the picker above.
+function CanonExtractionBanner({ extraction }) {
+ const partial = extraction.status === 'partial';
+ const failed = (extraction.failedKinds || []).join(', ') || 'extraction';
+ const used = [extraction.provider, extraction.model].filter(Boolean).join(' / ') || 'the configured model';
+ const tone = partial
+ ? 'border-port-warning/40 bg-port-warning/5 text-port-warning'
+ : 'border-port-error/40 bg-port-error/5 text-port-error';
+ return (
+ <div className={`rounded-lg border p-3 flex items-start gap-2 ${tone}`} role="alert">
+ <AlertTriangle size={16} className="mt-0.5 shrink-0" />
+ <div className="space-y-1 min-w-0">
+ <p className="text-sm font-medium">
+ {partial
+ ? `Some canon extracted, but ${failed} failed with ${used}.`
+ : `Canon extraction failed with ${used}.`}
+ </p>
+ {extraction.error ? (
+ <p className="text-xs text-gray-400 break-words">{extraction.error}</p>
+ ) : null}
+ <p className="text-xs text-gray-400">
+ Pick a different provider/model above and retry — the entries that already
+ landed are kept.
+ </p>
+ </div>
+ </div>
+ );
+}
+
function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {
const Icon = kind.icon;
const inIssue = useMemo(() => kind.match(prose, all), [prose, all, kind]);
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index c2b94d2947..a9bf853dc6 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -171,17 +171,21 @@ export const extractPipelineComicPages = (issueId, { force } = {}) =>
body: JSON.stringify({ force }),
});
-// Run canon extraction (characters/places/objects) against an issue's
-// comicScript or teleplay stage output and merge the result into the series'
-// linked universe. Auto-extract only fires after prose; this lets the writer
-// pull in minor entities introduced only in script-stage panel directions or
-// dialogue cues. Returns { universe, extracted: { characters, places, objects },
-// sourceStage, truncated } — `truncated` is true when the script exceeded
-// the server's 200K-char extract cap and was clamped before being sent to the LLM.
-export const extractPipelineCanonFromScript = (issueId, stageId, { providerOverride } = {}, options = {}) =>
+// Run canon extraction (characters/places/objects) against an issue's prose,
+// comicScript, or teleplay stage output and merge the result into the series'
+// linked universe. Auto-extract fires after prose; this lets the writer re-run
+// it (e.g. after a provider failure) with a chosen provider/model, or pull in
+// minor entities introduced only in script-stage panel directions / dialogue
+// cues. `providerOverride`/`model` override the series' configured LLM for this
+// run so the user can keep trying models until extraction succeeds. Returns
+// { universe, issue, canonExtraction, failures, extracted: { characters, places,
+// objects }, sourceStage, truncated } — `canonExtraction` is the persisted
+// outcome marker; `failures` lists kinds that threw; `truncated` is true when
+// the corpus exceeded the server's 200K-char extract cap and was clamped.
+export const extractPipelineCanonFromScript = (issueId, stageId, { providerOverride, model } = {}, options = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/extract-canon`, {
method: 'POST',
- body: JSON.stringify({ providerOverride }),
+ body: JSON.stringify({ providerOverride, model }),
...options,
});
diff --git a/docs/plans/2026-05-30-canon-extraction-failure-retry.md b/docs/plans/2026-05-30-canon-extraction-failure-retry.md
new file mode 100644
index 0000000000..40f75e7412
--- /dev/null
+++ b/docs/plans/2026-05-30-canon-extraction-failure-retry.md
@@ -0,0 +1,143 @@
+# Retain canon-extraction failures + retry with a chosen provider/model
+
+## Context
+
+When a pipeline issue's **prose** stage finishes, PortOS auto-extracts canon
+(characters / places / objects) from the prose into the linked universe. The
+user generated prose for issue #1 of *Giant*, then extraction failed:
+
+- Codex **safety-refused** the `objects` kind (`Invalid prompt: we've limited
+ access to this content for safety reasons…`).
+- The Claude Code fallback then failed with `401 Invalid authentication
+ credentials`.
+- A later manual "Extract from prose" (Nouns stage) hit
+ `Invalid JSON in AI response: Bad control character…`.
+
+Two problems surfaced:
+
+1. **The failure is swallowed.** `extractCanonFromProse` runs all three kinds
+ through `Promise.all` (`server/services/universeCanon.js:71`), so one kind
+ rejecting discards the characters + places that *did* extract. The auto path
+ only `console.warn`s and throws nothing away that's visible
+ (`server/services/pipeline/textStages.js:331`) — nothing is persisted, so
+ after reload the user has no idea extraction failed or why.
+2. **No way to retry with a different model.** The Nouns "Extract from prose"
+ button sends no provider/model override (`NounsStage.jsx:223`), so the user
+ can't keep trying different providers/models until one succeeds.
+
+**Outcome:** extraction becomes resilient to per-kind failure (keep the
+successes, flag the rest), the outcome is **persisted on the issue** so it
+survives reload, and the Nouns stage gets a **provider/model picker + a failure
+banner + retry** so the user can keep trying models until objects (or whatever
+failed) come through.
+
+Design decisions confirmed with user: **keep partial successes & flag failed
+kinds**, and **put the retry UI on the Nouns stage** (not also on Prose).
+
+## Server
+
+### 1. Thread `modelOverride` through the extraction stack
+- `server/lib/bibleExtractor.js` — `extractBible({ … , modelOverride })`, pass
+ `modelOverride` into `runStagedLLM` (it already supports `modelOverride`,
+ `stageRunner.js:218`).
+- `server/services/universeCanon.js` — `extractCanonFromProse` accepts
+ `opts.modelOverride`, forwards to each `extractBible` call (`runOne`).
+
+### 2. Per-kind resilience in `extractCanonFromProse` (`universeCanon.js`)
+- Replace the `Promise.all` / serial-reduce that throws on the first rejection
+ with **settle semantics**: run each kind, collect successes and
+ `failures: [{ kind, error }]`.
+- Merge only the kinds that **succeeded** into the universe (existing
+ `mergeExtractedBible` path, unchanged).
+- If **every** kind failed → throw a `ServerError` (hard failure, callers still
+ see an error). If **some** succeeded → resolve.
+- New return shape (additive): `{ universe, results, failures }`. Existing
+ callers read `universe`/`results` and ignore `failures` — backward compatible.
+
+### 3. Persist outcome on the issue (`server/services/pipeline/issues.js`)
+- Add a `canonExtraction` field to `emptyStage()` and `sanitizeStage()` so it
+ round-trips (sanitizeStage currently drops unknown fields). Shape, all
+ clamped/sanitized, `null` when never attempted:
+ ```js
+ canonExtraction: {
+ status: 'ok' | 'partial' | 'failed',
+ error: '', // trimmed message (clamp like errorMessage)
+ failedKinds: [], // ['object', …]
+ extracted: { characters: 0, places: 0, objects: 0 },
+ provider: '', model: '', // what was used, so the banner can say "failed with X"
+ at: null, // ISO timestamp
+ }
+ ```
+
+### 4. Stamp it from both extraction paths
+- `server/services/pipeline/textStages.js` (auto, after prose) — replace the
+ `.catch(console.warn)` with: on resolve stamp `ok`/`partial` (+ failedKinds,
+ counts, provider/model); on reject stamp `failed` (+ error). Still **non-fatal**
+ to the prose write.
+- `server/routes/pipeline.js` `POST /issues/:id/stages/:stageId/extract-canon`
+ — **allow `prose`** in addition to `comicScript`/`teleplay`; add `model` to
+ `extractCanonFromScriptSchema`; pass `providerOverride` + `modelOverride` to
+ `extractCanonFromProse`; after extraction **stamp
+ `issue.stages.<stageId>.canonExtraction`** (single source of truth) and
+ include the updated `issue` + `failures` in the response (alongside the
+ existing `universe`, `extracted`, `truncated`).
+
+This routes the Nouns manual extract through the **pipeline** endpoint (which
+knows the issue) instead of the universe endpoint, so the marker is stamped
+server-side for both auto and manual paths.
+
+## Client
+
+### 5. API wrapper (`client/src/services/apiPipeline.js`)
+- `extractPipelineCanonFromScript(issueId, stageId, { providerOverride, model })`
+ — add `model`; the existing param already carries `providerOverride`. Allow
+ `prose` as a stageId (just a string passthrough).
+
+### 6. Nouns stage UI (`client/src/components/pipeline/stages/NounsStage.jsx`)
+- Switch `handleExtract` from `extractUniverseCanon(universe.id, …)` to the
+ pipeline endpoint with `stageId='prose'`, passing the chosen provider/model.
+ Use the returned `universe` (setUniverse) and the returned `issue`'s
+ `stages.prose.canonExtraction` to drive the banner.
+- Add a compact **provider/model picker** next to "Extract from prose",
+ defaulting to `series.llm` (provider+model), letting the user override per
+ attempt. Reuse the dropdown pattern from
+ `client/src/components/pipeline/SeriesLlmPicker.jsx` (load via `getProviders`,
+ "Active provider" / "Default model" empty options) — extract a small local
+ presentational picker (local state, not persisted to the series) rather than
+ re-saving `series.llm`.
+- Render a **persisted failure/partial banner** from
+ `issue.stages.prose.canonExtraction` (seed local state from the prop, update
+ it from each attempt's response): e.g. *"Object extraction failed with Codex /
+ default: <error>. Pick a different provider/model and retry."* Use
+ `port-warning` styling for `partial`, `port-error` for `failed`. Hidden when
+ `status === 'ok'` or never attempted.
+- Toast on retry already exists; extend to mention failed kinds when partial.
+
+## Tests
+- `server/services/universeCanon.test.js` — add: one kind rejecting still merges
+ the others and returns `failures`; all kinds rejecting throws; `modelOverride`
+ is forwarded.
+- `server/routes/pipeline.test.js` — `prose` is an accepted stageId; `model`
+ passthrough; response includes the stamped `canonExtraction`; failure path
+ stamps `failed`.
+- `server/services/pipeline/issues.test.js` (or wherever sanitizeStage is
+ covered) — `canonExtraction` round-trips through sanitize and defaults to the
+ empty/`null` shape.
+
+## Verification
+1. `cd server && npm test` (universeCanon, pipeline route, issues sanitize).
+2. `cd client && npm test` (NounsStage if covered).
+3. Manual: `npm run dev`, open a pipeline issue with a linked universe, generate
+ prose, force a provider that refuses one kind (Codex) → confirm characters +
+ places land, a **persisted** warning banner shows the failed kind + error,
+ reload the page and the banner is still there, then pick Claude/Gemini in the
+ picker and retry → objects extract, banner clears.
+
+## Notes / out of scope
+- The Codex safety-refusal + Claude `401` are *provider* problems; this work
+ surfaces and recovers from them, it doesn't fix the providers themselves
+ (those already spawn "AI provider investigation" tasks — see logs).
+- The universe-builder `POST /:id/extract-canon` route (used by the standalone
+ Universe Builder page) is left as-is; only the Nouns/pipeline path gets the
+ marker + picker. Adding the picker there is a possible follow-up
+ (capture in `PLAN.md` if deferred).
diff --git a/server/lib/bibleExtractor.js b/server/lib/bibleExtractor.js
index d8dac4e1ef..feae06a7d8 100644
--- a/server/lib/bibleExtractor.js
+++ b/server/lib/bibleExtractor.js
@@ -23,6 +23,7 @@ const EXISTING_VAR = Object.freeze({
* @param {Array} [args.existing] current bible (sent to the prompt for deference)
* @param {object} [args.context] extra prompt variables (work, series, issue, ...)
* @param {string} [args.providerOverride]
+ * @param {string} [args.modelOverride] explicit model id (beats stage.model)
* @param {string} [args.source] run-tracking source tag
*/
export async function extractBible({
@@ -31,6 +32,7 @@ export async function extractBible({
existing = [],
context = {},
providerOverride,
+ modelOverride,
source,
}) {
const stage = KIND_STAGE[kind];
@@ -48,6 +50,7 @@ export async function extractBible({
const result = await runStagedLLM(stage, variables, {
providerOverride,
+ modelOverride,
returnsJson: true,
source: source || `bible-extract-${kind}`,
});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index ed923c90be..037129ce85 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -55,7 +55,7 @@ import {
refineStoryboardScenePrompt,
buildRenderSlot,
} from '../services/pipeline/visualStages.js';
-import { extractCanonFromProse } from '../services/universeCanon.js';
+import { extractCanonFromProse, summarizeCanonExtraction } from '../services/universeCanon.js';
import { getSeriesCanon } from '../services/pipeline/seriesCanon.js';
import { findDuplicateSeriesGroups, findSameNameSeries } from '../services/duplicateDetection.js';
import { mergeSeries } from '../services/recordMerge.js';
@@ -490,8 +490,14 @@ const extractComicPagesSchema = z.object({
const extractCanonFromScriptSchema = z.object({
providerOverride: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(128).optional(),
});
+// Stages whose `output` can be mined for canon. `prose` is the conventional
+// source (auto-extracted post-generation); `comicScript`/`teleplay` let the
+// writer pull characters introduced only in panel directions / dialogue cues.
+const CANON_EXTRACT_STAGES = Object.freeze(['prose', 'comicScript', 'teleplay']);
+
// Per-issue truncation budget for canon extraction. Decoupled from the
// importer's source ceiling (which ingests a *whole book* — millions of
// chars): a pipeline issue's stage output is already hard-bounded at
@@ -1563,9 +1569,9 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r
// derived entries survive later AI refines.
router.post('/issues/:id/stages/:stageId/extract-canon', asyncHandler(async (req, res) => {
const { id, stageId } = req.params;
- if (stageId !== 'comicScript' && stageId !== 'teleplay') {
+ if (!CANON_EXTRACT_STAGES.includes(stageId)) {
throw new ServerError(
- `Stage "${stageId}" does not support canon extraction — supported: comicScript, teleplay`,
+ `Stage "${stageId}" does not support canon extraction — supported: ${CANON_EXTRACT_STAGES.join(', ')}`,
{ status: 400, code: 'PIPELINE_CANON_EXTRACT_BAD_STAGE' },
);
}
@@ -1590,20 +1596,43 @@ router.post('/issues/:id/stages/:stageId/extract-canon', asyncHandler(async (req
{ status: 400, code: 'PIPELINE_CANON_EXTRACT_NO_UNIVERSE' },
);
}
- const result = await extractCanonFromProse(series.universeId, {
- corpus,
- // Fall back to the series' configured LLM when the client doesn't pass
- // an explicit override — matches every other Pipeline LLM action
- // (e.g. storyboards/extract-scenes) so a manual extract honors the
- // provider picked in the series header instead of the global default.
- providerOverride: body.providerOverride || series.llm?.provider || undefined,
- parallel: true,
- autoLock: true,
- sourceSeriesId: series.id,
- }).catch((err) => { throw mapServiceError(err); });
+ // Fall back to the series' configured LLM when the client doesn't pass an
+ // explicit override — matches every other Pipeline LLM action (e.g.
+ // storyboards/extract-scenes) so a manual extract honors the provider/model
+ // picked in the series header instead of the global default.
+ const provider = body.providerOverride || series.llm?.provider || '';
+ const model = body.model || series.llm?.model || '';
+
+ // Stamp the outcome on the stage so the Nouns UI can persist a
+ // failure/partial banner and the user can retry with a different
+ // provider/model. A hard failure (every kind threw) still records `failed`
+ // before re-throwing so the banner survives even when the request 5xxes.
+ let result;
+ try {
+ result = await extractCanonFromProse(series.universeId, {
+ corpus,
+ providerOverride: provider || undefined,
+ modelOverride: model || undefined,
+ parallel: true,
+ autoLock: true,
+ sourceSeriesId: series.id,
+ });
+ } catch (err) {
+ const marker = summarizeCanonExtraction({ error: err, provider, model });
+ await issuesSvc.updateStage(id, stageId, { canonExtraction: marker })
+ .catch((e) => console.warn(`⚠️ Failed to record canon-extraction status for issue ${id.slice(0, 8)}: ${e.message}`));
+ throw mapServiceError(err);
+ }
+
+ const marker = summarizeCanonExtraction({ results: result.results, failures: result.failures, provider, model });
+ const { issue: stampedIssue } = await issuesSvc.updateStage(id, stageId, { canonExtraction: marker })
+ .catch((err) => { throw mapServiceError(err); });
res.json({
universe: result.universe,
+ issue: stampedIssue,
+ canonExtraction: marker,
+ failures: result.failures,
extracted: countExtractedCanon(result.results),
sourceStage: stageId,
truncated,
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index cc475b7af4..a0e3340e5a 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -1112,12 +1112,13 @@ describe('pipeline routes', () => {
// ---- :stageId/extract-canon (manual canon extraction from comicScript / teleplay) ----
- it('POST /issues/:id/stages/:stageId/extract-canon 400s when stage is not comicScript or teleplay', async () => {
+ it('POST /issues/:id/stages/:stageId/extract-canon 400s for a stage that cannot source canon', async () => {
const app = makeApp();
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' });
+ // `idea` is not a canon-extraction source (prose/comicScript/teleplay are).
const r = await request(app)
- .post(`/api/pipeline/issues/${iss.body.id}/stages/prose/extract-canon`)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/idea/extract-canon`)
.send({});
expect(r.status).toBe(400);
expect(r.body.code).toBe('PIPELINE_CANON_EXTRACT_BAD_STAGE');
@@ -1254,6 +1255,64 @@ describe('pipeline routes', () => {
spy.mockRestore();
});
+ it('POST /issues/:id/stages/prose/extract-canon allows prose, forwards model, and stamps a partial canonExtraction marker', async () => {
+ const canonSvc = await import('../services/universeCanon.js');
+ const spy = vi.spyOn(canonSvc, 'extractCanonFromProse').mockResolvedValue({
+ universe: { id: 'u', characters: [{ id: 'c1', name: 'Barkeep' }], places: [], objects: [] },
+ results: {
+ characters: { extracted: [{ name: 'Barkeep' }] },
+ places: { extracted: [] },
+ objects: { extracted: [] },
+ },
+ failures: [{ kind: 'object', error: 'safety refused' }],
+ });
+
+ const app = makeApp();
+ const uni = await universeSvc.createUniverse({ name: 'U' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: uni.id });
+ 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: 'A barkeep slides a glass to Lina.' } },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/prose/extract-canon`)
+ .send({ providerOverride: 'anthropic', model: 'claude-x' });
+ expect(r.status).toBe(200);
+ expect(r.body.sourceStage).toBe('prose');
+ expect(r.body.canonExtraction.status).toBe('partial');
+ expect(r.body.canonExtraction.failedKinds).toEqual(['object']);
+ expect(r.body.failures).toEqual([{ kind: 'object', error: 'safety refused' }]);
+ // Marker is persisted on the returned issue (survives reload).
+ expect(r.body.issue.stages.prose.canonExtraction.status).toBe('partial');
+ // provider/model forwarded to the service.
+ expect(spy.mock.calls[0][1].providerOverride).toBe('anthropic');
+ expect(spy.mock.calls[0][1].modelOverride).toBe('claude-x');
+ spy.mockRestore();
+ });
+
+ it('POST /issues/:id/stages/prose/extract-canon stamps `failed` before re-throwing on a hard failure', async () => {
+ const canonSvc = await import('../services/universeCanon.js');
+ const issuesSvc = await import('../services/pipeline/issues.js');
+ const err = Object.assign(new Error('all kinds failed'), { status: 502, code: 'UNIVERSE_CANON_EXTRACT_ALL_FAILED' });
+ const spy = vi.spyOn(canonSvc, 'extractCanonFromProse').mockRejectedValue(err);
+
+ const app = makeApp();
+ const uni = await universeSvc.createUniverse({ name: 'U' });
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: uni.id });
+ 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: 'some prose' } },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/prose/extract-canon`)
+ .send({});
+ expect(r.status).toBe(502);
+ // The marker was still stamped so the UI banner survives the 5xx.
+ const after = await issuesSvc.getIssue(iss.body.id);
+ expect(after.stages.prose.canonExtraction.status).toBe('failed');
+ spy.mockRestore();
+ });
+
// ---- comicPages/pages/:pageIndex/render ----
it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 400s for a non-integer pageIndex', async () => {
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index e50f5112ed..c60fcc7a03 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -182,6 +182,35 @@ const sanitizeRunHistory = (raw) => {
.slice(0, STAGE_RUN_HISTORY_MAX);
};
+export const CANON_EXTRACTION_STATUSES = Object.freeze(['ok', 'partial', 'failed']);
+const CANON_KINDS = Object.freeze(['character', 'place', 'object']);
+
+// Normalize a canon-extraction outcome marker. Returns `null` for absent /
+// malformed input (the "never attempted" state) so the field stays falsy in
+// the UI until a real extraction runs. `extracted` counts are coerced to
+// non-negative integers; `failedKinds` is filtered to the known kinds.
+const sanitizeCanonExtraction = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!CANON_EXTRACTION_STATUSES.includes(raw.status)) return null;
+ const count = (v) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);
+ const ex = raw.extracted && typeof raw.extracted === 'object' ? raw.extracted : {};
+ return {
+ status: raw.status,
+ error: trimTo(raw.error, STAGE_NOTES_MAX),
+ failedKinds: Array.isArray(raw.failedKinds)
+ ? [...new Set(raw.failedKinds.filter((k) => CANON_KINDS.includes(k)))]
+ : [],
+ extracted: {
+ characters: count(ex.characters),
+ places: count(ex.places),
+ objects: count(ex.objects),
+ },
+ provider: trimTo(raw.provider, 80),
+ model: trimTo(raw.model, 128),
+ at: isStr(raw.at) ? raw.at : null,
+ };
+};
+
const sanitizeStage = (raw) => {
if (!raw || typeof raw !== 'object') return emptyStage();
const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';
@@ -201,6 +230,16 @@ const sanitizeStage = (raw) => {
};
};
+// Text stages (idea/prose/comicScript/teleplay) carry one extra field beyond
+// the shared stage shape: `canonExtraction`, the persisted outcome of the last
+// characters/places/objects extraction run against the stage output (used on
+// `prose`). Layered here rather than in `sanitizeStage` so visual/audio shapes
+// never inherit a concern that doesn't apply to them. `null` = never attempted.
+const sanitizeTextStage = (raw) => ({
+ ...sanitizeStage(raw),
+ canonExtraction: sanitizeCanonExtraction(raw?.canonExtraction),
+});
+
/**
* Decide whether `patch` represents a generate-replacement on `prevStage` and,
* if so, prepend a snapshot of the prior state to `prevStage.runHistory`.
@@ -301,7 +340,8 @@ const sanitizeGenConfig = (raw) => {
const sanitizeVisualStage = (raw, stageId = null) => {
// Visual stages keep arbitrary structured artifact lists. Sanitize the
- // wrapper but pass through known shapes.
+ // wrapper but pass through known shapes. `canonExtraction` is text-stage-only
+ // (it lives on `sanitizeTextStage`), so the visual shape never carries it.
const base = sanitizeStage(raw);
return {
...base,
@@ -366,6 +406,8 @@ const sanitizeMusicTrack = (raw) => {
};
const sanitizeAudioStage = (raw) => {
+ // `canonExtraction` is text-stage-only (see sanitizeTextStage) — the audio
+ // shape never carries it.
const base = sanitizeStage(raw);
return {
...base,
@@ -378,7 +420,7 @@ const sanitizeAudioStage = (raw) => {
const sanitizeStages = (raw = {}) => {
const out = {};
- for (const id of TEXT_STAGE_IDS) out[id] = sanitizeStage(raw[id]);
+ for (const id of TEXT_STAGE_IDS) out[id] = sanitizeTextStage(raw[id]);
for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id], id);
for (const id of AUDIO_STAGE_IDS) out[id] = sanitizeAudioStage(raw[id]);
return out;
@@ -971,7 +1013,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
let next;
if (isVisual) next = sanitizeVisualStage(merged, stageId);
else if (isAudio) next = sanitizeAudioStage(merged);
- else next = sanitizeStage(merged);
+ else next = sanitizeTextStage(merged);
const mergedIssue = sanitizeIssue({
...cur,
stages: { ...cur.stages, [stageId]: next },
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 0eca166d24..405a3c8fc2 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -181,6 +181,39 @@ describe('pipeline issues service', () => {
});
});
+ describe('canonExtraction marker', () => {
+ it('defaults to null on a fresh stage', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'C' });
+ expect(i.stages.prose.canonExtraction).toBeNull();
+ });
+
+ it('round-trips a sanitized marker through updateStage', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'C' });
+ const { stage } = await svc.updateStage(i.id, 'prose', {
+ canonExtraction: {
+ status: 'partial',
+ error: 'object: safety refused',
+ failedKinds: ['object', 'bogus'],
+ extracted: { characters: 3, places: 1, objects: 0 },
+ provider: 'codex', model: 'default',
+ at: '2026-05-30T00:00:00.000Z',
+ },
+ });
+ expect(stage.canonExtraction.status).toBe('partial');
+ expect(stage.canonExtraction.failedKinds).toEqual(['object']); // unknown kind filtered
+ expect(stage.canonExtraction.extracted).toEqual({ characters: 3, places: 1, objects: 0 });
+ expect(stage.canonExtraction.provider).toBe('codex');
+ });
+
+ it('drops a marker with an invalid status (treated as never-attempted)', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'C' });
+ const { stage } = await svc.updateStage(i.id, 'prose', {
+ canonExtraction: { status: 'whoops' },
+ });
+ expect(stage.canonExtraction).toBeNull();
+ });
+ });
+
it('updateStage patches only the named stage', async () => {
const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
const { issue, stage } = await svc.updateStage(i.id, 'idea', {
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index e8fc82cb00..fa80c3225e 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -16,7 +16,7 @@
import { runStagedLLM } from '../../lib/stageRunner.js';
import { getSeries } from './series.js';
-import { extractCanonFromProse } from '../universeCanon.js';
+import { extractCanonFromProse, summarizeCanonExtraction } from '../universeCanon.js';
import { getIssue, listIssues, updateStage, assertStageUnlocked, TEXT_STAGE_IDS } from './issues.js';
import { getSeriesCanon } from './seriesCanon.js';
import { getUniverse } from '../universeBuilder.js';
@@ -300,7 +300,7 @@ export async function generateStage(issueId, stageId, options = {}) {
}
const output = (result.content || '').trim();
- const { issue: updatedIssue, stage } = await updateStage(issueId, stageId, {
+ let { issue: updatedIssue, stage } = await updateStage(issueId, stageId, {
status: output ? 'ready' : 'error',
output,
lastRunId: result.runId,
@@ -322,15 +322,36 @@ export async function generateStage(issueId, stageId, options = {}) {
// sourceSeriesId attributes them to the triggering series. Matches the
// pre-B.4 `extractAndMergeIntoSeries` semantics so existing-data behavior
// is preserved.
- await extractCanonFromProse(series.universeId, {
+ // Persist the extraction outcome on the prose stage (success, partial, or
+ // failed) so the Nouns UI can surface a banner and let the user retry with
+ // a different provider/model. Still non-fatal — a noisy extract shouldn't
+ // roll back the user's accepted prose draft. The stamp is best-effort: if
+ // even the stamp write fails we only warn (no throw out of the prose path).
+ const provider = options.providerId || series.llm?.provider || '';
+ const model = options.model || series.llm?.model || '';
+ const marker = await extractCanonFromProse(series.universeId, {
corpus: output,
providerOverride: options.providerId,
+ modelOverride: options.model,
parallel: true,
autoLock: true,
sourceSeriesId: series.id,
- }).catch((err) => {
- console.warn(`⚠️ Prose extraction failed for issue ${issueId.slice(0, 8)}: ${err.message}`);
+ }).then(
+ ({ results, failures }) => summarizeCanonExtraction({ results, failures, provider, model }),
+ (err) => {
+ console.warn(`⚠️ Prose extraction failed for issue ${issueId.slice(0, 8)}: ${err.message}`);
+ return summarizeCanonExtraction({ error: err, provider, model });
+ },
+ );
+ // Use the stamped issue/stage as the return value so callers (and the
+ // socket update) carry the fresh canonExtraction marker, not the pre-stamp
+ // snapshot. Best-effort: on a stamp-write failure we keep the pre-stamp
+ // values.
+ const stamped = await updateStage(issueId, 'prose', { canonExtraction: marker }).catch((err) => {
+ console.warn(`⚠️ Failed to record canon-extraction status for issue ${issueId.slice(0, 8)}: ${err.message}`);
+ return null;
});
+ if (stamped) ({ issue: updatedIssue, stage } = stamped);
}
return { issue: updatedIssue, stage, runId: result.runId };
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 4979715d83..5e71a10542 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -46,6 +46,13 @@ export const buildStyleClause = (universe) => {
* `opts.source` / `opts.autoLock` / `opts.sourceSeriesId` stamp NEW inserts
* only — existing entries are not touched by these options (locked existing
* entries are protected by mergeExtractedBible itself).
+ *
+ * `opts.providerOverride` / `opts.modelOverride` pick the LLM for every kind so
+ * the caller can retry a failed extraction with a different model.
+ *
+ * Returns `{ universe, results, failures }`. `failures` is `[{ kind, error }]`
+ * for kinds that threw — the successful kinds are still merged. Throws only
+ * when EVERY kind fails.
*/
export async function extractCanonFromProse(universeId, opts = {}) {
const universe = await getUniverse(universeId);
@@ -65,12 +72,45 @@ export async function extractCanonFromProse(universeId, opts = {}) {
existing: universe[BIBLE_FIELD[kind]] || [],
context: { universe: { id: universe.id, name: universe.name } },
providerOverride: opts.providerOverride,
+ modelOverride: opts.modelOverride,
source: `universe-canon-${kind}`,
}).then((result) => ({ kind, result }));
- const completed = opts.parallel
- ? await Promise.all(kinds.map(runOne))
- : await kinds.reduce(async (acc, kind) => [...(await acc), await runOne(kind)], Promise.resolve([]));
+ // Per-kind resilience: one kind failing (e.g. Codex safety-refusing
+ // `object`) must NOT discard the kinds that succeeded. Settle every kind,
+ // merge the successes, and report the rest as `failures` so the caller can
+ // persist what went wrong and let the user retry just the failed kinds with
+ // a different provider/model. Only throw when EVERY kind fails — a total
+ // wipe is a real error the caller should surface.
+ // Settle-shaped wrapper so parallel and serial paths produce the same
+ // `{ status, value | reason }` entries — runOne never rejects through this.
+ const runSettled = (kind) => runOne(kind).then(
+ (value) => ({ status: 'fulfilled', value }),
+ (reason) => ({ status: 'rejected', reason }),
+ );
+ const settled = opts.parallel
+ ? await Promise.all(kinds.map(runSettled))
+ : await kinds.reduce(
+ async (acc, kind) => [...(await acc), await runSettled(kind)],
+ Promise.resolve([]),
+ );
+
+ const completed = [];
+ const failures = [];
+ settled.forEach((outcome, i) => {
+ if (outcome.status === 'fulfilled') {
+ completed.push(outcome.value);
+ } else {
+ const err = outcome.reason;
+ failures.push({ kind: kinds[i], error: (err?.message || String(err)).slice(0, 2000) });
+ }
+ });
+ if (completed.length === 0) {
+ const detail = failures.map((f) => `${f.kind}: ${f.error}`).join(' | ');
+ throw new ServerError(`Canon extraction failed for all kinds — ${detail}`, {
+ status: 502, code: 'UNIVERSE_CANON_EXTRACT_ALL_FAILED',
+ });
+ }
const wantsLock = opts.autoLock !== false;
const mergeOpts = {
@@ -119,7 +159,47 @@ export async function extractCanonFromProse(universeId, opts = {}) {
};
}
const updated = await updateUniverse(universe.id, patch);
- return { universe: updated, results };
+ return { universe: updated, results, failures };
+}
+
+// All three canon kinds, used when a hard (all-kinds) failure leaves us
+// without per-kind detail. Mirrors the BIBLE_KIND values stamped on `failures`.
+const ALL_CANON_KINDS = [BIBLE_KIND.CHARACTER, BIBLE_KIND.PLACE, BIBLE_KIND.OBJECT];
+
+/**
+ * Collapse an `extractCanonFromProse` outcome into the persisted
+ * `stage.canonExtraction` marker (sanitized by issues.sanitizeCanonExtraction).
+ * Pass `error` for a hard failure (the whole call threw); otherwise pass the
+ * `{ results, failures }` from a resolved call. `provider`/`model` record what
+ * was actually used so the UI banner can say "failed with X".
+ */
+export function summarizeCanonExtraction({ results, failures, provider, model, error } = {}) {
+ const at = new Date().toISOString();
+ const base = { provider: provider || '', model: model || '', at };
+ if (error) {
+ return {
+ ...base,
+ status: 'failed',
+ error: (error?.message || String(error)).slice(0, 4000),
+ failedKinds: ALL_CANON_KINDS,
+ extracted: { characters: 0, places: 0, objects: 0 },
+ };
+ }
+ const failedKinds = (failures || []).map((f) => f.kind);
+ const extracted = {
+ characters: results?.characters?.extracted?.length || 0,
+ places: results?.places?.extracted?.length || 0,
+ objects: results?.objects?.extracted?.length || 0,
+ };
+ return {
+ ...base,
+ status: failedKinds.length ? 'partial' : 'ok',
+ error: failedKinds.length
+ ? (failures || []).map((f) => `${f.kind}: ${f.error}`).join(' | ').slice(0, 4000)
+ : '',
+ failedKinds,
+ extracted,
+ };
}
/**
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index c62bd5fd37..217c413ba9 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -293,6 +293,78 @@ describe('universeCanon — extractCanonFromProse passes autoLock + sourceSeries
});
});
+describe('universeCanon — extractCanonFromProse per-kind resilience', () => {
+ it('one kind failing still merges the others and reports failures[]', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ extractBibleMock.mockImplementation(async ({ kind }) => {
+ if (kind === 'object') throw new Error('safety refused');
+ return {
+ extracted: [{ name: `New-${kind}` }],
+ runId: 'r', providerId: 'p', model: 'm',
+ };
+ });
+ const result = await canonSvc.extractCanonFromProse(w.id, {
+ corpus: 'some prose',
+ parallel: true,
+ });
+ // Characters + places landed despite objects throwing.
+ expect(result.universe.characters.some((c) => c.name === 'New-character')).toBe(true);
+ expect(result.universe.places.some((p) => p.name === 'New-place')).toBe(true);
+ expect(result.failures).toEqual([{ kind: 'object', error: 'safety refused' }]);
+ // `results` only carries the kinds that succeeded.
+ expect(result.results.objects).toBeUndefined();
+ });
+
+ it('throws UNIVERSE_CANON_EXTRACT_ALL_FAILED only when EVERY kind fails', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ extractBibleMock.mockImplementation(async () => { throw new Error('boom'); });
+ await expect(canonSvc.extractCanonFromProse(w.id, { corpus: 'p', parallel: true }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_CANON_EXTRACT_ALL_FAILED' });
+ });
+
+ it('forwards modelOverride to extractBible', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ extractBibleMock.mockImplementation(async () => ({ extracted: [], runId: 'r', providerId: 'p', model: 'm' }));
+ await canonSvc.extractCanonFromProse(w.id, {
+ corpus: 'p', kinds: ['character'], providerOverride: 'anthropic', modelOverride: 'claude-x',
+ });
+ expect(extractBibleMock).toHaveBeenCalledWith(expect.objectContaining({
+ providerOverride: 'anthropic', modelOverride: 'claude-x',
+ }));
+ });
+});
+
+describe('universeCanon — summarizeCanonExtraction', () => {
+ it('ok when no failures', () => {
+ const m = canonSvc.summarizeCanonExtraction({
+ results: { characters: { extracted: [1, 2] }, places: { extracted: [3] }, objects: { extracted: [] } },
+ provider: 'codex', model: 'default',
+ });
+ expect(m.status).toBe('ok');
+ expect(m.failedKinds).toEqual([]);
+ expect(m.extracted).toEqual({ characters: 2, places: 1, objects: 0 });
+ expect(m.provider).toBe('codex');
+ });
+
+ it('partial when some kinds failed', () => {
+ const m = canonSvc.summarizeCanonExtraction({
+ results: { characters: { extracted: [1] } },
+ failures: [{ kind: 'object', error: 'safety refused' }],
+ provider: 'codex',
+ });
+ expect(m.status).toBe('partial');
+ expect(m.failedKinds).toEqual(['object']);
+ expect(m.error).toContain('object: safety refused');
+ });
+
+ it('failed (all kinds) when passed an error', () => {
+ const m = canonSvc.summarizeCanonExtraction({ error: new Error('401 bad creds'), provider: 'claude' });
+ expect(m.status).toBe('failed');
+ expect(m.error).toContain('401 bad creds');
+ expect(m.failedKinds).toEqual(['character', 'place', 'object']);
+ });
+});
+
describe('universeCanon — purgeReferenceSheetFromAllUniverses', () => {
it('nulls referenceSheetImageRef on every matching character across every universe', async () => {
const w1 = await seedUniverseWithCharacters([