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

Nouns stage: backfill descriptions from prose and show them from the right field

[._.]/ Adam Eivya6476b4dc13a
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index 0cad8d0c62..5a312ca7f5 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -16,7 +16,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Library, Loader2, Users, MapPin, Package,
- Settings as SettingsIcon, ChevronDown, ChevronRight, AlertTriangle,
+ Settings as SettingsIcon, ChevronDown, ChevronRight, AlertTriangle, FileSearch,
} from 'lucide-react';
import toast from '../../ui/Toast';
import {
@@ -24,7 +24,7 @@ import {
refineUniverseCharacter,
getUniverseSeriesNames,
} from '../../../services/apiUniverseBuilder';
-import { extractPipelineCanonFromScript } from '../../../services/apiPipeline';
+import { extractPipelineCanonFromScript, describePipelineCanonFromProse } from '../../../services/apiPipeline';
import { getProviders } from '../../../services/apiProviders';
import { getSettings, patchSettingsSlice, generateImage } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
@@ -48,14 +48,21 @@ import {
readPipelineImageSettings,
pipelineImageCfgToRenderOpts,
} from '../../../lib/pipelineImageDefaults';
+import { BIBLE_LIMITS } from '../../../lib/bibleLimits';
// Per-kind metadata. `descFor` picks the most visual field for ref-image
-// generation; `match` is the prose scanner that decides whether an entry
-// "appears in this issue".
+// generation; `descField`/`descFieldFallback`/`descFieldMax` bind CanonCard's
+// inline description editor to the RIGHT stored field (characters keep their
+// text in `physicalDescription`, not `description`) so the card neither shows a
+// false "No description yet" nor edits the wrong field; `match` is the prose
+// scanner that decides whether an entry "appears in this issue". Kept in
+// lock-step with UniverseCanonSection's KIND_DEFS so the pipeline + universe
+// canon views render identically.
const KINDS = [
{
key: 'characters', label: 'Characters', singular: 'character', icon: Users,
descFor: (c) => c.physicalDescription || c.description || '',
+ descField: 'physicalDescription', descFieldFallback: 'description', descFieldMax: BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,
match: matchCharactersInText,
},
{
@@ -65,11 +72,13 @@ const KINDS = [
p.palette ? `Palette: ${p.palette}` : '',
p.recurringDetails,
].filter(Boolean).join('. '),
+ descField: 'description', descFieldMax: BIBLE_LIMITS.PLACE_DESCRIPTION_MAX,
match: matchPlacesInText,
},
{
key: 'objects', label: 'Objects', singular: 'object', icon: Package,
descFor: (o) => o.description || o.significance || '',
+ descField: 'description', descFieldFallback: 'significance', descFieldMax: BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX,
match: matchObjectsInText,
},
];
@@ -287,6 +296,56 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
}
};
+ // Strictly-prose-grounded description backfill. Targets = the
+ // appears-in-this-issue entries (across every kind) that lack a description
+ // and aren't locked. The server re-validates and fills only from prose
+ // evidence, returning a `descGaps` marker for nouns the prose can't support.
+ const [describing, setDescribing] = useState(false);
+ const missingTargets = useMemo(() => {
+ const out = [];
+ if (!universe || !proseReady) return out;
+ for (const kind of KINDS) {
+ const list = Array.isArray(universe[kind.key]) ? universe[kind.key] : [];
+ for (const entry of kind.match(prose, list)) {
+ if (entry.locked === true) continue;
+ if (!kind.descFor(entry).trim()) out.push({ id: entry.id, kind: kind.singular });
+ }
+ }
+ return out;
+ }, [universe, prose, proseReady]);
+
+ const descGaps = issue.stages?.prose?.descGaps || null;
+
+ const handleDescribeFromProse = async () => {
+ if (!universe || !proseReady || describing || missingTargets.length === 0) return;
+ setDescribing(true);
+ const result = await describePipelineCanonFromProse(issue.id, 'prose', {
+ providerOverride: extractProvider || undefined,
+ model: extractModel || undefined,
+ targets: missingTargets,
+ }, { silent: true }).catch((err) => {
+ if (mountedRef.current) toast.error(err.message || 'Describe from prose failed');
+ return null;
+ });
+ if (mountedRef.current) setDescribing(false);
+ if (!result || !mountedRef.current) return;
+ if (result.universe) setUniverse(result.universe);
+ // Propagate the stamped prose stage (with the fresh descGaps marker) so the
+ // red-flag banner persists across reloads without a refetch.
+ if (result.issue?.stages?.prose) onStageUpdate?.('prose', result.issue.stages.prose, result.issue);
+ const r = result.report || {};
+ const gaps = (r.none || []).length;
+ if (r.filled) {
+ toast.success(gaps
+ ? `Described ${r.filled} from prose · ${gaps} can't be described — the manuscript is thin on them`
+ : `Described ${r.filled} noun${r.filled === 1 ? '' : 's'} from prose`);
+ } else if (gaps) {
+ toast.error(`The prose doesn't describe ${gaps} noun${gaps === 1 ? '' : 's'} — enrich the manuscript`);
+ } else {
+ toast.success('Nothing to backfill — matched nouns already have descriptions');
+ }
+ };
+
// Queue a reference render. The filename ISN'T persisted onto the entry's
// imageRefs[] yet — NounCard subscribes to job progress and calls
// `handleRefCompleted` once the file actually exists. Without that defer,
@@ -473,6 +532,18 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
{extracting ? <Loader2 size={14} className="animate-spin" /> : <Library size={14} />}
{canonExtraction && canonExtraction.status !== 'ok' ? 'Retry extraction' : 'Extract from prose'}
</button>
+ <button
+ type="button"
+ onClick={handleDescribeFromProse}
+ disabled={describing || !proseReady || missingTargets.length === 0}
+ title={missingTargets.length
+ ? `Write descriptions for ${missingTargets.length} undescribed noun${missingTargets.length === 1 ? '' : 's'} using ONLY what the prose says — nouns the prose can't describe are flagged, not invented`
+ : (proseReady ? 'Every noun that appears in this issue already has a description' : 'Generate prose first')}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-200 text-sm font-medium disabled:opacity-40 hover:border-port-accent/50 hover:text-white"
+ >
+ {describing ? <Loader2 size={14} className="animate-spin" /> : <FileSearch size={14} />}
+ Describe from prose{missingTargets.length ? ` (${missingTargets.length})` : ''}
+ </button>
</div>
</header>
@@ -480,6 +551,8 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
<CanonExtractionBanner extraction={canonExtraction} />
) : null}
+ {descGaps ? <DescGapBanner gaps={descGaps} /> : 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.
@@ -552,6 +625,56 @@ function CanonExtractionBanner({ extraction }) {
);
}
+// Persistent manuscript-quality red flag from the last "Describe from prose"
+// run. `none` = the prose names the noun but never describes it (the headline
+// signal that the manuscript is thin); `thin` = only a passing detail, could
+// use more. Both survive reload via the persisted `stage.descGaps` marker.
+function DescGapBanner({ gaps }) {
+ const none = Array.isArray(gaps.none) ? gaps.none : [];
+ const thin = Array.isArray(gaps.thin) ? gaps.thin : [];
+ if (none.length === 0 && thin.length === 0) return null;
+ const total = none.length + thin.length;
+ return (
+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/5 p-3 space-y-2" role="alert">
+ <div className="flex items-start gap-2 text-port-warning">
+ <AlertTriangle size={16} className="mt-0.5 shrink-0" />
+ <p className="text-sm font-medium">
+ The manuscript is thin on description for {total} noun{total === 1 ? '' : 's'}.
+ Enrich the prose, then re-run “Describe from prose”.
+ </p>
+ </div>
+ {none.length ? (
+ <div className="text-xs text-gray-300">
+ <span className="uppercase tracking-wider text-[10px] text-port-warning">Not described in prose</span>
+ <ul className="mt-1 space-y-1">
+ {none.map((g) => (
+ <li key={g.id}>
+ <span className="text-white">{g.name}</span>{' '}
+ <span className="text-gray-500">({g.kind})</span>
+ {g.note ? <span className="text-gray-400"> — {g.note}</span> : null}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ {thin.length ? (
+ <div className="text-xs text-gray-400">
+ <span className="uppercase tracking-wider text-[10px] text-gray-500">Only thinly described</span>
+ <ul className="mt-1 space-y-1">
+ {thin.map((g) => (
+ <li key={g.id}>
+ <span className="text-gray-200">{g.name}</span>{' '}
+ <span className="text-gray-600">({g.kind})</span>
+ {g.note ? <span className="text-gray-500"> — {g.note}</span> : null}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </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 bbbd0acce6..d643d4098c 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -199,6 +199,18 @@ export const extractPipelineCanonFromScript = (issueId, stageId, { providerOverr
...options,
});
+// Strictly-prose-grounded description backfill. `targets` is `[{ id, kind }]`
+// (kind = 'character' | 'place' | 'object') — the nouns lacking a description.
+// Returns `{ universe, issue, descGaps, report }`; `report.none` lists nouns the
+// prose can't describe (the manuscript-quality red flag), `report.filled` the
+// count written. Unlike extract, this never invents — a blank stays blank.
+export const describePipelineCanonFromProse = (issueId, stageId, { providerOverride, model, targets } = {}, options = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/describe-canon`, {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, model, targets }),
+ ...options,
+ });
+
// Render a full comic page (multi-panel layout in one image) — the default
// for cloud image models (Codex / Google), draft-quality for local models.
// Server persists the returned jobId on stages.comicPages.pages[pageIndex].
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 76e249f651..67932d213d 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -89,7 +89,12 @@
"description": "Analyze a project directory and detect its configuration",
"model": "default",
"returnsJson": true,
- "variables": ["jsonOutputFormat", "appDetectionSchema", "portDetectionRules", "pm2NamingConvention"]
+ "variables": [
+ "jsonOutputFormat",
+ "appDetectionSchema",
+ "portDetectionRules",
+ "pm2NamingConvention"
+ ]
},
"cos-agent-briefing": {
"name": "CoS Agent Briefing",
@@ -451,6 +456,13 @@
"model": "heavy",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-canon-describe-from-prose": {
+ "name": "Pipeline — Describe Nouns From Prose",
+ "description": "Backfill descriptions for canon nouns (characters/places/objects) that have none, using ONLY what the manuscript prose establishes. Grades each noun prose support (sufficient/thin/none) so nouns the prose never describes surface as a manuscript-quality red flag instead of being invented.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-canon-describe-from-prose.md b/data.reference/prompts/stages/pipeline-canon-describe-from-prose.md
new file mode 100644
index 0000000000..330b14bb00
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-canon-describe-from-prose.md
@@ -0,0 +1,51 @@
+# Pipeline — Describe Nouns From Prose (strictly grounded)
+
+You are a story analyst. You are given a manuscript (prose) and a list of "nouns" — characters, places, and objects — that currently have **no description** in the story bible. Your job is to write a description for each, using **only** what the prose itself establishes.
+
+This is a manuscript-quality check as much as a description task. If the prose names a noun but never describes it, you must say so — do **NOT** invent details to fill the gap. A blank that should stay blank is the correct, useful answer here, because it tells the writer their prose is thin on that noun.
+
+## Source prose
+
+```
+{{corpus}}
+```
+
+## Nouns to describe
+
+Each has an `id`, a `kind` (`character`, `place`, or `object`), a `name`, and known `aliases`. Scan every mention of the noun in the prose (by name or any alias) and gather what the text actually says about how it looks or is physically described.
+
+```json
+{{targetsJson}}
+```
+
+## Rules
+
+1. **Use only the prose.** Do not invent, infer beyond the text, or import genre / era / cultural conventions. If the prose does not state a visual or physical detail, do not supply one. Every description you write must be defensible by direct quotation from the prose.
+2. **Write in the right register for each kind** (image-generation-oriented, not literary):
+ - `character` — physical appearance only: apparent age range, build, skin / hair / eye coloring, distinguishing features, signature wardrobe — whatever the prose actually gives. Do **NOT** use the character's own name inside the description.
+ - `place` — the visual scene: architecture, layout, materials, lighting, weather, era cues, and recurring set dressing the prose mentions.
+ - `object` — physical form (size, material, shape, color, markings) and, briefly, its narrative significance when the prose makes it clear.
+3. **Grade each noun's prose support with `sufficiency`:**
+ - `sufficient` — the prose gives concrete, renderable detail. Write a tight description built strictly from it.
+ - `thin` — the prose gives only a little (a passing adjective or two). Write what is grounded, keep it short, and in `note` say what's missing for a confident render.
+ - `none` — the prose names the noun but says nothing about how it looks (only plot function, dialogue, or relationships). Leave `description` empty and in `note` explain that the manuscript never describes it. **This is a flag to the writer — do not paper over it by inventing.**
+4. **Evidence.** For `sufficient` and `thin`, include 1–3 short verbatim quotes (≤ 120 chars each) from the prose that justify the description. For `none`, leave `evidence` empty.
+5. Return exactly one entry per input `id`, echoing the `id` verbatim. Do not add nouns that weren't requested.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "descriptions": [
+ {
+ "id": "string (verbatim from input)",
+ "description": "string (empty when sufficiency is none)",
+ "evidence": ["string", ...],
+ "sufficiency": "sufficient | thin | none",
+ "note": "string (what's missing; empty when sufficient)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/089-canon-describe-from-prose-stage.js b/scripts/migrations/089-canon-describe-from-prose-stage.js
new file mode 100644
index 0000000000..5d25e91464
--- /dev/null
+++ b/scripts/migrations/089-canon-describe-from-prose-stage.js
@@ -0,0 +1,80 @@
+/**
+ * Seed the `pipeline-canon-describe-from-prose` stage into existing installs.
+ *
+ * Mirrors `088-series-generate-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new "Describe from prose"
+ * Nouns-stage action unseeded and `buildPrompt('pipeline-canon-describe-from-prose')`
+ * would throw "Stage not found" the first time a user clicks it.
+ *
+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when
+ * missing and never overwrites an install's existing prompt. A FUTURE migration
+ * that AMENDS this prompt must follow migration 003's hash-driven pattern
+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-canon-describe-from-prose.md';
+const STAGE_KEY = 'pipeline-canon-describe-from-prose';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log('📝 pipeline-canon-describe-from-prose prompt: already present');
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-canon-describe-from-prose: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-canon-describe-from-prose: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ pipeline-canon-describe-from-prose: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log('📝 pipeline-canon-describe-from-prose stage-config: already present');
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-canon-describe-from-prose: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 pipeline-canon-describe-from-prose stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-canon-describe-from-prose: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.js
index fbbfce09ec..52c42fd211 100644
--- a/server/routes/pipeline/issues.js
+++ b/server/routes/pipeline/issues.js
@@ -27,7 +27,10 @@ import {
refineStoryboardScenePrompt,
buildRenderSlot,
} from '../../services/pipeline/visualStages.js';
-import { extractCanonFromProse, summarizeCanonExtraction } from '../../services/universeCanon.js';
+import {
+ extractCanonFromProse, summarizeCanonExtraction,
+ describeCanonFromProse, summarizeDescribeGaps,
+} from '../../services/universeCanon.js';
import { getSeriesCanon } from '../../services/pipeline/seriesCanon.js';
import { startEpisodeVideoForIssue } from '../../services/pipeline/episodeVideo.js';
import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../../services/pipeline/owners.js';
@@ -269,6 +272,17 @@ const extractCanonFromScriptSchema = z.object({
model: z.string().trim().max(128).optional(),
});
+const describeCanonFromProseSchema = z.object({
+ providerOverride: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(128).optional(),
+ // Nouns to backfill — typically the appears-in-this-issue entries that lack
+ // a description. The server re-validates each against the universe canon.
+ targets: z.array(z.object({
+ id: z.string().trim().min(1).max(80),
+ kind: z.enum(['character', 'place', 'object']),
+ })).min(1).max(500),
+});
+
// 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.
@@ -623,6 +637,66 @@ router.post('/issues/:id/stages/:stageId/extract-canon', asyncHandler(async (req
});
}));
+// Backfill descriptions for canon nouns that have none, using ONLY what this
+// stage's prose establishes. Distinct from extract-canon: extraction invents +
+// flags missing renderable axes (so it never leaves a blank), while this pass
+// is strictly prose-grounded — a noun the prose never describes comes back in
+// the `descGaps` marker so the Nouns UI can flag the manuscript as thin instead
+// of fabricating a description that the prose can't support.
+router.post('/issues/:id/stages/:stageId/describe-canon', asyncHandler(async (req, res) => {
+ const { id, stageId } = req.params;
+ if (!CANON_EXTRACT_STAGES.includes(stageId)) {
+ throw new ServerError(
+ `Stage "${stageId}" does not support canon description — supported: ${CANON_EXTRACT_STAGES.join(', ')}`,
+ { status: 400, code: 'PIPELINE_CANON_DESCRIBE_BAD_STAGE' },
+ );
+ }
+ const body = validateRequest(describeCanonFromProseSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(id).catch((err) => { throw mapServiceError(err); });
+ const rawCorpus = (issue.stages?.[stageId]?.output || '').trim();
+ if (!rawCorpus) {
+ throw new ServerError(
+ `Cannot describe canon — issue's ${stageId} stage is empty`,
+ { status: 400, code: 'PIPELINE_CANON_DESCRIBE_NO_CORPUS' },
+ );
+ }
+ const corpus = rawCorpus.length > EXTRACT_CANON_CORPUS_MAX
+ ? rawCorpus.slice(0, EXTRACT_CANON_CORPUS_MAX)
+ : rawCorpus;
+ const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });
+ if (!series.universeId) {
+ throw new ServerError(
+ `Cannot describe canon — series has no linked universe. Link a universe in the series settings first.`,
+ { status: 400, code: 'PIPELINE_CANON_DESCRIBE_NO_UNIVERSE' },
+ );
+ }
+ // Same provider/model resolution as extract-canon so a manual describe honors
+ // the series-header LLM (or the per-attempt picker override).
+ const { provider, model } = resolveSeriesLlmOverride(series, {
+ overrideProvider: body.providerOverride,
+ overrideModel: body.model,
+ });
+
+ const result = await describeCanonFromProse(series.universeId, {
+ corpus,
+ targets: body.targets,
+ providerOverride: provider,
+ modelOverride: model,
+ }).catch((err) => { throw mapServiceError(err); });
+
+ const marker = summarizeDescribeGaps({ report: result.report, provider, model });
+ const { issue: stampedIssue } = await issuesSvc.updateStage(id, stageId, { descGaps: marker })
+ .catch((err) => { throw mapServiceError(err); });
+
+ res.json({
+ universe: result.universe,
+ issue: stampedIssue,
+ descGaps: marker,
+ report: result.report,
+ sourceStage: stageId,
+ });
+}));
+
// Per-page rawText patch — re-parses panels from the edited markdown so a
// subsequent render still gets a structured prompt. Page's `imageJobId` is
// preserved so the user doesn't lose an in-flight render after a save.
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 1d663e518b..49c4c85a30 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -202,6 +202,33 @@ const sanitizeCanonExtraction = (raw) => {
};
};
+// Persisted outcome of the last strictly-prose-grounded "describe nouns from
+// prose" run (see universeCanon.describeCanonFromProse). `null` = never run.
+// `none`/`thin` carry the nouns the manuscript couldn't (or only thinly)
+// describe so the Nouns UI can render a persistent manuscript-quality banner.
+const sanitizeDescGapList = (arr) => (Array.isArray(arr) ? arr : [])
+ .filter((g) => g && typeof g === 'object' && CANON_KINDS.includes(g.kind))
+ .slice(0, 200)
+ .map((g) => ({
+ id: trimTo(g.id, 80),
+ name: trimTo(g.name, 200),
+ kind: g.kind,
+ note: trimTo(g.note, 600),
+ }));
+
+const sanitizeDescGaps = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ return {
+ at: isStr(raw.at) ? raw.at : null,
+ provider: trimTo(raw.provider, 80),
+ model: trimTo(raw.model, 128),
+ filled: Number.isFinite(raw.filled) && raw.filled > 0 ? Math.floor(raw.filled) : 0,
+ none: sanitizeDescGapList(raw.none),
+ thin: sanitizeDescGapList(raw.thin),
+ skippedLocked: sanitizeDescGapList(raw.skippedLocked),
+ };
+};
+
const sanitizeStage = (raw) => {
if (!raw || typeof raw !== 'object') return emptyStage();
const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';
@@ -229,6 +256,7 @@ const sanitizeStage = (raw) => {
const sanitizeTextStage = (raw) => ({
...sanitizeStage(raw),
canonExtraction: sanitizeCanonExtraction(raw?.canonExtraction),
+ descGaps: sanitizeDescGaps(raw?.descGaps),
});
/**
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 5e71a10542..efa4501557 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -7,7 +7,7 @@
import { getUniverse, updateUniverse, listUniverses, joinInfluenceList } from './universeBuilder.js';
import { extractBible } from '../lib/bibleExtractor.js';
import {
- BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, mergeExtractedBible,
+ BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, BIBLE_LIMITS, mergeExtractedBible,
listSheetPointers, applySheetPointerToCharacter,
} from '../lib/storyBible.js';
import { runStagedLLM } from '../lib/stageRunner.js';
@@ -202,6 +202,181 @@ export function summarizeCanonExtraction({ results, failures, provider, model, e
};
}
+// Which field holds a kind's renderable description. Characters carry
+// `physicalDescription` (legacy `description` is the read-fallback);
+// places/objects use `description`. Mirrors NounsStage's `descFor` source.
+const DESC_FIELD = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: 'physicalDescription',
+ [BIBLE_KIND.PLACE]: 'description',
+ [BIBLE_KIND.OBJECT]: 'description',
+});
+const DESC_LIMIT = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,
+ [BIBLE_KIND.PLACE]: BIBLE_LIMITS.PLACE_DESCRIPTION_MAX,
+ [BIBLE_KIND.OBJECT]: BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX,
+});
+
+// True when an entry already carries a non-empty description (so the backfill
+// pass has nothing to do for it). Characters check both the canonical and the
+// legacy field so a pre-migration `description`-only entry isn't double-filled.
+const hasDescription = (kind, entry) => {
+ if (kind === BIBLE_KIND.CHARACTER) {
+ return !!(((entry.physicalDescription || '').trim()) || ((entry.description || '').trim()));
+ }
+ return !!((entry.description || '').trim());
+};
+
+/**
+ * Backfill descriptions for canon nouns that have none, using ONLY what the
+ * prose establishes. Unlike `extractCanonFromProse` (which is allowed to invent
+ * + flag renderable axes the prose omits, so it never leaves a blank), this
+ * pass is strictly prose-grounded: a noun the prose names but never describes
+ * comes back `none` with an empty description, so the gap surfaces as a
+ * manuscript-quality red flag rather than being papered over.
+ *
+ * `targets` is `[{ id, kind }]` — typically the appears-in-this-issue entries
+ * that lack a description. Unknown ids, already-described entries, and locked
+ * entries are dropped (locked ones are reported as `skippedLocked`).
+ *
+ * Returns `{ universe, report }` where `report` is
+ * `{ filled, sufficient[], thin[], none[], skippedLocked[], unmatched }`.
+ * Only `sufficient`/`thin` rows with a non-empty grounded description are
+ * written, and only into entries that are STILL empty + unlocked at write time.
+ */
+export async function describeCanonFromProse(universeId, opts = {}) {
+ const { corpus, targets, providerOverride, modelOverride } = opts;
+ if (typeof corpus !== 'string' || !corpus.trim()) {
+ throw new ServerError('describeCanonFromProse: corpus is required', {
+ status: 400, code: 'UNIVERSE_CANON_NO_CORPUS',
+ });
+ }
+ if (!Array.isArray(targets) || targets.length === 0) {
+ throw new ServerError('describeCanonFromProse: at least one target noun is required', {
+ status: 400, code: 'UNIVERSE_CANON_NO_TARGETS',
+ });
+ }
+ const universe = await getUniverse(universeId);
+
+ // Resolve each requested {id, kind} against the current canon. Drop unknown
+ // ids and already-described entries; hold locked ones aside to report.
+ const resolved = [];
+ const skippedLocked = [];
+ let unmatched = 0;
+ for (const t of (targets || [])) {
+ const kind = t?.kind;
+ if (!BIBLE_KINDS.includes(kind)) { unmatched += 1; continue; }
+ const list = Array.isArray(universe[BIBLE_FIELD[kind]]) ? universe[BIBLE_FIELD[kind]] : [];
+ const entry = list.find((e) => e.id === t.id);
+ if (!entry || hasDescription(kind, entry)) { unmatched += 1; continue; }
+ if (entry.locked === true) { skippedLocked.push({ id: entry.id, name: entry.name, kind }); continue; }
+ resolved.push({ kind, entry });
+ }
+
+ const report = { filled: 0, sufficient: [], thin: [], none: [], skippedLocked, unmatched };
+ if (resolved.length === 0) return { universe, report };
+
+ const targetsForPrompt = resolved.map(({ kind, entry }) => ({
+ id: entry.id,
+ kind,
+ name: entry.name,
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ }));
+
+ const result = await runStagedLLM('pipeline-canon-describe-from-prose', {
+ corpus,
+ targetsJson: JSON.stringify(targetsForPrompt, null, 2),
+ }, {
+ providerOverride,
+ modelOverride,
+ returnsJson: true,
+ source: 'universe-canon-describe-from-prose',
+ });
+
+ const rows = Array.isArray(result.content?.descriptions) ? result.content.descriptions : [];
+ const byId = new Map();
+ for (const r of rows) {
+ if (r && typeof r === 'object' && typeof r.id === 'string') byId.set(r.id, r);
+ }
+
+ const SUFFICIENCY = new Set(['sufficient', 'thin', 'none']);
+ const fills = new Map(); // entryId -> { value }
+ for (const { kind, entry } of resolved) {
+ const row = byId.get(entry.id);
+ const name = entry.name;
+ if (!row) {
+ // LLM omitted this id entirely — treat as un-describable so it still
+ // surfaces to the writer rather than vanishing silently.
+ report.none.push({ id: entry.id, name, kind, note: 'The model returned no result for this noun.' });
+ continue;
+ }
+ const sufficiency = SUFFICIENCY.has(row.sufficiency) ? row.sufficiency : 'none';
+ const desc = typeof row.description === 'string' ? row.description.trim() : '';
+ const note = typeof row.note === 'string' ? row.note.trim().slice(0, 600) : '';
+ if ((sufficiency === 'sufficient' || sufficiency === 'thin') && desc) {
+ fills.set(entry.id, { value: desc.slice(0, DESC_LIMIT[kind]) });
+ report.filled += 1;
+ (sufficiency === 'sufficient' ? report.sufficient : report.thin).push({ id: entry.id, name, kind, note });
+ } else {
+ report.none.push({
+ id: entry.id, name, kind,
+ note: note || 'The manuscript names this but never describes how it looks.',
+ });
+ }
+ }
+
+ if (fills.size > 0) {
+ // Mutator form: re-read freshest persisted state and write only into entries
+ // that are STILL empty + unlocked (guards against an inline edit landing
+ // between our read and this write). Mirrors setCanonEntryLock. The DESC_FIELD
+ // lookup is per-kind, so the right field is written for each entry.
+ const updated = await updateUniverse(universe.id, (cur) => {
+ const patch = {};
+ for (const kind of BIBLE_KINDS) {
+ const field = BIBLE_FIELD[kind];
+ const list = Array.isArray(cur[field]) ? cur[field] : [];
+ let touched = false;
+ const nextList = list.map((e) => {
+ const fill = fills.get(e.id);
+ if (!fill || e.locked === true || hasDescription(kind, e)) return e;
+ touched = true;
+ return { ...e, [DESC_FIELD[kind]]: fill.value };
+ });
+ if (touched) patch[field] = nextList;
+ }
+ return Object.keys(patch).length ? patch : null;
+ });
+ console.log(`📝 Universe canon describe-from-prose — universe=${shortId(universeId)} filled=${report.filled} none=${report.none.length} thin=${report.thin.length} runId=${shortId(result.runId)}`);
+ return { universe: updated || universe, report };
+ }
+ console.log(`📝 Universe canon describe-from-prose — universe=${shortId(universeId)} filled=0 none=${report.none.length} thin=${report.thin.length} runId=${shortId(result.runId)}`);
+ return { universe, report };
+}
+
+/**
+ * Collapse a `describeCanonFromProse` report into the persisted
+ * `stage.descGaps` marker (sanitized by issues.sanitizeDescGaps). Records the
+ * counts + the nouns the prose couldn't describe (`none`) or only thinly
+ * described (`thin`) so the Nouns UI can render a persistent red-flag banner
+ * pointing the writer at manuscript gaps. `provider`/`model` record what ran.
+ */
+export function summarizeDescribeGaps({ report, provider, model } = {}) {
+ const mapGap = (arr) => (Array.isArray(arr) ? arr : []).map((g) => ({
+ id: String(g.id || ''),
+ name: String(g.name || '').slice(0, 200),
+ kind: g.kind,
+ note: String(g.note || '').slice(0, 600),
+ }));
+ return {
+ at: new Date().toISOString(),
+ provider: provider || '',
+ model: model || '',
+ filled: report?.filled || 0,
+ none: mapGap(report?.none),
+ thin: mapGap(report?.thin),
+ skippedLocked: mapGap(report?.skippedLocked),
+ };
+}
+
/**
* Rewrite one character's `physicalDescription` so they render distinct
* from every peer. Same prompt as the series-side refine; just sourced from
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 217c413ba9..1091a583a1 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -334,6 +334,97 @@ describe('universeCanon — extractCanonFromProse per-kind resilience', () => {
});
});
+describe('universeCanon — describeCanonFromProse (strictly prose-grounded)', () => {
+ it('fills physicalDescription for a sufficient char and reports a none char without inventing', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Mara', physicalDescription: '', locked: false },
+ { name: 'Ghost', physicalDescription: '', locked: false },
+ ]);
+ const [mara, ghost] = w.characters;
+ runStagedLLMMock.mockResolvedValue({
+ content: {
+ descriptions: [
+ { id: mara.id, sufficiency: 'sufficient', description: 'tall woman, copper braid, freckles', evidence: ['her copper braid'] },
+ { id: ghost.id, sufficiency: 'none', description: '', note: 'only named in dialogue' },
+ ],
+ },
+ runId: 'run-d', providerId: 'test', model: 'test',
+ });
+ const result = await canonSvc.describeCanonFromProse(w.id, {
+ corpus: 'Mara has a copper braid. Ghost is mentioned.',
+ targets: [{ id: mara.id, kind: 'character' }, { id: ghost.id, kind: 'character' }],
+ });
+ expect(result.report.filled).toBe(1);
+ expect(result.report.none.map((g) => g.id)).toEqual([ghost.id]);
+ const refreshed = (await svc.listUniverses())[0];
+ expect(refreshed.characters.find((c) => c.id === mara.id).physicalDescription).toContain('copper braid');
+ // The un-describable noun stays blank — the whole point of the red flag.
+ expect(refreshed.characters.find((c) => c.id === ghost.id).physicalDescription).toBe('');
+ });
+
+ it('skips locked + already-described targets and never calls the LLM when nothing is left', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Locked', physicalDescription: '', locked: true },
+ { name: 'Done', physicalDescription: 'already has a look', locked: false },
+ ]);
+ const [locked, done] = w.characters;
+ const result = await canonSvc.describeCanonFromProse(w.id, {
+ corpus: 'some prose',
+ targets: [{ id: locked.id, kind: 'character' }, { id: done.id, kind: 'character' }],
+ });
+ expect(runStagedLLMMock).not.toHaveBeenCalled();
+ expect(result.report.filled).toBe(0);
+ expect(result.report.skippedLocked.map((g) => g.id)).toEqual([locked.id]);
+ expect(result.report.unmatched).toBe(1); // `Done` already described
+ });
+
+ it('grades thin into report.thin while still filling the grounded fragment', async () => {
+ const w = await svc.updateUniverse(
+ (await svc.createUniverse({ name: 'U', starterPrompt: 'x', stylePrompt: 'y' })).id,
+ { places: [{ name: 'The Vault', description: '', locked: false }] },
+ );
+ const vault = w.places[0];
+ runStagedLLMMock.mockResolvedValue({
+ content: { descriptions: [{ id: vault.id, sufficiency: 'thin', description: 'a dim concrete room', note: 'no lighting or scale given' }] },
+ runId: 'run-t', providerId: 'test', model: 'test',
+ });
+ const result = await canonSvc.describeCanonFromProse(w.id, {
+ corpus: 'The Vault was dim.',
+ targets: [{ id: vault.id, kind: 'place' }],
+ });
+ expect(result.report.filled).toBe(1);
+ expect(result.report.thin.map((g) => g.id)).toEqual([vault.id]);
+ expect(result.universe.places.find((p) => p.id === vault.id).description).toBe('a dim concrete room');
+ });
+
+ it('rejects an empty corpus and empty targets', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ await expect(canonSvc.describeCanonFromProse(w.id, { corpus: '', targets: [{ id: 'x', kind: 'character' }] }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_CANON_NO_CORPUS' });
+ await expect(canonSvc.describeCanonFromProse(w.id, { corpus: 'p', targets: [] }))
+ .rejects.toMatchObject({ code: 'UNIVERSE_CANON_NO_TARGETS' });
+ });
+});
+
+describe('universeCanon — summarizeDescribeGaps', () => {
+ it('maps the report into a persistable marker', () => {
+ const m = canonSvc.summarizeDescribeGaps({
+ report: {
+ filled: 2,
+ none: [{ id: 'a', name: 'A', kind: 'character', note: 'no look' }],
+ thin: [{ id: 'b', name: 'B', kind: 'place', note: 'sparse' }],
+ skippedLocked: [{ id: 'c', name: 'C', kind: 'object' }],
+ },
+ provider: 'codex', model: 'default',
+ });
+ expect(m.filled).toBe(2);
+ expect(m.none).toEqual([{ id: 'a', name: 'A', kind: 'character', note: 'no look' }]);
+ expect(m.thin[0].id).toBe('b');
+ expect(m.provider).toBe('codex');
+ expect(typeof m.at).toBe('string');
+ });
+});
+
describe('universeCanon — summarizeCanonExtraction', () => {
it('ok when no failures', () => {
const m = canonSvc.summarizeCanonExtraction({