Skip to content

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

feat: review whether a cast holds together, not just whether its fields are filled (#6415)

[._.]/ Adam Eivy567b23cf7d8c
diff --git a/client/src/components/universe/CastIntegrityPanel.jsx b/client/src/components/universe/CastIntegrityPanel.jsx
new file mode 100644
index 0000000000..56eff6d479
--- /dev/null
+++ b/client/src/components/universe/CastIntegrityPanel.jsx
@@ -0,0 +1,384 @@
+/**
+ * Cast integrity review + selective augmentation (#6415).
+ *
+ * Three states in one modal, in the order the work actually happens:
+ *
+ * 1. **Completeness** — opened straight into the DETERMINISTIC report, which
+ * costs nothing. Every character is listed with an explicit status, so
+ * "passed" and "never looked at" can never read the same.
+ * 2. **Review** — the semantic pass. The button names the provider, the model
+ * and how many characters the batch covers BEFORE it runs, because a click
+ * here spends provider budget (AGENTS.md: no unannounced provider calls).
+ * 3. **Augment** — for the findings a model can actually repair. Proposals
+ * arrive as before/after pairs and are applied ONE CHECKBOX AT A TIME; a
+ * `contradictory` finding never offers the button, because only the author
+ * can decide which of two disagreeing fields is the wrong one.
+ *
+ * Nothing here is persisted. The report is derived on open and carries the
+ * fingerprint of the cast it measured; applying a proposal against a character
+ * that changed since returns 409 rather than overwriting the newer edit.
+ */
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Loader2, ShieldCheck, Sparkles, X, Check } from 'lucide-react';
+import Modal from '../ui/Modal';
+import toast from '../ui/Toast';
+import useMounted from '../../hooks/useMounted';
+import {
+ getUniverseCastIntegrity,
+ reviewUniverseCastIntegrity,
+ proposeCharacterAugmentation,
+ applyCharacterAugmentation,
+} from '../../services/apiUniverseBuilder';
+import {
+ DEPTH_META,
+ DIMENSION_LABELS,
+ FINDING_KIND_META,
+ REVIEW_STATUS_META,
+ castIntegrityPassed,
+ findingIsRepairable,
+ incompleteCoverage,
+} from '../../lib/characterIntegrity';
+
+const TONE_CLASS = {
+ emerald: 'bg-emerald-500/15 text-emerald-300 border-emerald-500/40',
+ amber: 'bg-amber-500/15 text-amber-300 border-amber-500/40',
+ rose: 'bg-rose-500/15 text-rose-300 border-rose-500/40',
+ slate: 'bg-port-bg text-gray-400 border-port-border',
+};
+
+const Badge = ({ tone, children, title }) => (
+ <span
+ title={title}
+ className={`inline-flex items-center px-1.5 py-0.5 rounded border text-[10px] uppercase tracking-wider ${TONE_CLASS[tone] || TONE_CLASS.slate}`}
+ >
+ {children}
+ </span>
+);
+
+/** `psychology.drives.status.fear` → `Psychology › drives › status › fear`. */
+const humanizeField = (field) => field
+ .split('.')
+ .map((part) => part.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()).trim())
+ .join(' › ');
+
+export default function CastIntegrityPanel({ open, universeId, onClose, onUniverseChange }) {
+ const mountedRef = useMounted();
+ const [report, setReport] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [reviewing, setReviewing] = useState(false);
+ // Findings the user ticked, by finding id — the augment batch.
+ const [selected, setSelected] = useState(() => new Set());
+ // `{ characterId, entryName, fingerprint, proposals: [] }` awaiting review.
+ const [preview, setPreview] = useState(null);
+ const [proposing, setProposing] = useState(false);
+ const [accepted, setAccepted] = useState(() => new Set());
+ const [applying, setApplying] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const result = await getUniverseCastIntegrity(universeId, {}, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Could not load the integrity report'); return null; });
+ if (!mountedRef.current) return;
+ setLoading(false);
+ if (result) {
+ setReport(result);
+ setSelected(new Set());
+ setPreview(null);
+ }
+ }, [universeId, mountedRef]);
+
+ useEffect(() => {
+ if (!open || !universeId) return;
+ load();
+ }, [open, universeId, load]);
+
+ const scope = report?.reviewScope;
+ const findings = useMemo(() => report?.findings || [], [report]);
+ const repairable = useMemo(() => findings.filter(findingIsRepairable), [findings]);
+ const incomplete = useMemo(() => incompleteCoverage(report), [report]);
+ const passed = castIntegrityPassed(report);
+
+ // Augmentation is per character (one call, one fingerprint), so a mixed
+ // selection would need N calls and N staleness checks. Keep it to one.
+ const selectedCharacterIds = useMemo(() => {
+ const ids = new Set();
+ for (const f of repairable) if (selected.has(f.id)) ids.add(f.characterId);
+ return [...ids];
+ }, [repairable, selected]);
+
+ const toggleFinding = (id) => setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id); else next.add(id);
+ return next;
+ });
+
+ const handleReview = async () => {
+ if (reviewing) return;
+ setReviewing(true);
+ const result = await reviewUniverseCastIntegrity(universeId, {}, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Cast review failed'); return null; });
+ if (mountedRef.current) setReviewing(false);
+ if (!result || !mountedRef.current) return;
+ setReport(result);
+ setSelected(new Set());
+ const n = result.findings?.length || 0;
+ toast.success(result.truncated
+ ? `Reviewed ${result.reviewScope?.characterCount || 0} of the cast — ${n} finding${n === 1 ? '' : 's'}. ${result.reviewScope?.remainingCount || 0} still unreviewed.`
+ : `Reviewed the cast — ${n} finding${n === 1 ? '' : 's'}`);
+ };
+
+ const handlePropose = async () => {
+ if (proposing || selectedCharacterIds.length !== 1) return;
+ const characterId = selectedCharacterIds[0];
+ const fields = repairable.filter((f) => selected.has(f.id) && f.characterId === characterId).map((f) => f.field);
+ setProposing(true);
+ const result = await proposeCharacterAugmentation(universeId, characterId, { fields }, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Augment failed'); return null; });
+ if (mountedRef.current) setProposing(false);
+ if (!result || !mountedRef.current) return;
+ if (result.locked) {
+ toast.error(`${result.entry?.name || 'Character'} is locked — unlock before augmenting`);
+ return;
+ }
+ if (!result.proposals?.length) {
+ toast.success('Nothing to sharpen — the model had no improvement to offer');
+ return;
+ }
+ setPreview({
+ characterId,
+ entryName: result.entry?.name || 'Character',
+ fingerprint: result.fingerprint,
+ proposals: result.proposals,
+ });
+ // Opt-IN: nothing is accepted until the author ticks it.
+ setAccepted(new Set());
+ };
+
+ const handleApply = async () => {
+ if (applying || !preview) return;
+ const fields = preview.proposals
+ .filter((p) => accepted.has(p.field))
+ .map((p) => ({ field: p.field, value: p.after }));
+ if (fields.length === 0) return;
+ setApplying(true);
+ const result = await applyCharacterAugmentation(
+ universeId,
+ preview.characterId,
+ { fields, fingerprint: preview.fingerprint },
+ { silent: true },
+ ).catch((err) => {
+ toast.error(err.message || 'Apply failed');
+ return null;
+ });
+ if (mountedRef.current) setApplying(false);
+ if (!result || !mountedRef.current) return;
+ if (result.locked) {
+ toast.error(`${preview.entryName} is locked — unlock before applying`);
+ return;
+ }
+ if (result.universe) onUniverseChange?.(result.universe);
+ toast.success(`Applied ${result.appliedFields?.length || 0} field${result.appliedFields?.length === 1 ? '' : 's'} to ${preview.entryName}`);
+ setPreview(null);
+ setSelected(new Set());
+ // This character just changed, so every finding the open report holds about
+ // it was measured against a version that no longer exists. Mark the row
+ // STALE rather than re-deriving the whole report: a re-derive would run the
+ // deterministic pass again and silently discard the semantic review the
+ // user just paid for.
+ setReport((prev) => (prev ? {
+ ...prev,
+ coverage: prev.coverage.map((c) => (
+ c.characterId === preview.characterId ? { ...c, status: 'stale', semanticReviewed: false } : c
+ )),
+ } : prev));
+ };
+
+ const reviewLabel = scope?.providerId
+ ? `Review ${scope.characterCount} character${scope.characterCount === 1 ? '' : 's'} with ${scope.providerName || scope.providerId}${scope.model ? ` · ${scope.model}` : ''}`
+ : 'Review cast';
+
+ return (
+ <Modal open={open} onClose={onClose} size="3xl" ariaLabelledBy="cast-integrity-title">
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col min-h-0">
+ <div className="flex items-start justify-between gap-3 p-4 border-b border-port-border">
+ <div>
+ <h2 id="cast-integrity-title" className="text-white text-sm font-semibold flex items-center gap-2">
+ <ShieldCheck size={14} /> Cast integrity
+ </h2>
+ <p className="text-xs text-gray-500 mt-1 max-w-xl">
+ Whether each character holds together — not just whether the fields are filled. The completeness pass below is free; the semantic review costs one provider call.
+ </p>
+ </div>
+ <button type="button" onClick={onClose} aria-label="Close cast integrity" className="text-gray-500 hover:text-white">
+ <X size={16} />
+ </button>
+ </div>
+
+ <div className="p-4 overflow-y-auto space-y-4">
+ {loading ? (
+ <p className="text-xs text-gray-400 flex items-center gap-2"><Loader2 size={12} className="animate-spin" /> Reading the cast…</p>
+ ) : null}
+
+ {!loading && report ? (
+ <>
+ <div className="flex flex-wrap items-center gap-2 justify-between">
+ <p className="text-xs text-gray-400">
+ {passed
+ ? `All ${report.castCount} characters reviewed and clean.`
+ : `${findings.length} finding${findings.length === 1 ? '' : 's'} across ${report.castCount} character${report.castCount === 1 ? '' : 's'}.`}
+ {incomplete.length ? (
+ <span className="text-gray-500"> {incomplete.length} not fully reviewed.</span>
+ ) : null}
+ </p>
+ <button
+ type="button"
+ onClick={handleReview}
+ disabled={reviewing || !report.castCount}
+ title={scope?.remainingCount ? `${scope.remainingCount} character(s) beyond this batch stay unreviewed` : undefined}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/15 hover:bg-port-accent/25 text-port-accent border border-port-accent/40 text-xs disabled:opacity-40"
+ >
+ {reviewing ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ {reviewLabel}
+ </button>
+ </div>
+
+ <div className="overflow-x-auto">
+ <table className="w-full text-xs">
+ <thead>
+ <tr className="text-gray-500 text-left uppercase tracking-wider text-[10px]">
+ <th scope="col" className="py-1 pr-3 font-normal">Character</th>
+ <th scope="col" className="py-1 pr-3 font-normal">Status</th>
+ <th scope="col" className="py-1 pr-3 font-normal">Depth</th>
+ <th scope="col" className="py-1 font-normal">Findings</th>
+ </tr>
+ </thead>
+ <tbody>
+ {(report.coverage || []).map((row) => (
+ <tr key={row.characterId} className="border-t border-port-border/50">
+ <td className="py-1.5 pr-3 text-gray-200">{row.characterName || row.characterId}</td>
+ <td className="py-1.5 pr-3">
+ <Badge tone={REVIEW_STATUS_META[row.status]?.tone}>{REVIEW_STATUS_META[row.status]?.label || row.status}</Badge>
+ </td>
+ <td className="py-1.5 pr-3">
+ <Badge tone="slate" title={DEPTH_META[row.depth]?.hint}>{DEPTH_META[row.depth]?.label || row.depth}</Badge>
+ </td>
+ <td className="py-1.5 text-gray-400">{row.findingCount}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ {findings.length ? (
+ <div className="space-y-2">
+ <h3 className="text-xs uppercase tracking-wider text-gray-500">Findings</h3>
+ {findings.map((f) => {
+ const meta = FINDING_KIND_META[f.kind] || {};
+ const checkboxId = `integrity-finding-${f.id.replace(/[^a-zA-Z0-9]/g, '-')}`;
+ return (
+ <div key={f.id} className="rounded border border-port-border bg-port-bg p-2.5">
+ <div className="flex items-start gap-2">
+ {meta.repairable ? (
+ <input
+ type="checkbox"
+ id={checkboxId}
+ checked={selected.has(f.id)}
+ onChange={() => toggleFinding(f.id)}
+ className="mt-0.5 accent-port-accent"
+ />
+ ) : <span className="w-3" aria-hidden="true" />}
+ <div className="min-w-0 flex-1">
+ <label htmlFor={meta.repairable ? checkboxId : undefined} className="flex flex-wrap items-center gap-1.5">
+ <span className="text-gray-200">{f.characterName || f.characterId}</span>
+ <span className="text-gray-500">·</span>
+ <span className="text-gray-400 font-mono text-[11px]">{humanizeField(f.field)}</span>
+ <Badge tone={meta.tone} title={meta.hint}>{meta.label || f.kind}</Badge>
+ {f.dimension ? <Badge tone="slate">{DIMENSION_LABELS[f.dimension] || f.dimension}</Badge> : null}
+ </label>
+ <p className="text-gray-400 mt-1">{f.evidence}</p>
+ {f.suggestion ? <p className="text-gray-500 mt-1 italic">{f.suggestion}</p> : null}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : null}
+
+ {selected.size ? (
+ <div className="flex flex-wrap items-center justify-between gap-2 rounded border border-port-border bg-port-bg p-2.5">
+ <p className="text-xs text-gray-400">
+ {selected.size} field{selected.size === 1 ? '' : 's'} selected
+ {selectedCharacterIds.length > 1
+ ? ' — augment runs one character at a time, so narrow the selection to a single character.'
+ : '.'}
+ </p>
+ <button
+ type="button"
+ onClick={handlePropose}
+ disabled={proposing || selectedCharacterIds.length !== 1}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/15 hover:bg-port-accent/25 text-port-accent border border-port-accent/40 text-xs disabled:opacity-40"
+ >
+ {proposing ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Propose improvements
+ </button>
+ </div>
+ ) : null}
+
+ {preview ? (
+ <div className="rounded border border-port-accent/40 bg-port-bg p-3 space-y-3">
+ <h3 className="text-xs uppercase tracking-wider text-gray-400">
+ Proposed for {preview.entryName} — tick what to keep
+ </h3>
+ {preview.proposals.map((p) => {
+ const id = `augment-${p.field.replace(/[^a-zA-Z0-9]/g, '-')}`;
+ return (
+ <div key={p.field} className="space-y-1">
+ <label htmlFor={id} className="flex items-center gap-2 text-xs text-gray-200">
+ <input
+ type="checkbox"
+ id={id}
+ checked={accepted.has(p.field)}
+ onChange={() => setAccepted((prev) => {
+ const next = new Set(prev);
+ if (next.has(p.field)) next.delete(p.field); else next.add(p.field);
+ return next;
+ })}
+ className="accent-port-accent"
+ />
+ <span className="font-mono text-[11px]">{humanizeField(p.field)}</span>
+ </label>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <p className="text-[11px] text-gray-500 border border-port-border rounded p-2 whitespace-pre-wrap">
+ {p.before || <span className="italic">(empty)</span>}
+ </p>
+ <p className="text-[11px] text-gray-200 border border-port-accent/40 rounded p-2 whitespace-pre-wrap">{p.after}</p>
+ </div>
+ {p.rationale ? <p className="text-[11px] text-gray-500 italic">{p.rationale}</p> : null}
+ </div>
+ );
+ })}
+ <div className="flex items-center justify-end gap-2">
+ <button type="button" onClick={() => setPreview(null)} className="px-2 py-1 text-xs text-gray-400 hover:text-white">
+ Discard
+ </button>
+ <button
+ type="button"
+ onClick={handleApply}
+ disabled={applying || accepted.size === 0}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-40"
+ >
+ {applying ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
+ Apply {accepted.size || ''}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </>
+ ) : null}
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/universe/CastIntegrityPanel.test.jsx b/client/src/components/universe/CastIntegrityPanel.test.jsx
new file mode 100644
index 0000000000..90547dae7f
--- /dev/null
+++ b/client/src/components/universe/CastIntegrityPanel.test.jsx
@@ -0,0 +1,206 @@
+/**
+ * Rendered interaction for the cast-integrity panel (#6415).
+ *
+ * The behaviors worth pinning here are the ones the server cannot enforce: that
+ * the panel costs nothing until the user asks, that it names what a review will
+ * spend BEFORE spending it, that a `contradictory` finding offers no repair
+ * button, and that applying a proposal is opt-in per field.
+ */
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import CastIntegrityPanel from './CastIntegrityPanel';
+
+const apiMocks = vi.hoisted(() => ({
+ getUniverseCastIntegrity: vi.fn(),
+ reviewUniverseCastIntegrity: vi.fn(),
+ proposeCharacterAugmentation: vi.fn(),
+ applyCharacterAugmentation: vi.fn(),
+}));
+vi.mock('../../services/apiUniverseBuilder', () => apiMocks);
+const toastMock = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('../ui/Toast', () => ({ default: toastMock }));
+
+const coverage = [
+ { characterId: 'c-1', characterName: 'Wren', depth: 'full', status: 'findings', findingCount: 1, semanticReviewed: false },
+ { characterId: 'c-2', characterName: 'Dockhand', depth: 'light', status: 'not-reviewed', findingCount: 0, semanticReviewed: false },
+];
+
+const underspecified = {
+ id: 'c-1::underspecified::lie',
+ characterId: 'c-1',
+ characterName: 'Wren',
+ kind: 'underspecified',
+ field: 'lie',
+ dimension: 'control-predicts-behavior',
+ evidence: 'The belief is stated so broadly it predicts no particular behavior.',
+ suggestion: 'Name the moment she refuses to hand over the chart.',
+};
+
+const contradictory = {
+ ...underspecified,
+ id: 'c-1::contradictory::want',
+ kind: 'contradictory',
+ field: 'want',
+ evidence: 'The want and the need describe the same outcome.',
+};
+
+const report = (over = {}) => ({
+ findings: [underspecified],
+ coverage,
+ fingerprints: { 'c-1': 'fp-1' },
+ reviewedCount: 1,
+ castCount: 2,
+ semanticReviewedCount: 0,
+ reviewScope: {
+ characterIds: ['c-1', 'c-2'],
+ characterCount: 2,
+ remainingCount: 0,
+ batchMax: 12,
+ providerId: 'prov-1',
+ providerName: 'Local Llama',
+ model: 'llama-3.3',
+ },
+ ...over,
+});
+
+const props = { open: true, universeId: 'u-1', onClose: () => {}, onUniverseChange: vi.fn() };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ apiMocks.getUniverseCastIntegrity.mockResolvedValue(report());
+});
+
+describe('CastIntegrityPanel', () => {
+ it('opens on the free deterministic report and starts no review of its own', async () => {
+ render(<CastIntegrityPanel {...props} />);
+ // 'Wren' renders in both the coverage table and the findings list.
+ expect(await screen.findAllByText('Wren')).not.toHaveLength(0);
+ expect(apiMocks.getUniverseCastIntegrity).toHaveBeenCalledTimes(1);
+ expect(apiMocks.reviewUniverseCastIntegrity).not.toHaveBeenCalled();
+ });
+
+ it('names the provider, model and character count on the review button before it is pressed', async () => {
+ render(<CastIntegrityPanel {...props} />);
+ expect(await screen.findByRole('button', { name: /Review 2 characters with Local Llama · llama-3\.3/ })).toBeInTheDocument();
+ });
+
+ it('shows a not-reviewed character as such rather than as a pass', async () => {
+ render(<CastIntegrityPanel {...props} />);
+ expect(await screen.findByText('Dockhand')).toBeInTheDocument();
+ expect(screen.getByText('Not reviewed')).toBeInTheDocument();
+ });
+
+ it('reports partial coverage after a truncated review instead of a clean result', async () => {
+ apiMocks.reviewUniverseCastIntegrity.mockResolvedValue(report({
+ findings: [],
+ truncated: true,
+ coverage: [{ ...coverage[0], status: 'passed', findingCount: 0, semanticReviewed: true }, { ...coverage[1], status: 'truncated' }],
+ reviewScope: { ...report().reviewScope, characterCount: 1, remainingCount: 1 },
+ }));
+ render(<CastIntegrityPanel {...props} />);
+ fireEvent.click(await screen.findByRole('button', { name: /Review 2 characters/ }));
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith(expect.stringContaining('still unreviewed')));
+ expect(await screen.findByText('Truncated')).toBeInTheDocument();
+ });
+
+ it('offers no repair path on a contradictory finding — only the author can resolve it', async () => {
+ apiMocks.getUniverseCastIntegrity.mockResolvedValue(report({ findings: [contradictory] }));
+ render(<CastIntegrityPanel {...props} />);
+ expect(await screen.findByText('Contradictory')).toBeInTheDocument();
+ expect(screen.queryByRole('checkbox')).toBeNull();
+ expect(screen.queryByRole('button', { name: /Propose improvements/ })).toBeNull();
+ });
+
+ it('proposes, then applies ONLY the field the author ticked', async () => {
+ apiMocks.proposeCharacterAugmentation.mockResolvedValue({
+ entry: { id: 'c-1', name: 'Wren' },
+ fingerprint: 'fp-1',
+ proposals: [
+ { field: 'lie', before: 'old lie', after: 'a sharper lie', rationale: 'names the act' },
+ { field: 'want', before: 'old want', after: 'a sharper want', rationale: 'concrete goal' },
+ ],
+ });
+ apiMocks.applyCharacterAugmentation.mockResolvedValue({
+ universe: { id: 'u-1' }, entry: { id: 'c-1', name: 'Wren' }, appliedFields: ['lie'],
+ });
+
+ render(<CastIntegrityPanel {...props} />);
+ fireEvent.click(await screen.findByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: /Propose improvements/ }));
+
+ // Nothing is pre-accepted — the author opts in per field.
+ const lieBox = await screen.findByLabelText('Lie');
+ expect(lieBox).not.toBeChecked();
+ expect(screen.getByLabelText('Want')).not.toBeChecked();
+ expect(screen.getByRole('button', { name: /^Apply/ })).toBeDisabled();
+
+ fireEvent.click(lieBox);
+ fireEvent.click(screen.getByRole('button', { name: /^Apply 1/ }));
+
+ await waitFor(() => expect(apiMocks.applyCharacterAugmentation).toHaveBeenCalled());
+ const [, entryId, body] = apiMocks.applyCharacterAugmentation.mock.calls[0];
+ expect(entryId).toBe('c-1');
+ expect(body).toEqual({ fields: [{ field: 'lie', value: 'a sharper lie' }], fingerprint: 'fp-1' });
+ // The touched character is marked stale IN PLACE. Re-deriving the report
+ // would re-run the free deterministic pass and throw away the semantic
+ // review the user just paid a provider call for.
+ expect(await screen.findByText('Stale')).toBeInTheDocument();
+ expect(apiMocks.getUniverseCastIntegrity).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the semantic findings after an apply instead of discarding them', async () => {
+ apiMocks.getUniverseCastIntegrity.mockResolvedValue(report({
+ findings: [underspecified],
+ coverage: [{ ...coverage[0], semanticReviewed: true }, coverage[1]],
+ semanticReviewedCount: 1,
+ }));
+ apiMocks.proposeCharacterAugmentation.mockResolvedValue({
+ entry: { id: 'c-1', name: 'Wren' },
+ fingerprint: 'fp-1',
+ proposals: [{ field: 'lie', before: 'old lie', after: 'a sharper lie', rationale: '' }],
+ });
+ apiMocks.applyCharacterAugmentation.mockResolvedValue({
+ universe: { id: 'u-1' }, entry: { id: 'c-1' }, appliedFields: ['lie'],
+ });
+
+ render(<CastIntegrityPanel {...props} />);
+ fireEvent.click(await screen.findByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: /Propose improvements/ }));
+ fireEvent.click(await screen.findByLabelText('Lie'));
+ fireEvent.click(screen.getByRole('button', { name: /^Apply 1/ }));
+
+ expect(await screen.findByText('Stale')).toBeInTheDocument();
+ expect(screen.getByText(underspecified.evidence)).toBeInTheDocument();
+ });
+
+ it('blocks a mixed-character selection instead of firing one call per character', async () => {
+ apiMocks.getUniverseCastIntegrity.mockResolvedValue(report({
+ findings: [underspecified, { ...underspecified, id: 'c-2::underspecified::want', characterId: 'c-2', characterName: 'Dockhand', field: 'want' }],
+ }));
+ render(<CastIntegrityPanel {...props} />);
+ const boxes = await screen.findAllByRole('checkbox');
+ fireEvent.click(boxes[0]);
+ fireEvent.click(boxes[1]);
+ expect(screen.getByRole('button', { name: /Propose improvements/ })).toBeDisabled();
+ expect(screen.getByText(/one character at a time/)).toBeInTheDocument();
+ });
+
+ it('surfaces a stale apply as an error instead of pretending it landed', async () => {
+ apiMocks.proposeCharacterAugmentation.mockResolvedValue({
+ entry: { id: 'c-1', name: 'Wren' },
+ fingerprint: 'fp-stale',
+ proposals: [{ field: 'lie', before: 'old lie', after: 'a sharper lie', rationale: '' }],
+ });
+ apiMocks.applyCharacterAugmentation.mockRejectedValue(new Error('This character changed since the proposal was generated'));
+
+ render(<CastIntegrityPanel {...props} />);
+ fireEvent.click(await screen.findByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: /Propose improvements/ }));
+ fireEvent.click(await screen.findByLabelText('Lie'));
+ fireEvent.click(screen.getByRole('button', { name: /^Apply 1/ }));
+
+ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining('changed since the proposal')));
+ expect(props.onUniverseChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 7a58afbca0..71a5cee6de 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -14,12 +14,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import {
- Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus, Sparkles, Plus,
+ Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus, Sparkles, Plus, ShieldCheck,
} from 'lucide-react';
import toast from '../ui/Toast';
import IngredientPicker from '../IngredientPicker';
import VisionDescribeModal from './VisionDescribeModal';
import CorrectiveReferenceModal from './CorrectiveReferenceModal';
+import CastIntegrityPanel from './CastIntegrityPanel';
import { linkCatalogIngredient } from '../../services/apiCatalog';
import {
extractUniverseCanon,
@@ -126,6 +127,9 @@ export default function UniverseCanonSection({
const [renderingJobs, setRenderingJobs] = useState({});
const [refiningId, setRefiningId] = useState(null);
const [expandingId, setExpandingId] = useState(null);
+ // Cast integrity (#6415) — opens on the deterministic (free) report; the
+ // semantic review inside is a separate, explicitly-named provider call.
+ const [integrityOpen, setIntegrityOpen] = useState(false);
const [differentiating, setDifferentiating] = useState(false);
const [togglingLockId, setTogglingLockId] = useState(null);
// Ref mirrors togglingLockId for the reentrancy guard so handleToggleLock
@@ -833,6 +837,17 @@ export default function UniverseCanonSection({
objects, hide the action so it doesn't look applicable to the
current trunk. Keep it visible on the all-kinds view + on the
characters-filtered view. */}
+ {(!kindFilter || kindFilter === 'characters') ? (
+ <button
+ type="button"
+ onClick={() => setIntegrityOpen(true)}
+ disabled={charCount < 1}
+ title={charCount < 1 ? 'Add a character first' : 'Review whether the cast holds together — free completeness pass, optional semantic review'}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-bg border border-port-border text-gray-300 text-xs hover:border-port-accent/50 hover:text-white disabled:opacity-40"
+ >
+ <ShieldCheck size={12} /> Cast integrity
+ </button>
+ ) : null}
{(!kindFilter || kindFilter === 'characters') ? (
<button
type="button"
@@ -951,6 +966,17 @@ export default function UniverseCanonSection({
onClose={() => setCorrectTarget(null)}
/>
) : null}
+
+ {/* Cast integrity — the shared review contract (#6415). Mounted only
+ while open so it doesn't fetch the report until the user asks. */}
+ {integrityOpen ? (
+ <CastIntegrityPanel
+ open
+ universeId={universeId}
+ onUniverseChange={onUniverseChange}
+ onClose={() => setIntegrityOpen(false)}
+ />
+ ) : null}
</section>
);
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9eb968e395..2290aa23c0 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -52,6 +52,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
| `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
| `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, and `CHARACTER_SLIDER_AXES`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |
+| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — the finding kinds, review statuses and dimension ids mirrored from `server/lib/characterIntegrity.js` (guarded by `characterIntegrity.mirror.test.js`), plus `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy, `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `castIntegrityPassed` and `incompleteCoverage`. |
| `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. |
| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. |
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
diff --git a/client/src/lib/characterIntegrity.js b/client/src/lib/characterIntegrity.js
new file mode 100644
index 0000000000..c4bd248f7b
--- /dev/null
+++ b/client/src/lib/characterIntegrity.js
@@ -0,0 +1,93 @@
+/**
+ * Client-side vocabulary for the shared cast-integrity contract (#6415).
+ *
+ * Mirrors the display-relevant half of `server/lib/characterIntegrity.js` —
+ * the finding kinds, the review statuses, and the five semantic dimensions —
+ * plus the labels/tones the report UI renders them with.
+ *
+ * MIRRORED, not imported: the server module pulls `storyBible.js` (crypto +
+ * fileUtils) through `universeBibleCompleteness.js`, which has no place in the
+ * browser bundle. `server/lib/characterIntegrity.mirror.test.js` fails when the
+ * two lists drift, so this is a checked copy rather than a hopeful one.
+ */
+
+/** @see INTEGRITY_FINDING_KINDS in server/lib/characterIntegrity.js */
+export const INTEGRITY_FINDING_KINDS = Object.freeze(['missing', 'underspecified', 'contradictory']);
+
+/** @see AUGMENTABLE_FINDING_KINDS — `contradictory` needs the author, not a model. */
+export const AUGMENTABLE_FINDING_KINDS = Object.freeze(['missing', 'underspecified']);
+
+/** @see CHARACTER_REVIEW_STATUSES */
+export const CHARACTER_REVIEW_STATUSES = Object.freeze([
+ 'passed', 'findings', 'not-reviewed', 'truncated', 'stale',
+]);
+
+/** @see INCOMPLETE_REVIEW_STATUSES — none of these license "clean". */
+export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'truncated', 'stale']);
+
+/** @see INTEGRITY_DEPTHS */
+export const INTEGRITY_DEPTHS = Object.freeze(['explained', 'light', 'full']);
+
+/** @see INTEGRITY_DIMENSION_IDS */
+export const INTEGRITY_DIMENSION_IDS = Object.freeze([
+ 'control-predicts-behavior',
+ 'origin-supports-control',
+ 'drives-specific',
+ 'relationships-pressure',
+ 'challenge-testable',
+]);
+
+/**
+ * How each finding kind reads and what the user can do about it. `tone` maps to
+ * the badge color; `repairable` is what gates the Augment button — offering it
+ * on a `contradictory` finding would promise a fix the model cannot make,
+ * because it cannot know which of the two conflicting fields is the wrong one.
+ */
+export const FINDING_KIND_META = Object.freeze({
+ missing: Object.freeze({ label: 'Missing', tone: 'amber', repairable: true, hint: 'Nothing authored — fill it in, or let Expand fill the blanks.' }),
+ underspecified: Object.freeze({ label: 'Underspecified', tone: 'amber', repairable: true, hint: 'Authored but too generic to predict behavior — Augment can propose a sharper version.' }),
+ contradictory: Object.freeze({ label: 'Contradictory', tone: 'rose', repairable: false, hint: 'Two authored fields disagree. Only you can decide which one is wrong.' }),
+});
+
+/** Per-status badge copy for the coverage table. */
+export const REVIEW_STATUS_META = Object.freeze({
+ passed: Object.freeze({ label: 'Passed', tone: 'emerald' }),
+ findings: Object.freeze({ label: 'Findings', tone: 'amber' }),
+ 'not-reviewed': Object.freeze({ label: 'Not reviewed', tone: 'slate' }),
+ truncated: Object.freeze({ label: 'Truncated', tone: 'slate' }),
+ stale: Object.freeze({ label: 'Stale', tone: 'slate' }),
+});
+
+/** Why a character was held to a lighter standard — shown so the report doesn't look arbitrary. */
+export const DEPTH_META = Object.freeze({
+ full: Object.freeze({ label: 'Full', hint: 'Held to the whole framework.' }),
+ light: Object.freeze({ label: 'Light', hint: 'A minor role or a declared flat arc — only the conscious pursuit is expected.' }),
+ explained: Object.freeze({ label: 'Explained', hint: 'You ruled the interior unknown or not applicable and said why. That is a finished assessment.' }),
+});
+
+export const DIMENSION_LABELS = Object.freeze({
+ 'control-predicts-behavior': 'Belief predicts behavior',
+ 'origin-supports-control': 'Origin supports the belief',
+ 'drives-specific': 'Drives are specific',
+ 'relationships-pressure': 'Relationships create pressure',
+ 'challenge-testable': 'Strategy is testable',
+});
+
+/** Whether a finding can be handed to the augment flow. */
+export const findingIsRepairable = (finding) =>
+ FINDING_KIND_META[finding?.kind]?.repairable === true;
+
+/**
+ * Whether a report may be described as a clean pass — mirrors
+ * `castIntegrityPassed`. Any incomplete coverage row disqualifies it, so the UI
+ * cannot render a green summary over a half-reviewed cast.
+ */
+export const castIntegrityPassed = (report) => {
+ const coverage = report?.coverage || [];
+ if (coverage.length === 0) return false;
+ return coverage.every((c) => c.status === 'passed' && c.semanticReviewed);
+};
+
+/** Coverage rows that keep the report from being a clean pass, for the summary line. */
+export const incompleteCoverage = (report) =>
+ (report?.coverage || []).filter((c) => INCOMPLETE_REVIEW_STATUSES.includes(c.status));
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 9554b2d039..da8dfc6ea1 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -26,6 +26,7 @@ export * from './beatColors.js';
export * from './beatGrid.js';
export * from './bibleLimits.js';
export * from './characterFramework.js';
+export * from './characterIntegrity.js';
export * from './catalogTypes.js';
export * from './creativeDirectorPlan.js';
export * from './creativeDirectorPreview.js';
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 63a838a75b..18fb2d55a2 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -382,6 +382,47 @@ export const differentiateUniverseCast = (universeId, { providerId, model } = {}
...options,
}));
+// ── Cast integrity (#6415) ──────────────────────────────────────────────
+// DETERMINISTIC report — no provider call, safe to run on load. Returns
+// `{ findings, coverage, fingerprints, reviewScope }`; `reviewScope` names the
+// provider/model/batch size a semantic review WOULD spend, so the UI can show
+// the cost before the user opts in. Omit `characterIds` for the whole cast.
+export const getUniverseCastIntegrity = (universeId, { characterIds } = {}, options = {}) => {
+ const qs = Array.isArray(characterIds) && characterIds.length
+ ? `?characterIds=${encodeURIComponent(characterIds.join(','))}`
+ : '';
+ return request(`/universe-builder/${encodeURIComponent(universeId)}/characters/integrity${qs}`, options);
+};
+
+// SEMANTIC review — one bounded LLM call. Explicit user action only. Characters
+// past the batch cap come back with status `truncated`, never `passed`.
+export const reviewUniverseCastIntegrity = (universeId, { characterIds, providerId, model } = {}, options = {}) =>
+ request(`/universe-builder/${encodeURIComponent(universeId)}/characters/integrity/review`, {
+ method: 'POST',
+ body: JSON.stringify({ characterIds, providerId, model }),
+ ...options,
+ });
+
+// Propose sharper values for POPULATED fields — the augment pass the
+// fill-blanks expand deliberately can't do. Writes NOTHING; returns
+// `{ proposals: [{ field, before, after, rationale }], fingerprint }`.
+export const proposeCharacterAugmentation = (universeId, entryId, { fields, providerId, model } = {}, options = {}) =>
+ request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/augment`, {
+ method: 'POST',
+ body: JSON.stringify({ fields, providerId, model }),
+ ...options,
+ });
+
+// Apply only the proposals the author selected. `fingerprint` is the character
+// state the preview was reviewed against — a mismatch returns 409 rather than
+// overwriting an edit that landed in the meantime.
+export const applyCharacterAugmentation = (universeId, entryId, { fields, fingerprint } = {}, options = {}) =>
+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/augment/apply`, {
+ method: 'POST',
+ body: JSON.stringify({ fields, fingerprint }),
+ ...options,
+ }));
+
// Cross-reference: where each canon entry appears across the universe's
// linked series. Returns `{ characters: { [entryId]: [{seriesId, seriesName,
// issueIds, issueCount}] }, settings: ..., objects: ..., seriesCount,
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 1b6219e7d0..bd9e1045f2 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -364,42 +364,74 @@
"description": "Character-first planning pass used before the macro arc and again for post-arc reconciliation. It fully authors every series-linked character's narrative profile and render identity, completes causal Ghost/Wound/Lie/Want/Need engines, distinct voices, relationships, secrets, and provisional whole-series transitions before plot generation; afterward it preserves that foundation while permitting only necessary refinements and a small additive set of story-required characters.",
"model": "heavy",
"returnsJson": true,
- "variables": ["phase", "foundationFindingJson", "seriesJson", "outline", "charactersJson"]
+ "variables": [
+ "phase",
+ "foundationFindingJson",
+ "seriesJson",
+ "outline",
+ "charactersJson"
+ ]
},
"pipeline-foundation-repair": {
"name": "Pipeline — Foundation Repair",
"description": "Judge-directed pre-draft repair for the weak character or craft dimension. It strengthens the referenced core cast and whole-series character arcs as an ensemble, or writes an actionable series voice with concrete exemplars, while preserving established identities and story structure.",
"model": "heavy",
"returnsJson": true,
- "variables": ["dimension", "foundationFindingJson", "seriesJson", "outline", "charactersJson"]
+ "variables": [
+ "dimension",
+ "foundationFindingJson",
+ "seriesJson",
+ "outline",
+ "charactersJson"
+ ]
},
"pipeline-panel-editor": {
"name": "Pipeline — Reader Panel: The Editor",
"description": "Reader-panel persona (#2170, CWQE Phase 6). A senior developmental/line editor reads a condensed arc digest of the series and answers ~10 qualitative questions (momentum, earned ending, cut candidate, missing scene, thinnest character, best/worst scene, would recommend, haunts you, next book), citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
"model": "heavy",
"returnsJson": true,
- "variables": ["seriesName", "logline", "issueCount", "digest"]
+ "variables": [
+ "seriesName",
+ "logline",
+ "issueCount",
+ "digest"
+ ]
},
"pipeline-panel-genre-reader": {
"name": "Pipeline — Reader Panel: The Genre Reader",
"description": "Reader-panel persona (#2170, CWQE Phase 6). A voracious genre reader (50+ novels/year) reads a condensed arc digest and answers the panel's ~10 qualitative questions from a pure page-turn-pull perspective, citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
"model": "heavy",
"returnsJson": true,
- "variables": ["seriesName", "logline", "issueCount", "digest"]
+ "variables": [
+ "seriesName",
+ "logline",
+ "issueCount",
+ "digest"
+ ]
},
"pipeline-panel-writer": {
"name": "Pipeline — Reader Panel: The Writer",
"description": "Reader-panel persona (#2170, CWQE Phase 6). A working novelist reads a condensed arc digest for craft — structure, beats, setup/payoff — and answers the panel's ~10 qualitative questions citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
"model": "heavy",
"returnsJson": true,
- "variables": ["seriesName", "logline", "issueCount", "digest"]
+ "variables": [
+ "seriesName",
+ "logline",
+ "issueCount",
+ "digest"
+ ]
},
"pipeline-panel-first-reader": {
"name": "Pipeline — Reader Panel: The First Reader",
"description": "Reader-panel persona (#2170, CWQE Phase 6). An ordinary reader with no craft vocabulary reads a condensed arc digest and answers the panel's ~10 qualitative questions as pure emotional response, citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
"model": "heavy",
"returnsJson": true,
- "variables": ["seriesName", "logline", "issueCount", "digest"]
+ "variables": [
+ "seriesName",
+ "logline",
+ "issueCount",
+ "digest"
+ ]
},
"pipeline-reverse-outline": {
"name": "Pipeline — Reverse Outline (scene segmentation + plotline tagging)",
@@ -1114,6 +1146,20 @@
"source",
"shots"
]
+ },
+ "universe-cast-integrity-review": {
+ "name": "Universe — Cast Integrity Review",
+ "description": "Review an authored cast for narrative integrity rather than completeness: whether the stated control belief predicts behavior, its origin supports it, the three drives are specific, relationships create pressure, and a plausible challenge can test the strategy. Returns per-character findings with evidence and a suggested edit. Minor roles, flat arcs and explained unknowns are held to lighter requirements.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "universe-character-augment": {
+ "name": "Universe — Augment Populated Character Fields",
+ "description": "Sharpen character fields that are already written but too generic to predict behavior. Distinct from the fill-blanks expand: it rewrites populated prose while preserving the authored intent, and returns per-field proposals the author accepts or rejects individually.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/universe-cast-integrity-review.md b/data.reference/prompts/stages/universe-cast-integrity-review.md
new file mode 100644
index 0000000000..6f01a782a9
--- /dev/null
+++ b/data.reference/prompts/stages/universe-cast-integrity-review.md
@@ -0,0 +1,53 @@
+# Universe — Cast Integrity Review
+
+You are reviewing an authored cast for INTEGRITY, not for completeness. A separate deterministic pass already reports blank fields; do not duplicate it. Your job is the question a blank-count cannot answer: does each character, as written, hold together?
+
+## The dimensions
+
+Each character below carries a `dimensions` array naming the checks that apply to it. Ask ONLY those questions of that character.
+
+```json
+{{dimensionsJson}}
+```
+
+## The cast
+
+```json
+{{castJson}}
+```
+
+## Rules
+
+1. **Evidence, or nothing.** Every finding must quote or paraphrase the specific authored text that produced it. A finding that only asserts a problem ("the motivation is weak") is worthless and will be discarded. Name what you read and why it doesn't hold.
+2. **No finding is the normal result.** Most characters in most casts are fine. Do not manufacture a finding to look thorough. Returning an empty `findings` array is a valid, common, correct answer.
+3. **Never demand trauma, and never demand redemption.** A character with no Ghost is not broken. A character who does not change is not broken. A villain who stays a villain is not broken. Deliberate ambiguity is a legitimate authorial choice — a field left open ON PURPOSE, where the surrounding material shows the intent, is not a gap.
+4. **Respect the declared depth.** `depth: "light"` means a minor role or a declared flat arc — expect the conscious pursuit and nothing about origin damage. `depth: "explained"` means the author already ruled the interior unknown or not-applicable and said why; that is a finished assessment, so raise nothing.
+5. **Only the three kinds:**
+ - `underspecified` — authored, but so generic it predicts no particular behavior ("wants to be happy", "fears failure"). This is the one you will use most.
+ - `contradictory` — two authored fields genuinely disagree (the stated belief predicts one behavior, the personality describes the opposite). Name BOTH fields in the evidence.
+ - `missing` — reserve this for a field whose absence breaks a dimension the character IS held to. The deterministic pass covers plain blanks; prefer the other two kinds.
+6. **`status` means perceived value to a group** — respect, standing, being counted. Not wealth, not dominance. For a non-human character, read all three drives in terms of its own form rather than forcing a human interior onto it.
+7. **The Lie and the theory of control are not the same field.** A `lie` is a judgment about a belief; `psychology.theoryOfControl` is the rule the character actually runs on, stated as they would hold it. Do not report them as duplicates just because they are related, and do not demand the `need` be the literal opposite of either — it may qualify the belief instead.
+8. **One finding per field per character.** If a field has several problems, write the one that matters most.
+
+## Output contract
+
+Return ONLY valid JSON, no markdown fence, no commentary.
+
+`characterId` MUST be an `id` copied verbatim from the cast above. `field` MUST be one of: `motivations`, `ghost`, `wound`, `lie`, `want`, `need`, `relationshipLinks`, `psychology.theoryOfControl`, `psychology.strategy`, `psychology.protectiveBenefit`, `psychology.presentCost`, `psychology.testingPressure`, `psychology.candidateChange`, or `psychology.drives.<survival|connection|status>.<desire|fear>`. `dimension` MUST be one of the dimension ids listed above, and must be one the character's own `dimensions` array contains. Findings that break any of these rules are dropped.
+
+```json
+{
+ "findings": [
+ {
+ "characterId": "string — verbatim from the cast",
+ "field": "string — one of the paths above",
+ "kind": "underspecified | contradictory | missing",
+ "dimension": "string — one of the dimension ids",
+ "evidence": "string — REQUIRED. The authored text you read, and why it does not hold.",
+ "suggestion": "string — a concrete, specific alternative the author could write. Not 'add more detail'."
+ }
+ ],
+ "rationale": "1-sentence summary of the cast's overall state"
+}
+```
diff --git a/data.reference/prompts/stages/universe-character-augment.md b/data.reference/prompts/stages/universe-character-augment.md
new file mode 100644
index 0000000000..6950e28bd1
--- /dev/null
+++ b/data.reference/prompts/stages/universe-character-augment.md
@@ -0,0 +1,58 @@
+# Universe — Augment Populated Character Fields
+
+You are SHARPENING fields that are already written. This is not the fill-blanks pass — the fields below have content, and the author has judged it too generic to predict behavior. Rewrite each one so it does.
+
+## The character
+
+```json
+{{characterJson}}
+```
+
+## Other characters in this universe (stay distinct from them)
+
+```json
+{{peersJson}}
+```
+
+## Fields to sharpen
+
+Each entry gives the field path and its CURRENT value. Return a replacement for each one you can genuinely improve.
+
+```json
+{{fieldsJson}}
+```
+
+## Rules
+
+1. **Preserve the authored intent.** You are making the existing idea specific, not replacing it with a better idea of your own. If the current value says the character fears abandonment, the replacement still fears abandonment — it just says who, since when, and what they do about it. A rewrite that changes what the character IS will be rejected by the author and wastes the call.
+2. **Specific beats intense.** Do not reach for trauma, tragedy, or melodrama to add weight. "Checks that the door is locked twice before sitting down" is stronger than "was profoundly damaged by his childhood".
+3. **Behavior, not adjectives.** Every value should let a writer predict what this character DOES in a scene. Name the concrete action, habit, or refusal.
+4. **Stay inside the field.** `psychology.drives.status.fear` is one sentence about the fear of losing standing in a group — not a paragraph restating the whole character. Respect what each path is for:
+ - `motivations` — what they want and fear losing, 2–3 sentences.
+ - `ghost` / `wound` — the origin event, and the damage it left. 1–2 sentences each.
+ - `lie` / `need` — one sentence each. The `need` may QUALIFY the belief rather than be its literal opposite.
+ - `want` — the concrete external goal, one sentence.
+ - `psychology.theoryOfControl` — the operating rule in the character's own terms, stated WITHOUT calling it false.
+ - `psychology.strategy` / `protectiveBenefit` / `presentCost` — the behavior it motivates, what it genuinely protects, what it costs now.
+ - `psychology.testingPressure` / `candidateChange` — anticipated only. What would put the rule under load, and the revision it might undergo. Do NOT write plot events, issue numbers, or a sequence here.
+ - `psychology.drives.<axis>.<desire|fear>` — one specific sentence. `status` means perceived value to a GROUP, not wealth or dominance.
+5. **Stay distinct from the peers listed above.** Don't hand two characters the same wound or the same fear.
+6. **Skip what you cannot improve.** Omit a field rather than returning a paraphrase of its current value. An honest partial result is better than churn the author has to read and reject.
+7. **Non-human characters keep their own form.** Read the drives as continuity, coupling, and standing within whatever the character belongs to, rather than forcing a human interior onto it.
+
+## Output contract
+
+Return ONLY valid JSON, no markdown fence, no commentary. `field` MUST be copied verbatim from the fields list above; anything else is dropped.
+
+```json
+{
+ "proposals": [
+ {
+ "field": "string — verbatim from the fields list",
+ "value": "string — the replacement text",
+ "rationale": "string — one short line on what you made specific"
+ }
+ ],
+ "rationale": "1-sentence summary of the direction you took"
+}
+```
diff --git a/scripts/migrations/363-cast-integrity-stages.js b/scripts/migrations/363-cast-integrity-stages.js
new file mode 100644
index 0000000000..b35559b450
--- /dev/null
+++ b/scripts/migrations/363-cast-integrity-stages.js
@@ -0,0 +1,20 @@
+/**
+ * Seed the cast-integrity review + character-augment stages into existing
+ * installs (#6415).
+ *
+ * Boot runs migrations (`server/index.js`) but not `setup-data.js`, so an
+ * install that upgrades by pulling and restarting would otherwise reach the new
+ * Review Cast / Augment buttons with no template and no stage-config entry, and
+ * `runStagedLLM` would throw "Stage not found" on the first click.
+ *
+ * The shared seed helper copies only missing files and merges only missing
+ * config entries, so a user who has already customized either template keeps
+ * their version.
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'universe-cast-integrity-review',
+ 'universe-character-augment',
+]);
diff --git a/scripts/migrations/363-cast-integrity-stages.test.js b/scripts/migrations/363-cast-integrity-stages.test.js
new file mode 100644
index 0000000000..b035c3ab50
--- /dev/null
+++ b/scripts/migrations/363-cast-integrity-stages.test.js
@@ -0,0 +1,12 @@
+import { describe } from 'vitest';
+
+import migration from './363-cast-integrity-stages.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+describe('migration 363 — seed the cast integrity stages', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: ['universe-cast-integrity-review', 'universe-character-augment'],
+ prefix: 'migration-363-',
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 928b132008..7fb87e6457 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -111,6 +111,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. |
| `storyBible.js` | Canonical Character / Place / Object shapes; re-exports `BIBLE_LIMITS` from `bibleLimits.js`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |
| `characterFramework.js` | The narrative-character framework as one definition: `CHARACTER_ARC_TYPES`, `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_FIELDS` (the Ghost→Wound→Lie→Need→Want chain plus motivations, arc type, secrets, relationship links), `CHARACTER_FRAMEWORK_LIMITS`, and `pickCharacterFramework` / `pickCastFramework` (framework-only projection for an author-side review prompt, empty entries dropped). A pure leaf over `bibleLimits.js` so the store editableFields, the Zod schemas, and the client editors share one list (#6417). |
+| `characterIntegrity.js` | The shared cast-integrity contract (#6415): `INTEGRITY_FINDING_KINDS` (`missing` / `underspecified` / `contradictory`), the five `INTEGRITY_DIMENSIONS`, `CHARACTER_REVIEW_STATUSES` (`passed` vs `not-reviewed` / `truncated` / `stale` — incomplete coverage can never read as clean), `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` / `staleReportCharacterIds` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
| `bibleLimits.js` | `BIBLE_LIMITS` — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of `storyBible.js` (which pulls `crypto` + `fileUtils`) so `catalogTypes.js` and the browser bundle can read the numbers alone. |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index da38f1157a..b9ea0643ca 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -16305,6 +16305,22 @@
"server/routes/universeBuilder/canon.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/universe-builder/:id/characters/:entryId/augment",
+ "mountPath": "/api/universe-builder",
+ "sources": [
+ "server/routes/universeBuilder/canon.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/universe-builder/:id/characters/:entryId/augment/apply",
+ "mountPath": "/api/universe-builder",
+ "sources": [
+ "server/routes/universeBuilder/canon.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/universe-builder/:id/characters/:entryId/expand",
@@ -16353,6 +16369,22 @@
"server/routes/universeBuilder/canon.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/universe-builder/:id/characters/integrity",
+ "mountPath": "/api/universe-builder",
+ "sources": [
+ "server/routes/universeBuilder/canon.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/universe-builder/:id/characters/integrity/review",
+ "mountPath": "/api/universe-builder",
+ "sources": [
+ "server/routes/universeBuilder/canon.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/universe-builder/:id/export/markdown",
@@ -17868,8 +17900,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2213,
- "declarations": 2221,
+ "operations": 2217,
+ "declarations": 2225,
"sourceFiles": 233
}
}
diff --git a/server/lib/characterIntegrity.js b/server/lib/characterIntegrity.js
new file mode 100644
index 0000000000..c8c93b984f
--- /dev/null
+++ b/server/lib/characterIntegrity.js
@@ -0,0 +1,506 @@
+/**
+ * The shared cast-integrity contract (#6415).
+ *
+ * "Every field is filled" and "this character holds together" are different
+ * questions, and until now only the first had an answer. `missingBibleFields`
+ * counts blanks; `applyExpansion` fills blanks; neither can say that a fully
+ * populated profile states a control belief its own behavior contradicts, or
+ * that its three drives are the same sentence written three ways.
+ *
+ * This module is the vocabulary both questions report in, so one report shape
+ * reaches every consumer instead of each surface inventing its own:
+ *
+ * - the deterministic pass (`castCompletenessFindings`) — NO provider calls,
+ * safe to run on every load
+ * - the semantic pass (`mergeSemanticFindings`) — an explicitly invoked LLM
+ * review, validated back into the same finding shape
+ *
+ * PURE: shape, predicates and merges only. No storage, no provider I/O, no
+ * universe/series/work concepts — the callers own those, which is what lets
+ * Universe Bible, Series, FableLoom and Writers Room share one contract.
+ *
+ * Reports are DERIVED, never persisted, so `characterFingerprint` is what keeps
+ * a repair honest: a proposal carries the fingerprint of the character it was
+ * reviewed against, and applying it to a record that has since changed is
+ * refused rather than silently overwriting the newer edit.
+ */
+
+import {
+ CHARACTER_FRAMEWORK_TEXT_FIELDS,
+} from './characterFramework.js';
+import {
+ bibleFieldIsBlank,
+ characterPsychologyIsBlank,
+} from './universeBibleCompleteness.js';
+import { PSYCHOLOGY_DRIVE_AXES, isBlank } from './storyBible.js';
+
+/**
+ * What KIND of gap a finding reports. The three are genuinely different repairs
+ * and must not collapse into one "incomplete" bucket:
+ * - `missing` — the field is blank. Fill-blanks can close it.
+ * Deterministic; no model required.
+ * - `underspecified` — populated, but too generic to predict behavior
+ * ("wants to be happy"). Augmentation can close it.
+ * - `contradictory` — populated and specific, but at odds with another
+ * authored field. NOBODY can close it automatically; it needs the author,
+ * because the report cannot know which of the two fields is the wrong one.
+ */
+export const INTEGRITY_FINDING_KINDS = Object.freeze(['missing', 'underspecified', 'contradictory']);
+const FINDING_KIND_SET = new Set(INTEGRITY_FINDING_KINDS);
+
+/** Only `missing` and `underspecified` are machine-repairable — see above. */
+export const AUGMENTABLE_FINDING_KINDS = Object.freeze(['missing', 'underspecified']);
+
+/**
+ * The five questions the semantic review asks. Stated as checks on the
+ * AUTHORED material, not as demands for a particular kind of character: each
+ * one can be satisfied by a deliberately flat, opaque or minor character, and
+ * "no finding" is the expected result for most of a cast.
+ */
+export const INTEGRITY_DIMENSIONS = Object.freeze([
+ Object.freeze({
+ id: 'control-predicts-behavior',
+ label: 'Belief predicts behavior',
+ question: 'Does the stated control belief actually predict the behavior the profile describes?',
+ }),
+ Object.freeze({
+ id: 'origin-supports-control',
+ label: 'Origin supports the belief',
+ question: 'Does the Ghost/Wound history make this belief a plausible thing for this character to have concluded?',
+ }),
+ Object.freeze({
+ id: 'drives-specific',
+ label: 'Drives are specific',
+ question: 'Are the survival, connection and status desires/fears distinct and specific to this character, rather than one sentiment restated three times?',
+ }),
+ Object.freeze({
+ id: 'relationships-pressure',
+ label: 'Relationships create pressure',
+ question: 'Do the authored relationships put meaningful pressure on the belief, rather than only describing who knows whom?',
+ }),
+ Object.freeze({
+ id: 'challenge-testable',
+ label: 'Strategy is testable',
+ question: 'Can a plausible story challenge test this strategy — is there something that would actually cost this character to hold onto it?',
+ }),
+]);
+export const INTEGRITY_DIMENSION_IDS = Object.freeze(INTEGRITY_DIMENSIONS.map((d) => d.id));
+const DIMENSION_ID_SET = new Set(INTEGRITY_DIMENSION_IDS);
+
+/**
+ * Per-character coverage. The whole point of the enum is that `passed` and
+ * `not-reviewed` are NOT the same answer — a review that quietly skipped half
+ * the cast and reported no findings would read as a clean bill of health.
+ * - `passed` — reviewed, nothing found
+ * - `findings` — reviewed, at least one finding
+ * - `not-reviewed` — outside the requested scope, or the pass never reached it
+ * - `truncated` — the review ran but its budget cut this character off
+ * - `stale` — the character changed after the report was measured
+ */
+export const CHARACTER_REVIEW_STATUSES = Object.freeze([
+ 'passed', 'findings', 'not-reviewed', 'truncated', 'stale',
+]);
+
+/** Statuses that do NOT license "this cast is clean". */
+export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'truncated', 'stale']);
+
+/**
+ * The framework fields the deterministic pass measures, in report order.
+ * Sourced from `characterFramework.js` plus the psychology profile so a field
+ * added there is measured here without a second edit.
+ *
+ * `relationshipLinks` is deliberately absent: it is authored by picking a
+ * sibling entry, and a solo character legitimately has none. The
+ * `relationships-pressure` DIMENSION still asks about it semantically — the
+ * difference is that a human/model judges whether the pressure is meaningful,
+ * where a blank-count would just call every hermit incomplete.
+ */
+export const INTEGRITY_FIELDS = Object.freeze([...CHARACTER_FRAMEWORK_TEXT_FIELDS, 'psychology']);
+
+/**
+ * How much of the framework a character is expected to carry.
+ *
+ * The issue is explicit that minor roles, flat arcs, unknowns and deliberate
+ * ambiguity get "lighter or explained requirements, not manufactured trauma or
+ * mandatory redemption" — so the depth is COMPUTED from what the author already
+ * declared rather than demanded uniformly:
+ *
+ * - `explained` — the author ruled the interior out (`psychology.assessment`
+ * of `unknown` / `not-applicable`) AND said why. That is a finished
+ * assessment; the pass asks for nothing further.
+ * - `light` — a declared minor role, or a flat arc. Wants the conscious
+ * pursuit (motivations/want) and nothing about origin damage.
+ * - `full` — everything else.
+ */
+export const INTEGRITY_DEPTHS = Object.freeze(['explained', 'light', 'full']);
+
+/** Fields each depth actually asks for. `explained` asks for none. */
+const DEPTH_FIELDS = Object.freeze({
+ explained: Object.freeze([]),
+ light: Object.freeze(['motivations', 'want']),
+ full: INTEGRITY_FIELDS,
+});
+
+/**
+ * Roles that read as "this character is scenery" — matched as whole words on a
+ * lowercased role so "extra" doesn't fire on "extraordinary". Deliberately
+ * short: the cost of missing one is a full-depth report on a bit player (noisy
+ * but correct), while the cost of over-matching is silently excusing a lead.
+ */
+const MINOR_ROLE_WORDS = Object.freeze([
+ 'minor', 'background', 'extra', 'cameo', 'walk-on', 'bit', 'incidental',
+]);
+
+const roleIsMinor = (role) => {
+ if (typeof role !== 'string') return false;
+ const words = role.toLowerCase().split(/[^a-z-]+/).filter(Boolean);
+ return words.some((w) => MINOR_ROLE_WORDS.includes(w));
+};
+
+/**
+ * Which depth applies to one character. Exported so a UI can explain WHY a
+ * character was held to a lighter standard instead of looking inconsistent.
+ */
+export function characterIntegrityDepth(entry) {
+ if (!entry || typeof entry !== 'object') return 'light';
+ const assessment = entry.psychology?.assessment;
+ if ((assessment === 'unknown' || assessment === 'not-applicable')
+ && !isBlank(entry.psychology?.assessmentNote)) {
+ return 'explained';
+ }
+ if (roleIsMinor(entry.role) || entry.arcType === 'flat') return 'light';
+ return 'full';
+}
+
+/** The dimensions worth asking about a character at its depth. */
+export function characterIntegrityDimensions(entry) {
+ const depth = characterIntegrityDepth(entry);
+ if (depth === 'explained') return [];
+ if (depth === 'light') return ['control-predicts-behavior', 'challenge-testable'];
+ return INTEGRITY_DIMENSION_IDS;
+}
+
+const findingId = (characterId, kind, field) => `${characterId}::${kind}::${field}`;
+
+/**
+ * One finding, normalized. Every finding — deterministic or model-authored —
+ * has the same shape so a consumer never branches on where it came from.
+ */
+const makeFinding = ({
+ characterId, characterName, kind, field, evidence, suggestion, dimension,
+}) => ({
+ id: findingId(characterId, kind, field),
+ characterId,
+ characterName: characterName || '',
+ kind,
+ // Dotted path into the character record — `psychology.drives.status.fear`,
+ // not just `psychology` — so an editor can focus the exact input.
+ field,
+ dimension: dimension || null,
+ evidence: evidence || '',
+ suggestion: suggestion || '',
+});
+
+/**
+ * Deterministic gaps on ONE character. No provider, no judgement — a field
+ * this reports is genuinely empty, which is why it can run on every load.
+ *
+ * `psychology` expands into its leaves rather than reporting one opaque gap:
+ * "the profile is unfilled" is not actionable, "the status drive has no fear"
+ * is. The leaf walk only runs once the profile is partly authored — an
+ * untouched character reports the single `psychology` gap instead of nine.
+ */
+export function characterCompletenessFindings(entry) {
+ if (!entry || typeof entry !== 'object') return [];
+ const depth = characterIntegrityDepth(entry);
+ const fields = DEPTH_FIELDS[depth] || DEPTH_FIELDS.full;
+ const findings = [];
+ const base = { characterId: entry.id, characterName: entry.name, kind: 'missing' };
+ for (const field of fields) {
+ if (field !== 'psychology') {
+ if (bibleFieldIsBlank(entry, field)) {
+ findings.push(makeFinding({ ...base, field, evidence: `\`${field}\` is empty.` }));
+ }
+ continue;
+ }
+ if (!characterPsychologyIsBlank(entry.psychology)) continue;
+ // Nothing authored at all — one gap, not a wall of them.
+ if (!entry.psychology || typeof entry.psychology !== 'object') {
+ findings.push(makeFinding({
+ ...base,
+ field: 'psychology',
+ evidence: 'No theory of control or drives authored.',
+ }));
+ continue;
+ }
+ if (isBlank(entry.psychology.theoryOfControl)) {
+ findings.push(makeFinding({
+ ...base,
+ field: 'psychology.theoryOfControl',
+ evidence: 'No control belief stated, so nothing predicts this behavior.',
+ }));
+ }
+ for (const axis of PSYCHOLOGY_DRIVE_AXES) {
+ for (const leaf of ['desire', 'fear']) {
+ if (!isBlank(entry.psychology.drives?.[axis]?.[leaf])) continue;
+ findings.push(makeFinding({
+ ...base,
+ field: `psychology.drives.${axis}.${leaf}`,
+ evidence: `The ${axis} drive has no ${leaf}.`,
+ }));
+ }
+ }
+ }
+ return findings;
+}
+
+/**
+ * A content fingerprint of the fields a report is measured against.
+ *
+ * Deliberately narrow: only the integrity fields plus role/arcType (which pick
+ * the depth) and the relationship targets (which the pressure dimension reads).
+ * A wardrobe edit or a re-render must NOT invalidate a review that had nothing
+ * to do with it — a fingerprint over the whole record would make every report
+ * stale on the next image job.
+ */
+export function characterFingerprint(entry) {
+ if (!entry || typeof entry !== 'object') return '';
+ const parts = [entry.id || '', entry.role || '', entry.arcType || ''];
+ for (const field of CHARACTER_FRAMEWORK_TEXT_FIELDS) {
+ parts.push(typeof entry[field] === 'string' ? entry[field].trim() : '');
+ }
+ const p = entry.psychology;
+ if (p && typeof p === 'object' && !Array.isArray(p)) {
+ parts.push(
+ p.theoryOfControl || '', p.strategy || '', p.protectiveBenefit || '',
+ p.presentCost || '', p.testingPressure || '', p.candidateChange || '',
+ p.assessment || '', p.assessmentNote || '',
+ );
+ for (const axis of PSYCHOLOGY_DRIVE_AXES) {
+ parts.push(p.drives?.[axis]?.desire || '', p.drives?.[axis]?.fear || '');
+ }
+ }
+ const links = Array.isArray(entry.relationshipLinks) ? entry.relationshipLinks : [];
+ for (const link of links) parts.push(`${link?.targetCharacterId || ''}:${link?.type || ''}`);
+ // Length-prefixed join: a `|` inside an authored field can't forge a
+ // boundary and make two different casts fingerprint the same.
+ return parts.map((s) => `${String(s).length}:${s}`).join('|');
+}
+
+/**
+ * Build the deterministic report for a cast.
+ *
+ * `characterIds` scopes the pass; every character outside it is still LISTED,
+ * with status `not-reviewed`. That is the coverage contract — the caller can
+ * always tell "no findings" apart from "never looked".
+ */
+export function buildCastIntegrityReport(characters, { characterIds = null } = {}) {
+ const cast = Array.isArray(characters) ? characters.filter((c) => c?.id) : [];
+ const scope = characterIds ? new Set(characterIds) : null;
+ const findings = [];
+ const coverage = cast.map((entry) => {
+ const inScope = !scope || scope.has(entry.id);
+ if (!inScope) {
+ return {
+ characterId: entry.id,
+ characterName: entry.name || '',
+ depth: characterIntegrityDepth(entry),
+ status: 'not-reviewed',
+ findingCount: 0,
+ semanticReviewed: false,
+ };
+ }
+ const own = characterCompletenessFindings(entry);
+ findings.push(...own);
+ return {
+ characterId: entry.id,
+ characterName: entry.name || '',
+ depth: characterIntegrityDepth(entry),
+ status: own.length ? 'findings' : 'passed',
+ findingCount: own.length,
+ // The deterministic pass alone never counts as a semantic review — a
+ // blank-complete character is exactly the case this issue exists for.
+ semanticReviewed: false,
+ };
+ });
+ return {
+ findings,
+ coverage,
+ reviewedCount: coverage.filter((c) => c.status !== 'not-reviewed').length,
+ castCount: cast.length,
+ semanticReviewedCount: 0,
+ };
+}
+
+/**
+ * Every field path a finding may legally name. A model-authored finding
+ * pointing anywhere else is dropped rather than rendered — the report must not
+ * be able to invent a field the editor has no input for.
+ */
+export const INTEGRITY_FIELD_PATHS = Object.freeze([
+ ...INTEGRITY_FIELDS,
+ 'relationshipLinks',
+ 'psychology.theoryOfControl',
+ 'psychology.strategy',
+ 'psychology.protectiveBenefit',
+ 'psychology.presentCost',
+ 'psychology.testingPressure',
+ 'psychology.candidateChange',
+ ...PSYCHOLOGY_DRIVE_AXES.flatMap((axis) => [
+ `psychology.drives.${axis}.desire`,
+ `psychology.drives.${axis}.fear`,
+ ]),
+]);
+const FIELD_PATH_SET = new Set(INTEGRITY_FIELD_PATHS);
+
+/**
+ * Fold a model's semantic findings into a deterministic report.
+ *
+ * Everything here is validation, because the input is an LLM payload: a finding
+ * naming a character outside the cast, an unknown field path, an unknown kind
+ * or an unknown dimension is DROPPED rather than shown — a review that invents
+ * a field is worse than a review that reports less.
+ *
+ * `reviewedIds` is what the caller actually managed to review; ids in scope but
+ * absent from it become `truncated`, so a budget-capped batch cannot read as a
+ * clean pass over the whole cast.
+ */
+export function mergeSemanticFindings(report, {
+ characters, findings = [], reviewedIds = [], truncated = false,
+} = {}) {
+ const cast = Array.isArray(characters) ? characters.filter((c) => c?.id) : [];
+ const byId = new Map(cast.map((c) => [c.id, c]));
+ const reviewed = new Set(reviewedIds.filter((id) => byId.has(id)));
+ const seen = new Set();
+ const accepted = [];
+ for (const raw of Array.isArray(findings) ? findings : []) {
+ const entry = byId.get(raw?.characterId);
+ if (!entry || !reviewed.has(raw.characterId)) continue;
+ const kind = typeof raw.kind === 'string' ? raw.kind.trim().toLowerCase() : '';
+ if (!FINDING_KIND_SET.has(kind)) continue;
+ const field = typeof raw.field === 'string' ? raw.field.trim() : '';
+ if (!FIELD_PATH_SET.has(field)) continue;
+ const dimension = typeof raw.dimension === 'string' ? raw.dimension.trim() : '';
+ if (dimension && !DIMENSION_ID_SET.has(dimension)) continue;
+ // A dimension the character's depth excuses must not produce a finding —
+ // that is how "lighter requirements" stays a real guarantee rather than a
+ // prompt suggestion the model can talk itself out of.
+ const allowedDims = characterIntegrityDimensions(entry);
+ if (dimension && !allowedDims.includes(dimension)) continue;
+ const evidence = typeof raw.evidence === 'string' ? raw.evidence.trim() : '';
+ // Evidence is the whole product. A finding that only asserts a problem is
+ // not reviewable by the author, so it is not worth showing.
+ if (!evidence) continue;
+ const finding = makeFinding({
+ characterId: raw.characterId,
+ characterName: entry.name,
+ kind,
+ field,
+ dimension: dimension || null,
+ evidence,
+ suggestion: typeof raw.suggestion === 'string' ? raw.suggestion.trim() : '',
+ });
+ if (seen.has(finding.id)) continue;
+ seen.add(finding.id);
+ accepted.push(finding);
+ }
+
+ // Deterministic findings win a collision: they state a fact (the field is
+ // empty) where the model states a judgement about the same field.
+ const deterministic = Array.isArray(report?.findings) ? report.findings : [];
+ const deterministicIds = new Set(deterministic.map((f) => f.id));
+ const merged = [...deterministic, ...accepted.filter((f) => !deterministicIds.has(f.id))];
+ const countsById = merged.reduce((acc, f) => {
+ acc[f.characterId] = (acc[f.characterId] || 0) + 1;
+ return acc;
+ }, {});
+
+ const coverage = (report?.coverage || []).map((row) => {
+ if (row.status === 'not-reviewed') return row;
+ const semanticReviewed = reviewed.has(row.characterId);
+ const findingCount = countsById[row.characterId] || 0;
+ // In deterministic scope but the semantic pass never reached it.
+ if (!semanticReviewed) {
+ return {
+ ...row,
+ status: truncated ? 'truncated' : row.status,
+ findingCount,
+ semanticReviewed: false,
+ };
+ }
+ return {
+ ...row,
+ status: findingCount ? 'findings' : 'passed',
+ findingCount,
+ semanticReviewed: true,
+ };
+ });
+
+ return {
+ ...report,
+ findings: merged,
+ coverage,
+ semanticReviewedCount: coverage.filter((c) => c.semanticReviewed).length,
+ };
+}
+
+/**
+ * Whether a report licenses "this cast has been reviewed and is clean".
+ * False whenever ANY character is `not-reviewed` / `truncated` / `stale` —
+ * incomplete coverage cannot pass.
+ */
+export const castIntegrityPassed = (report) => {
+ const coverage = report?.coverage || [];
+ if (coverage.length === 0) return false;
+ return coverage.every((c) => c.status === 'passed' && c.semanticReviewed);
+};
+
+/**
+ * The field paths the augment flow may propose a value for: every integrity
+ * path that holds a plain STRING.
+ *
+ * `psychology` (the container) and `relationshipLinks` are excluded because
+ * they are not prose — a "before / after" preview of a structured object is not
+ * something an author can review field-by-field, and a link row points at a
+ * sibling id no model can mint. Both can still be REPORTED on; they just can't
+ * be machine-repaired.
+ */
+export const AUGMENTABLE_FIELD_PATHS = Object.freeze(
+ INTEGRITY_FIELD_PATHS.filter((p) => p !== 'psychology' && p !== 'relationshipLinks'),
+);
+const AUGMENTABLE_PATH_SET = new Set(AUGMENTABLE_FIELD_PATHS);
+
+/** Whether a dotted path names a string-valued integrity field. */
+export const isAugmentableFieldPath = (path) => AUGMENTABLE_PATH_SET.has(path);
+
+/** Current value at a dotted integrity path — `''` when unset at any level. */
+export function readIntegrityField(entry, path) {
+ if (!entry || typeof entry !== 'object' || !AUGMENTABLE_PATH_SET.has(path)) return '';
+ const value = path.split('.').reduce((node, key) => (
+ node && typeof node === 'object' ? node[key] : undefined
+ ), entry);
+ return typeof value === 'string' ? value : '';
+}
+
+/**
+ * A copy of `entry` with `path` set to `value`, materializing the psychology
+ * container and drive rows as needed. Pure — the caller still runs the result
+ * through the bible sanitizer before persisting.
+ */
+export function withIntegrityField(entry, path, value) {
+ if (!entry || typeof entry !== 'object' || !AUGMENTABLE_PATH_SET.has(path)) return entry;
+ const [head, ...rest] = path.split('.');
+ if (rest.length === 0) return { ...entry, [head]: value };
+ const psychology = (entry.psychology && typeof entry.psychology === 'object' && !Array.isArray(entry.psychology))
+ ? entry.psychology
+ : {};
+ if (rest.length === 1) return { ...entry, psychology: { ...psychology, [rest[0]]: value } };
+ // psychology.drives.<axis>.<leaf>
+ const [, axis, leaf] = rest;
+ const drives = (psychology.drives && typeof psychology.drives === 'object') ? psychology.drives : {};
+ const row = (drives[axis] && typeof drives[axis] === 'object') ? drives[axis] : {};
+ return {
+ ...entry,
+ psychology: { ...psychology, drives: { ...drives, [axis]: { ...row, [leaf]: value } } },
+ };
+}
diff --git a/server/lib/characterIntegrity.mirror.test.js b/server/lib/characterIntegrity.mirror.test.js
new file mode 100644
index 0000000000..9bbbd80a1d
--- /dev/null
+++ b/server/lib/characterIntegrity.mirror.test.js
@@ -0,0 +1,80 @@
+/**
+ * Parity guard: the client's integrity vocabulary must match the server's.
+ *
+ * `client/src/lib/characterIntegrity.js` cannot import the server module — it
+ * reaches `storyBible.js` (crypto + fileUtils) through
+ * `universeBibleCompleteness.js`, which has no place in the browser bundle — so
+ * the two lists are mirrored by hand. A drift here is not cosmetic: the client
+ * decides which findings offer an Augment button from its OWN kind list, so a
+ * kind the server can emit but the client doesn't know renders as an unlabeled
+ * badge with no repair path, and a status the client doesn't know silently
+ * falls out of the "is this cast clean?" check.
+ *
+ * Reads the client file as TEXT rather than importing it: this suite runs in
+ * the server (node) project, which has no React/JSX resolution.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import {
+ INTEGRITY_FINDING_KINDS,
+ AUGMENTABLE_FINDING_KINDS,
+ CHARACTER_REVIEW_STATUSES,
+ INCOMPLETE_REVIEW_STATUSES,
+ INTEGRITY_DEPTHS,
+ INTEGRITY_DIMENSION_IDS,
+} from './characterIntegrity.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const CLIENT_LIB = join(REPO_ROOT, 'client', 'src', 'lib', 'characterIntegrity.js');
+
+const source = readFileSync(CLIENT_LIB, 'utf8');
+
+/** Pull `export const NAME = Object.freeze([...])` string members out of the client source. */
+const mirroredList = (name) => {
+ const match = source.match(new RegExp(`export const ${name} = Object\\.freeze\\(\\[([^\\]]*)\\]`));
+ if (!match) throw new Error(`client characterIntegrity.js has no ${name} array`);
+ return [...match[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
+};
+
+/** Pull the keys of `export const NAME = Object.freeze({ key: ... })`. */
+const mirroredKeys = (name) => {
+ const start = source.indexOf(`export const ${name} = Object.freeze({`);
+ if (start < 0) throw new Error(`client characterIntegrity.js has no ${name} object`);
+ const body = source.slice(start, source.indexOf('\n});', start));
+ return [...body.matchAll(/^ {2}'?([a-zA-Z][\w-]*)'?:/gm)].map((m) => m[1]);
+};
+
+describe('characterIntegrity client mirror', () => {
+ it.each([
+ ['INTEGRITY_FINDING_KINDS', INTEGRITY_FINDING_KINDS],
+ ['AUGMENTABLE_FINDING_KINDS', AUGMENTABLE_FINDING_KINDS],
+ ['CHARACTER_REVIEW_STATUSES', CHARACTER_REVIEW_STATUSES],
+ ['INCOMPLETE_REVIEW_STATUSES', INCOMPLETE_REVIEW_STATUSES],
+ ['INTEGRITY_DEPTHS', INTEGRITY_DEPTHS],
+ ['INTEGRITY_DIMENSION_IDS', INTEGRITY_DIMENSION_IDS],
+ ])('%s matches the server list exactly, in order', (name, expected) => {
+ expect(mirroredList(name)).toEqual([...expected]);
+ });
+
+ it('has badge copy for every finding kind, review status and depth', () => {
+ expect(mirroredKeys('FINDING_KIND_META').sort()).toEqual([...INTEGRITY_FINDING_KINDS].sort());
+ expect(mirroredKeys('REVIEW_STATUS_META').sort()).toEqual([...CHARACTER_REVIEW_STATUSES].sort());
+ expect(mirroredKeys('DEPTH_META').sort()).toEqual([...INTEGRITY_DEPTHS].sort());
+ });
+
+ it('labels every dimension the server can attribute a finding to', () => {
+ expect(mirroredKeys('DIMENSION_LABELS').sort()).toEqual([...INTEGRITY_DIMENSION_IDS].sort());
+ });
+
+ it('marks exactly the augmentable kinds as repairable', () => {
+ const repairable = [...INTEGRITY_FINDING_KINDS].filter((kind) => {
+ const row = source.match(new RegExp(`\\b${kind}: Object\\.freeze\\(\\{[^}]*\\}\\)`));
+ return row ? /repairable: true/.test(row[0]) : false;
+ });
+ expect(repairable).toEqual([...AUGMENTABLE_FINDING_KINDS]);
+ });
+});
diff --git a/server/lib/characterIntegrity.test.js b/server/lib/characterIntegrity.test.js
new file mode 100644
index 0000000000..5bd58f9942
--- /dev/null
+++ b/server/lib/characterIntegrity.test.js
@@ -0,0 +1,270 @@
+/**
+ * The integrity contract's own guarantees — the ones a route or UI test would
+ * only observe indirectly, and the ones that MUST hold no matter what an LLM
+ * returns.
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ buildCastIntegrityReport,
+ castIntegrityPassed,
+ characterCompletenessFindings,
+ characterFingerprint,
+ characterIntegrityDepth,
+ characterIntegrityDimensions,
+ mergeSemanticFindings,
+ readIntegrityField,
+ withIntegrityField,
+} from './characterIntegrity.js';
+
+/** A fully authored lead — nothing for the deterministic pass to report. */
+const lead = () => ({
+ id: 'c-lead',
+ name: 'Wren Ashcombe',
+ role: 'protagonist',
+ motivations: 'Wants the survey contract renewed; fears being sent back inland.',
+ ghost: 'Her crew drowned on a run she planned.',
+ wound: 'She no longer trusts her own judgment under time pressure.',
+ lie: 'If I am the one holding the chart, nobody else dies.',
+ want: 'Sole command of the northern survey.',
+ need: 'That shared command is not the same as being replaceable.',
+ psychology: {
+ theoryOfControl: 'If I carry every decision myself, the cost lands on me instead of the crew.',
+ strategy: 'Takes the night watch alone and rewrites other people’s plans.',
+ protectiveBenefit: 'She never has to watch somebody else make the call that kills them.',
+ presentCost: 'Nobody on her crew has learned to navigate without her.',
+ testingPressure: 'A run she physically cannot take herself.',
+ candidateChange: 'Letting a second navigator sign the chart.',
+ assessment: 'assessed',
+ assessmentNote: '',
+ drives: {
+ survival: { desire: 'A berth that does not depend on weather luck.', fear: 'Being put ashore.' },
+ connection: { desire: 'A crew that stays a full season.', fear: 'Being the reason one leaves.' },
+ status: { desire: 'To be the name the harbourmaster asks for.', fear: 'Being read as lucky rather than good.' },
+ },
+ },
+});
+
+describe('characterIntegrityDepth', () => {
+ it('holds an ordinary lead to the full framework', () => {
+ expect(characterIntegrityDepth(lead())).toBe('full');
+ });
+
+ it.each([
+ ['a declared minor role', { id: 'x', role: 'minor dockhand' }],
+ ['a background player', { id: 'x', role: 'Background — market crowd' }],
+ ['a declared flat arc', { id: 'x', role: 'protagonist', arcType: 'flat' }],
+ ])('holds %s to lighter requirements', (_label, entry) => {
+ expect(characterIntegrityDepth(entry)).toBe('light');
+ });
+
+ it('does not read "extra" out of a longer word', () => {
+ expect(characterIntegrityDepth({ id: 'x', role: 'extraordinary envoy' })).toBe('full');
+ });
+
+ it('treats an EXPLAINED unknown as a finished assessment, not a gap', () => {
+ const hive = {
+ id: 'x',
+ role: 'antagonist',
+ psychology: { assessment: 'not-applicable', assessmentNote: 'A distributed fungal intelligence with no legible interior.' },
+ };
+ expect(characterIntegrityDepth(hive)).toBe('explained');
+ expect(characterCompletenessFindings(hive)).toEqual([]);
+ expect(characterIntegrityDimensions(hive)).toEqual([]);
+ });
+
+ it('still reports an UNEXPLAINED unknown — the note is what makes it an assessment', () => {
+ const findings = characterCompletenessFindings({
+ id: 'x', role: 'antagonist', psychology: { assessment: 'unknown', assessmentNote: '' },
+ });
+ expect(findings.length).toBeGreaterThan(0);
+ });
+});
+
+describe('characterCompletenessFindings', () => {
+ it('finds nothing on a fully authored lead', () => {
+ expect(characterCompletenessFindings(lead())).toEqual([]);
+ });
+
+ it('reports ONE psychology gap for an untouched character, not nine leaves', () => {
+ const findings = characterCompletenessFindings({ id: 'x', name: 'Blank', role: 'protagonist' });
+ const psych = findings.filter((f) => f.field.startsWith('psychology'));
+ expect(psych).toHaveLength(1);
+ expect(psych[0].field).toBe('psychology');
+ });
+
+ it('walks into the leaves once the profile is partly authored', () => {
+ const entry = lead();
+ entry.psychology.drives.status.fear = '';
+ entry.psychology.theoryOfControl = '';
+ const fields = characterCompletenessFindings(entry).map((f) => f.field);
+ expect(fields).toContain('psychology.theoryOfControl');
+ expect(fields).toContain('psychology.drives.status.fear');
+ expect(fields).not.toContain('psychology.drives.survival.desire');
+ });
+
+ it('asks a light-depth character only for the conscious pursuit', () => {
+ const fields = characterCompletenessFindings({ id: 'x', name: 'Dockhand', role: 'minor' }).map((f) => f.field);
+ expect(fields).toEqual(['motivations', 'want']);
+ });
+
+ it('reports every finding as `missing` — it never judges populated prose', () => {
+ const entry = lead();
+ entry.want = 'stuff';
+ expect(characterCompletenessFindings(entry)).toEqual([]);
+ });
+});
+
+describe('buildCastIntegrityReport coverage', () => {
+ const cast = [lead(), { id: 'c-2', name: 'Second', role: 'protagonist' }];
+
+ it('lists out-of-scope characters as not-reviewed rather than omitting them', () => {
+ const report = buildCastIntegrityReport(cast, { characterIds: ['c-lead'] });
+ const second = report.coverage.find((c) => c.characterId === 'c-2');
+ expect(second.status).toBe('not-reviewed');
+ expect(report.castCount).toBe(2);
+ expect(report.reviewedCount).toBe(1);
+ });
+
+ it('never counts a deterministic pass as a clean review', () => {
+ const report = buildCastIntegrityReport([lead()]);
+ expect(report.coverage[0].status).toBe('passed');
+ // Blank-complete is exactly the case this issue exists for.
+ expect(castIntegrityPassed(report)).toBe(false);
+ });
+
+ it('an empty cast is not a pass', () => {
+ expect(castIntegrityPassed(buildCastIntegrityReport([]))).toBe(false);
+ });
+});
+
+describe('mergeSemanticFindings', () => {
+ const cast = [lead(), { id: 'c-2', name: 'Second', role: 'minor' }];
+ const base = () => buildCastIntegrityReport(cast);
+
+ const semantic = (over = {}) => ({
+ characterId: 'c-lead',
+ field: 'lie',
+ kind: 'underspecified',
+ dimension: 'control-predicts-behavior',
+ evidence: 'The stated belief is about chart-holding, but the personality shows her delegating freely.',
+ suggestion: 'Name the moment she refuses to hand over the chart.',
+ ...over,
+ });
+
+ it('accepts a well-formed finding and flips the character to `findings`', () => {
+ const report = mergeSemanticFindings(base(), {
+ characters: cast, findings: [semantic()], reviewedIds: ['c-lead', 'c-2'],
+ });
+ expect(report.findings.map((f) => f.field)).toContain('lie');
+ expect(report.coverage.find((c) => c.characterId === 'c-lead').status).toBe('findings');
+ });
+
+ it.each([
+ ['an unknown character', { characterId: 'c-nope' }],
+ ['an unknown field path', { field: 'wardrobes' }],
+ ['an unknown kind', { kind: 'vibes' }],
+ ['an unknown dimension', { dimension: 'made-up' }],
+ ['no evidence', { evidence: ' ' }],
+ ])('drops a finding naming %s', (_label, over) => {
+ const report = mergeSemanticFindings(base(), {
+ characters: cast, findings: [semantic(over)], reviewedIds: ['c-lead', 'c-2'],
+ });
+ expect(report.findings.filter((f) => f.dimension)).toEqual([]);
+ });
+
+ it('drops a dimension the character’s depth excuses', () => {
+ // `c-2` is a minor role → light depth, which does not ask about origin.
+ const report = mergeSemanticFindings(base(), {
+ characters: cast,
+ findings: [semantic({ characterId: 'c-2', field: 'ghost', dimension: 'origin-supports-control' })],
+ reviewedIds: ['c-lead', 'c-2'],
+ });
+ expect(report.findings.some((f) => f.dimension === 'origin-supports-control')).toBe(false);
+ });
+
+ it('marks characters the batch never reached as truncated, not passed', () => {
+ const report = mergeSemanticFindings(base(), {
+ characters: cast, findings: [], reviewedIds: ['c-lead'], truncated: true,
+ });
+ expect(report.coverage.find((c) => c.characterId === 'c-2').status).toBe('truncated');
+ expect(castIntegrityPassed(report)).toBe(false);
+ });
+
+ it('a fully reviewed, finding-free cast is the ONLY thing that passes', () => {
+ const clean = [lead()];
+ const report = mergeSemanticFindings(buildCastIntegrityReport(clean), {
+ characters: clean, findings: [], reviewedIds: ['c-lead'],
+ });
+ expect(castIntegrityPassed(report)).toBe(true);
+ });
+
+ it('ignores findings about a character the batch did not review', () => {
+ const report = mergeSemanticFindings(base(), {
+ characters: cast, findings: [semantic()], reviewedIds: ['c-2'],
+ });
+ expect(report.findings.some((f) => f.dimension)).toBe(false);
+ });
+
+ it('keeps the deterministic finding when the model names the same field', () => {
+ const blank = [{ id: 'c-3', name: 'Blank', role: 'protagonist' }];
+ const report = mergeSemanticFindings(buildCastIntegrityReport(blank), {
+ characters: blank,
+ findings: [semantic({ characterId: 'c-3', field: 'lie', kind: 'missing', evidence: 'no lie' })],
+ reviewedIds: ['c-3'],
+ });
+ const lieFindings = report.findings.filter((f) => f.characterId === 'c-3' && f.field === 'lie');
+ expect(lieFindings).toHaveLength(1);
+ expect(lieFindings[0].dimension).toBeNull();
+ });
+});
+
+describe('fingerprints', () => {
+ it('changes when an integrity field changes', () => {
+ const before = characterFingerprint(lead());
+ const after = characterFingerprint({ ...lead(), lie: 'something else' });
+ expect(after).not.toBe(before);
+ });
+
+ it('changes when a psychology LEAF changes', () => {
+ const entry = lead();
+ const before = characterFingerprint(entry);
+ entry.psychology.drives.status.fear = 'different';
+ expect(characterFingerprint(entry)).not.toBe(before);
+ });
+
+ it('does NOT change on an unrelated edit — a re-render must not stale a review', () => {
+ const before = characterFingerprint(lead());
+ expect(characterFingerprint({ ...lead(), wardrobes: [{ name: 'coat', description: 'x' }], voiceId: 'v1' }))
+ .toBe(before);
+ });
+
+ it('cannot be forged by a delimiter inside an authored field', () => {
+ const a = characterFingerprint({ ...lead(), lie: 'a|b', want: 'c' });
+ const b = characterFingerprint({ ...lead(), lie: 'a', want: 'b|c' });
+ expect(a).not.toBe(b);
+ });
+});
+
+describe('integrity field paths', () => {
+ it('reads and writes a psychology drive leaf without clobbering its siblings', () => {
+ const entry = lead();
+ const next = withIntegrityField(entry, 'psychology.drives.status.fear', 'Being called lucky.');
+ expect(readIntegrityField(next, 'psychology.drives.status.fear')).toBe('Being called lucky.');
+ expect(next.psychology.drives.status.desire).toBe(entry.psychology.drives.status.desire);
+ expect(next.psychology.drives.survival.fear).toBe(entry.psychology.drives.survival.fear);
+ expect(next.psychology.theoryOfControl).toBe(entry.psychology.theoryOfControl);
+ });
+
+ it('materializes the psychology container on a character that has none', () => {
+ const next = withIntegrityField({ id: 'x' }, 'psychology.theoryOfControl', 'rule');
+ expect(next.psychology.theoryOfControl).toBe('rule');
+ });
+
+ it('refuses a path outside the contract rather than writing it', () => {
+ const entry = { id: 'x' };
+ expect(withIntegrityField(entry, 'physicalDescription', 'nope')).toBe(entry);
+ expect(readIntegrityField({ physicalDescription: 'a' }, 'physicalDescription')).toBe('');
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 79d5b793f0..cfa3819f7a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -117,6 +117,7 @@ export * from './bibleLimits.js';
// re-exports CHARACTER_ARC_TYPES from here, so keep this flat export ahead of
// the namespaced storyBible below.
export * from './characterFramework.js';
+export * from './characterIntegrity.js';
// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for
// back-compat — namespace it so the canonical scenePrompt export wins flat.
export * as storyBible from './storyBible.js';
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index ed8260573b..d0733b06c4 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -433,6 +433,12 @@
"server/services/universeCanon.js",
"server/services/universeCanonEntryExpand.js"
],
+ "universe-cast-integrity-review": [
+ "server/services/universeCastIntegrity.js"
+ ],
+ "universe-character-augment": [
+ "server/services/universeCastIntegrity.js"
+ ],
"universe-character-expand": [
"server/services/universeCharacterExpand.js"
],
diff --git a/server/routes/universeBuilder/canon.js b/server/routes/universeBuilder/canon.js
index 1e546f11ea..aa93810ea0 100644
--- a/server/routes/universeBuilder/canon.js
+++ b/server/routes/universeBuilder/canon.js
@@ -13,6 +13,13 @@ import { asyncHandler } from '../../lib/errorHandler.js';
import { validateRequest } from '../../lib/validation.js';
import * as canonSvc from '../../services/universeCanon.js';
import { expandUniverseCharacter } from '../../services/universeCharacterExpand.js';
+import {
+ getUniverseCastIntegrity,
+ reviewUniverseCast,
+ proposeCharacterAugmentation,
+ applyCharacterAugmentation,
+} from '../../services/universeCastIntegrity.js';
+import { AUGMENTABLE_FIELD_PATHS } from '../../lib/characterIntegrity.js';
import { getUniverseCanonUsage, listLinkedSeriesNames } from '../../services/canonUsage.js';
import { mapServiceError, lockParamsSchema } from './shared.js';
@@ -58,6 +65,68 @@ router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) =>
res.json(result);
}));
+// ── Cast integrity (#6415) ───────────────────────────────────────────────
+// Character ids the caller wants scoped. Omitted entirely = the whole cast;
+// an explicit `[]` is an empty selection and reviews nobody. The two are
+// deliberately different answers, so the schema must not default it to [].
+const castScopeSchema = z.object({
+ characterIds: z.array(z.string().trim().min(1).max(120)).max(500).optional(),
+ providerId: z.string().trim().max(64).optional(),
+ model: z.string().trim().max(128).optional(),
+});
+
+// DETERMINISTIC integrity report — no provider call, safe on page load. Also
+// returns `reviewScope` (provider / model / batch size) so the UI can name what
+// a semantic review would spend BEFORE the user opts into it.
+router.get('/:id/characters/integrity', asyncHandler(async (req, res) => {
+ const characterIds = typeof req.query.characterIds === 'string' && req.query.characterIds.trim()
+ ? req.query.characterIds.split(',').map((s) => s.trim()).filter(Boolean)
+ : undefined;
+ const result = await getUniverseCastIntegrity(req.params.id, { characterIds })
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+// SEMANTIC review — one bounded LLM call, explicit user action only. Characters
+// past the batch cap come back `truncated`, never silently passed.
+router.post('/:id/characters/integrity/review', asyncHandler(async (req, res) => {
+ const body = validateRequest(castScopeSchema, req.body ?? {});
+ const result = await reviewUniverseCast(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+// Propose sharper values for POPULATED fields. Writes NOTHING — returns
+// before/after per field for the author to accept individually.
+const augmentProposeSchema = z.object({
+ fields: z.array(z.enum(AUGMENTABLE_FIELD_PATHS)).min(1).max(AUGMENTABLE_FIELD_PATHS.length),
+ providerId: z.string().trim().max(64).optional(),
+ model: z.string().trim().max(128).optional(),
+});
+router.post('/:id/characters/:entryId/augment', asyncHandler(async (req, res) => {
+ const body = validateRequest(augmentProposeSchema, req.body ?? {});
+ const result = await proposeCharacterAugmentation(req.params.id, req.params.entryId, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+// Apply only the proposals the author accepted. `fingerprint` is the character
+// state the preview was reviewed against — a mismatch is a 409, not a silent
+// overwrite of whatever was edited in the meantime.
+const augmentApplySchema = z.object({
+ fields: z.array(z.object({
+ field: z.enum(AUGMENTABLE_FIELD_PATHS),
+ value: z.string().trim().min(1).max(4000),
+ })).min(1).max(AUGMENTABLE_FIELD_PATHS.length),
+ fingerprint: z.string().max(20000).optional(),
+});
+router.post('/:id/characters/:entryId/augment/apply', asyncHandler(async (req, res) => {
+ const body = validateRequest(augmentApplySchema, req.body ?? {});
+ const result = await applyCharacterAugmentation(req.params.id, req.params.entryId, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Cast-wide differentiate — one LLM call rewrites every character so the
// cast as a whole has no visually-colliding pairs. Returns counts + the
// updated universe.
diff --git a/server/routes/universeBuilder/castIntegrity.test.js b/server/routes/universeBuilder/castIntegrity.test.js
new file mode 100644
index 0000000000..d3c345c7b5
--- /dev/null
+++ b/server/routes/universeBuilder/castIntegrity.test.js
@@ -0,0 +1,338 @@
+/**
+ * Route → Zod → service → store round trip for the cast-integrity endpoints (#6415).
+ *
+ * Only the PROVIDER boundary is stubbed (`runPromptRefineRaw` /
+ * `resolveStageContext`) — everything else is the real router, the real
+ * schemas, the real merge and the real contract. `updateUniverse` is a faithful
+ * stand-in that actually applies the mutator against a mutable universe, so the
+ * inside-the-write-queue lock / staleness re-checks are genuinely exercised
+ * rather than asserted against a mock's arguments.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../../lib/testHelper.js';
+import { errorMiddleware } from '../../lib/errorHandler.js';
+
+let universe;
+
+const getUniverseMock = vi.fn(async () => universe);
+// Mirrors the real contract: the mutator receives the FRESHEST record and
+// returns either a patch or null (no write).
+const updateUniverseMock = vi.fn(async (_id, mutate) => {
+ const patch = mutate(universe);
+ if (!patch) return null;
+ universe = { ...universe, ...patch };
+ return universe;
+});
+vi.mock('../../services/universeBuilder.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getUniverse: (...args) => getUniverseMock(...args),
+ updateUniverse: (...args) => updateUniverseMock(...args),
+}));
+
+const refineRawMock = vi.fn();
+vi.mock('../../services/pipeline/refineHelpers.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ runPromptRefineRaw: (...args) => refineRawMock(...args),
+}));
+
+const resolveStageContextMock = vi.fn(async () => ({
+ provider: { id: 'prov-1', name: 'Local Llama' },
+ model: 'llama-3.3',
+ contextWindow: 32000,
+}));
+vi.mock('../../services/stageRunner.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ resolveStageContext: (...args) => resolveStageContextMock(...args),
+}));
+
+const { default: universeBuilderRoutes } = await import('./index.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json({ limit: '55mb' }));
+ app.use('/api/universe-builder', universeBuilderRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const lead = () => ({
+ id: 'c-lead',
+ name: 'Wren',
+ role: 'protagonist',
+ motivations: 'Wants the survey contract renewed.',
+ ghost: 'Her crew drowned on a run she planned.',
+ wound: 'She no longer trusts her judgment under pressure.',
+ lie: 'If I hold the chart, nobody else dies.',
+ want: 'Sole command of the northern survey.',
+ need: 'Shared command is not the same as being replaceable.',
+ psychology: {
+ theoryOfControl: 'If I carry every decision, the cost lands on me.',
+ strategy: 'Takes the night watch alone.',
+ protectiveBenefit: 'She never watches somebody else make the fatal call.',
+ presentCost: 'Nobody on her crew can navigate without her.',
+ testingPressure: 'A run she cannot take herself.',
+ candidateChange: 'Letting a second navigator sign the chart.',
+ assessment: 'assessed',
+ assessmentNote: '',
+ drives: {
+ survival: { desire: 'A steady berth.', fear: 'Being put ashore.' },
+ connection: { desire: 'A crew that stays.', fear: 'Being why one leaves.' },
+ status: { desire: 'To be the name asked for.', fear: 'Being read as lucky.' },
+ },
+ },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ resolveStageContextMock.mockResolvedValue({
+ provider: { id: 'prov-1', name: 'Local Llama' }, model: 'llama-3.3', contextWindow: 32000,
+ });
+ universe = {
+ id: 'u-1',
+ characters: [lead(), { id: 'c-2', name: 'Dockhand', role: 'minor' }],
+ places: [],
+ objects: [],
+ };
+});
+
+describe('GET /:id/characters/integrity — the deterministic pass', () => {
+ it('reports the free completeness pass and spends NOTHING on a provider', async () => {
+ const res = await request(makeApp()).get('/api/universe-builder/u-1/characters/integrity');
+ expect(res.status).toBe(200);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ expect(res.body.castCount).toBe(2);
+ expect(res.body.coverage.map((c) => c.characterId)).toEqual(['c-lead', 'c-2']);
+ // Blank-complete is not a semantic pass.
+ expect(res.body.semanticReviewedCount).toBe(0);
+ });
+
+ it('names the provider, model and batch size a review WOULD spend', async () => {
+ const res = await request(makeApp()).get('/api/universe-builder/u-1/characters/integrity');
+ expect(res.body.reviewScope).toMatchObject({
+ providerId: 'prov-1', providerName: 'Local Llama', model: 'llama-3.3', characterCount: 2,
+ });
+ });
+
+ it('still renders the report when no provider can be resolved', async () => {
+ resolveStageContextMock.mockRejectedValue(new Error('no provider configured'));
+ const res = await request(makeApp()).get('/api/universe-builder/u-1/characters/integrity');
+ expect(res.status).toBe(200);
+ expect(res.body.reviewScope.providerId).toBeNull();
+ expect(res.body.coverage).toHaveLength(2);
+ });
+
+ it('lists characters outside an explicit scope as not-reviewed, never omitted', async () => {
+ const res = await request(makeApp())
+ .get('/api/universe-builder/u-1/characters/integrity?characterIds=c-lead');
+ expect(res.body.coverage.find((c) => c.characterId === 'c-2').status).toBe('not-reviewed');
+ expect(res.body.reviewedCount).toBe(1);
+ });
+
+ it('holds the minor role to lighter requirements', async () => {
+ const res = await request(makeApp()).get('/api/universe-builder/u-1/characters/integrity');
+ const dockhand = res.body.coverage.find((c) => c.characterId === 'c-2');
+ expect(dockhand.depth).toBe('light');
+ const fields = res.body.findings.filter((f) => f.characterId === 'c-2').map((f) => f.field);
+ expect(fields).toEqual(['motivations', 'want']);
+ });
+});
+
+describe('POST /:id/characters/integrity/review — the semantic pass', () => {
+ const reviewResponse = (findings) => ({
+ content: { findings }, rationale: 'ok', runId: 'run-1', providerId: 'prov-1', model: 'llama-3.3',
+ });
+
+ it('merges a well-formed finding and marks the character reviewed', async () => {
+ refineRawMock.mockResolvedValue(reviewResponse([{
+ characterId: 'c-lead',
+ field: 'psychology.drives.status.fear',
+ kind: 'underspecified',
+ dimension: 'drives-specific',
+ evidence: 'The status fear restates the survival fear.',
+ suggestion: 'Name the specific standing she loses.',
+ }]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/integrity/review').send({});
+ expect(res.status).toBe(200);
+ const lead = res.body.coverage.find((c) => c.characterId === 'c-lead');
+ expect(lead.status).toBe('findings');
+ expect(lead.semanticReviewed).toBe(true);
+ expect(res.body.findings.some((f) => f.field === 'psychology.drives.status.fear')).toBe(true);
+ });
+
+ it('drops a finding that names a character outside the cast', async () => {
+ refineRawMock.mockResolvedValue(reviewResponse([{
+ characterId: 'c-does-not-exist', field: 'lie', kind: 'contradictory', evidence: 'x',
+ }]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/integrity/review').send({});
+ expect(res.body.findings.some((f) => f.characterId === 'c-does-not-exist')).toBe(false);
+ });
+
+ it('drops a finding on a field path outside the contract', async () => {
+ refineRawMock.mockResolvedValue(reviewResponse([{
+ characterId: 'c-lead', field: 'physicalDescription', kind: 'underspecified', evidence: 'x',
+ }]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/integrity/review').send({});
+ expect(res.body.findings.some((f) => f.field === 'physicalDescription')).toBe(false);
+ });
+
+ it('400s on an empty explicit selection rather than reviewing the whole cast', async () => {
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/integrity/review').send({ characterIds: [] });
+ expect(res.status).toBe(400);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+
+ it('sends the model only the characters in scope', async () => {
+ refineRawMock.mockResolvedValue(reviewResponse([]));
+ await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/integrity/review').send({ characterIds: ['c-2'] });
+ const cast = JSON.parse(refineRawMock.mock.calls[0][0].variables.castJson);
+ expect(cast.map((c) => c.id)).toEqual(['c-2']);
+ });
+});
+
+describe('POST /:id/characters/:entryId/augment — propose', () => {
+ const proposalResponse = (proposals) => ({
+ content: { proposals }, rationale: 'ok', runId: 'run-2', providerId: 'prov-1', model: 'llama-3.3',
+ });
+
+ it('returns before/after and writes NOTHING', async () => {
+ refineRawMock.mockResolvedValue(proposalResponse([
+ { field: 'lie', value: 'If I am the only one who signs the chart, no one else carries a death.', rationale: 'names the act' },
+ ]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment').send({ fields: ['lie'] });
+ expect(res.status).toBe(200);
+ expect(res.body.proposals[0]).toMatchObject({ field: 'lie', before: 'If I hold the chart, nobody else dies.' });
+ expect(res.body.fingerprint).toEqual(expect.any(String));
+ expect(updateUniverseMock).not.toHaveBeenCalled();
+ expect(universe.characters[0].lie).toBe('If I hold the chart, nobody else dies.');
+ });
+
+ it('drops a proposal for a field the user did not request', async () => {
+ refineRawMock.mockResolvedValue(proposalResponse([
+ { field: 'lie', value: 'sharper lie' },
+ { field: 'want', value: 'an unrequested rewrite' },
+ ]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment').send({ fields: ['lie'] });
+ expect(res.body.proposals.map((p) => p.field)).toEqual(['lie']);
+ });
+
+ it('drops a proposal identical to the current value', async () => {
+ refineRawMock.mockResolvedValue(proposalResponse([
+ { field: 'lie', value: 'If I hold the chart, nobody else dies.' },
+ ]));
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment').send({ fields: ['lie'] });
+ expect(res.body.proposals).toEqual([]);
+ });
+
+ it('rejects a field path outside the contract at the schema, before any call', async () => {
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment').send({ fields: ['physicalDescription'] });
+ expect(res.status).toBe(400);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+
+ it('skips the provider entirely for a locked character', async () => {
+ universe.characters[0].locked = true;
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment').send({ fields: ['lie'] });
+ expect(res.body.locked).toBe(true);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+
+ it('404s on a character that is not in the universe', async () => {
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-ghost/augment').send({ fields: ['lie'] });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe('POST /:id/characters/:entryId/augment/apply — selective apply', () => {
+ // The fingerprint comes from a real propose call, which is the only way a
+ // client ever obtains one.
+ const fingerprintFor = async (id = 'c-lead') => {
+ refineRawMock.mockResolvedValue({
+ content: { proposals: [{ field: 'lie', value: 'A sharper lie.' }] },
+ rationale: '', runId: 'run-3', providerId: 'prov-1', model: 'llama-3.3',
+ });
+ const res = await request(makeApp())
+ .post(`/api/universe-builder/u-1/characters/${id}/augment`).send({ fields: ['lie'] });
+ return res.body.fingerprint;
+ };
+
+ it('applies ONLY the selected field and leaves the rest untouched', async () => {
+ const fingerprint = await fingerprintFor();
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.status).toBe(200);
+ expect(res.body.appliedFields).toEqual(['lie']);
+ expect(universe.characters[0].lie).toBe('A sharper lie.');
+ expect(universe.characters[0].want).toBe('Sole command of the northern survey.');
+ });
+
+ it('writes a psychology leaf without dropping its siblings', async () => {
+ const fingerprint = await fingerprintFor();
+ await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'psychology.drives.status.fear', value: 'Being thanked instead of hired.' }], fingerprint });
+ const { psychology } = universe.characters[0];
+ expect(psychology.drives.status.fear).toBe('Being thanked instead of hired.');
+ expect(psychology.drives.status.desire).toBe('To be the name asked for.');
+ expect(psychology.theoryOfControl).toBe('If I carry every decision, the cost lands on me.');
+ });
+
+ it('409s instead of clobbering a character edited since the proposal', async () => {
+ const fingerprint = await fingerprintFor();
+ universe.characters[0].lie = 'the author rewrote this by hand';
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'lie', value: 'the model version' }], fingerprint });
+ expect(res.status).toBe(409);
+ expect(universe.characters[0].lie).toBe('the author rewrote this by hand');
+ });
+
+ it('does not go stale on an edit to an UNRELATED field', async () => {
+ const fingerprint = await fingerprintFor();
+ universe.characters[0].physicalDescription = 'a newly rendered description';
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.status).toBe(200);
+ });
+
+ it('refuses a character locked between the proposal and the apply', async () => {
+ const fingerprint = await fingerprintFor();
+ universe.characters[0].locked = true;
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.body.locked).toBe(true);
+ expect(universe.characters[0].lie).toBe('If I hold the chart, nobody else dies.');
+ });
+
+ it('404s when the character was deleted between the proposal and the apply', async () => {
+ const fingerprint = await fingerprintFor();
+ universe.characters = universe.characters.filter((c) => c.id !== 'c-lead');
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.status).toBe(404);
+ });
+
+ it('rejects an out-of-contract field path at the schema', async () => {
+ const res = await request(makeApp())
+ .post('/api/universe-builder/u-1/characters/c-lead/augment/apply')
+ .send({ fields: [{ field: 'wardrobes', value: 'x' }] });
+ expect(res.status).toBe(400);
+ expect(updateUniverseMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/universeCastIntegrity.js b/server/services/universeCastIntegrity.js
new file mode 100644
index 0000000000..ba75998611
--- /dev/null
+++ b/server/services/universeCastIntegrity.js
@@ -0,0 +1,333 @@
+/**
+ * Universe cast integrity — the review and repair half of #6415.
+ *
+ * Three operations over one contract (`server/lib/characterIntegrity.js`):
+ *
+ * 1. `getUniverseCastIntegrity` — the DETERMINISTIC pass. Zero provider
+ * calls, so a page load may run it. It also reports the `reviewScope`:
+ * the provider, model and character count a semantic review WOULD spend,
+ * resolved without executing anything, so the UI can name the cost before
+ * the user opts in (AGENTS.md: no cold-bootstrap LLM calls).
+ * 2. `reviewUniverseCast` — the SEMANTIC pass, only ever from an explicit
+ * user action. One call per batch; the model's findings are validated back
+ * into the contract, and characters the batch didn't reach are reported
+ * `truncated` rather than silently passing.
+ * 3. `proposeCharacterAugmentation` / `applyCharacterAugmentation` — the
+ * augment-POPULATED-fields action the existing expand deliberately can't
+ * do. Propose writes NOTHING and returns before/after per field; apply
+ * takes back only the paths the user selected.
+ *
+ * Reports are derived, never stored, so "invalidate stale reports on relevant
+ * edits" is a fingerprint comparison rather than a cache: `applyCharacterAugmentation`
+ * refuses a proposal whose character changed underneath it (409), the same way
+ * the expand runner re-derives its merge inside the write queue.
+ */
+
+import { getUniverse, updateUniverse } from './universeBuilder.js';
+import { runPromptRefineRaw } from './pipeline/refineHelpers.js';
+import { resolveStageContext } from './stageRunner.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { sanitizeBibleField } from '../lib/storyBible.js';
+import { shortId } from '../lib/fileUtils.js';
+import {
+ INTEGRITY_DIMENSIONS,
+ buildCastIntegrityReport,
+ characterFingerprint,
+ characterIntegrityDepth,
+ characterIntegrityDimensions,
+ isAugmentableFieldPath,
+ mergeSemanticFindings,
+ readIntegrityField,
+ withIntegrityField,
+} from '../lib/characterIntegrity.js';
+
+const REVIEW_STAGE = 'universe-cast-integrity-review';
+const AUGMENT_STAGE = 'universe-character-augment';
+
+/**
+ * How many characters one semantic review call covers. A cast larger than this
+ * is reviewed in a bounded batch and the remainder is reported `truncated` —
+ * the alternative (silently fanning out N provider calls from one click) is
+ * exactly the runaway spend AGENTS.md forbids.
+ */
+export const CAST_REVIEW_BATCH_MAX = 12;
+
+const notFound = (entryId) => new ServerError(`Character ${entryId} not found in universe`, {
+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',
+});
+
+const castOf = (universe) => (Array.isArray(universe?.characters) ? universe.characters.filter((c) => c?.id) : []);
+
+/** The character record the review prompt sees — framework + the fields the dimensions judge against. */
+const characterForReview = (entry) => ({
+ id: entry.id,
+ name: entry.name || '',
+ role: entry.role || '',
+ arcType: entry.arcType || null,
+ depth: characterIntegrityDepth(entry),
+ dimensions: characterIntegrityDimensions(entry),
+ motivations: entry.motivations || '',
+ ghost: entry.ghost || '',
+ wound: entry.wound || '',
+ lie: entry.lie || '',
+ want: entry.want || '',
+ need: entry.need || '',
+ personality: entry.personality || '',
+ background: entry.background || '',
+ secrets: Array.isArray(entry.secrets) ? entry.secrets : [],
+ psychology: entry.psychology || null,
+ relationshipLinks: (Array.isArray(entry.relationshipLinks) ? entry.relationshipLinks : []).map((l) => ({
+ targetCharacterId: l?.targetCharacterId || '',
+ type: l?.type || 'custom',
+ description: l?.description || '',
+ })),
+});
+
+/**
+ * Ids the caller asked about, narrowed to ids that actually exist. `null` (the
+ * default) means the whole cast — distinct from `[]`, which is an explicit
+ * empty selection and reviews nobody.
+ */
+const resolveScopeIds = (cast, characterIds) => {
+ if (!Array.isArray(characterIds)) return cast.map((c) => c.id);
+ const live = new Set(cast.map((c) => c.id));
+ return characterIds.filter((id) => live.has(id));
+};
+
+/**
+ * The deterministic report plus the cost of the semantic review that would
+ * follow. Makes NO provider call: `resolveStageContext` only resolves which
+ * provider/model the stage would use.
+ */
+export async function getUniverseCastIntegrity(universeId, { characterIds = null } = {}) {
+ const universe = await getUniverse(universeId);
+ const cast = castOf(universe);
+ const scopeIds = resolveScopeIds(cast, characterIds);
+ const report = buildCastIntegrityReport(cast, { characterIds: scopeIds });
+
+ // Best-effort: a universe with no provider configured yet must still be able
+ // to render its deterministic report, so a resolution failure degrades to an
+ // unnamed scope rather than failing the whole request.
+ const resolved = await resolveStageContext(REVIEW_STAGE).catch(() => null);
+
+ return {
+ ...report,
+ reviewScope: {
+ characterIds: scopeIds.slice(0, CAST_REVIEW_BATCH_MAX),
+ characterCount: Math.min(scopeIds.length, CAST_REVIEW_BATCH_MAX),
+ // What the batch cap leaves for a second pass — surfaced so "review the
+ // cast" never looks like it covered more than it did.
+ remainingCount: Math.max(scopeIds.length - CAST_REVIEW_BATCH_MAX, 0),
+ batchMax: CAST_REVIEW_BATCH_MAX,
+ providerId: resolved?.provider?.id || null,
+ providerName: resolved?.provider?.name || null,
+ model: resolved?.model || null,
+ },
+ };
+}
+
+/**
+ * Run the semantic review over a bounded batch. Explicit user action only.
+ */
+export async function reviewUniverseCast(universeId, { characterIds = null, providerId, model } = {}) {
+ const universe = await getUniverse(universeId);
+ const cast = castOf(universe);
+ const scopeIds = resolveScopeIds(cast, characterIds);
+ if (scopeIds.length === 0) {
+ throw new ServerError('No characters selected for review', {
+ status: 400, code: 'UNIVERSE_CAST_REVIEW_EMPTY',
+ });
+ }
+ const batchIds = scopeIds.slice(0, CAST_REVIEW_BATCH_MAX);
+ const truncated = scopeIds.length > batchIds.length;
+ const batch = cast.filter((c) => batchIds.includes(c.id));
+
+ const { content, rationale, runId, providerId: usedProvider, model: usedModel } = await runPromptRefineRaw({
+ templateName: REVIEW_STAGE,
+ variables: {
+ castJson: JSON.stringify(batch.map(characterForReview), null, 2),
+ dimensionsJson: JSON.stringify(INTEGRITY_DIMENSIONS, null, 2),
+ },
+ options: { providerId, model },
+ source: REVIEW_STAGE,
+ logTag: null,
+ emptyError: {
+ code: 'UNIVERSE_CAST_REVIEW_EMPTY_RESPONSE',
+ message: 'LLM returned an empty cast integrity review',
+ },
+ });
+
+ const base = buildCastIntegrityReport(cast, { characterIds: scopeIds });
+ const report = mergeSemanticFindings(base, {
+ characters: cast,
+ findings: Array.isArray(content.findings) ? content.findings : [],
+ reviewedIds: batchIds,
+ truncated,
+ });
+ console.log(`🧭 Cast integrity review — universe=${shortId(universeId)} reviewed=${batchIds.length} findings=${report.findings.length} runId=${shortId(runId)}`);
+ return {
+ ...report,
+ rationale,
+ runId,
+ truncated,
+ reviewScope: {
+ characterIds: batchIds,
+ characterCount: batchIds.length,
+ remainingCount: scopeIds.length - batchIds.length,
+ batchMax: CAST_REVIEW_BATCH_MAX,
+ providerId: usedProvider || null,
+ providerName: null,
+ model: usedModel || null,
+ },
+ };
+}
+
+/** Field paths the caller may ask to augment, narrowed to string-valued integrity paths. */
+const resolveAugmentPaths = (fields) => {
+ const requested = Array.isArray(fields) ? fields : [];
+ return [...new Set(requested.filter((f) => typeof f === 'string' && isAugmentableFieldPath(f)))];
+};
+
+/**
+ * Propose sharper values for POPULATED fields. Writes nothing — the whole point
+ * is that the author sees before/after and applies only what they accept ("AI
+ * proposals are not automatically verified canon").
+ */
+export async function proposeCharacterAugmentation(universeId, entryId, {
+ fields, providerId, model,
+} = {}) {
+ const universe = await getUniverse(universeId);
+ const cast = castOf(universe);
+ const target = cast.find((c) => c.id === entryId);
+ if (!target) throw notFound(entryId);
+ if (target.locked === true) return { locked: true, entry: target, proposals: [] };
+
+ const paths = resolveAugmentPaths(fields);
+ if (paths.length === 0) {
+ throw new ServerError('No augmentable fields requested', {
+ status: 400, code: 'UNIVERSE_CHARACTER_AUGMENT_NO_FIELDS',
+ });
+ }
+
+ const { content, rationale, runId, providerId: usedProvider, model: usedModel } = await runPromptRefineRaw({
+ templateName: AUGMENT_STAGE,
+ variables: {
+ characterJson: JSON.stringify(characterForReview(target), null, 2),
+ fieldsJson: JSON.stringify(paths.map((path) => ({ field: path, current: readIntegrityField(target, path) })), null, 2),
+ peersJson: JSON.stringify(
+ cast.filter((c) => c.id !== entryId).map((c) => ({ id: c.id, name: c.name, role: c.role || '' })),
+ ),
+ },
+ options: { providerId, model },
+ source: AUGMENT_STAGE,
+ logTag: null,
+ emptyError: {
+ code: 'UNIVERSE_CHARACTER_AUGMENT_EMPTY',
+ message: 'LLM returned an empty augmentation',
+ },
+ });
+
+ const requested = new Set(paths);
+ const seen = new Set();
+ const proposals = [];
+ for (const raw of Array.isArray(content.proposals) ? content.proposals : []) {
+ const field = typeof raw?.field === 'string' ? raw.field.trim() : '';
+ // Only fields the user asked about, once each — a model that volunteers a
+ // rewrite of an unrequested field would otherwise smuggle it into a preview
+ // the author is about to bulk-accept.
+ if (!requested.has(field) || seen.has(field)) continue;
+ const after = typeof raw.value === 'string' ? raw.value.trim() : '';
+ const before = readIntegrityField(target, field);
+ if (!after || after === before) continue;
+ seen.add(field);
+ proposals.push({
+ field,
+ before,
+ after,
+ rationale: typeof raw.rationale === 'string' ? raw.rationale.trim() : '',
+ });
+ }
+
+ return {
+ entry: target,
+ proposals,
+ // The author reviews against THIS version of the character; apply refuses
+ // if it moved on. Returned rather than stored, so there is no proposal
+ // record to garbage-collect.
+ fingerprint: characterFingerprint(target),
+ rationale,
+ runId,
+ providerId: usedProvider || null,
+ model: usedModel || null,
+ };
+}
+
+/**
+ * Apply the subset of a proposal the author accepted.
+ *
+ * Refuses — rather than silently overwriting — when the character was locked,
+ * deleted, or edited since the proposal was generated. All three are checked
+ * INSIDE the write queue against the freshest record, for the same reason the
+ * expand runner re-derives its merge there.
+ */
+export async function applyCharacterAugmentation(universeId, entryId, { fields = [], fingerprint } = {}) {
+ const accepted = (Array.isArray(fields) ? fields : [])
+ .filter((f) => typeof f?.field === 'string' && isAugmentableFieldPath(f.field) && typeof f.value === 'string' && f.value.trim());
+ if (accepted.length === 0) {
+ throw new ServerError('No fields selected to apply', {
+ status: 400, code: 'UNIVERSE_CHARACTER_AUGMENT_NO_SELECTION',
+ });
+ }
+
+ let outcome = { locked: false, stale: false, missing: false, appliedFields: [] };
+ const updated = await updateUniverse(universeId, (latest) => {
+ const list = Array.isArray(latest.characters) ? latest.characters : [];
+ const idx = list.findIndex((c) => c.id === entryId);
+ if (idx < 0) {
+ outcome = { ...outcome, missing: true };
+ return null;
+ }
+ const current = list[idx];
+ if (current.locked === true) {
+ outcome = { ...outcome, locked: true };
+ return null;
+ }
+ if (fingerprint && characterFingerprint(current) !== fingerprint) {
+ outcome = { ...outcome, stale: true };
+ return null;
+ }
+ let next = current;
+ const appliedFields = [];
+ for (const { field, value } of accepted) {
+ next = withIntegrityField(next, field, value.trim());
+ appliedFields.push(field);
+ }
+ // Re-sanitize the touched containers so caps/enums are enforced on values
+ // that came back from a model and then round-tripped through the client.
+ const psychology = sanitizeBibleField('character', current, 'psychology', next.psychology);
+ next = psychology ? { ...next, psychology } : next;
+ for (const field of new Set(appliedFields.filter((f) => !f.includes('.')))) {
+ next = { ...next, [field]: sanitizeBibleField('character', current, field, next[field]) };
+ }
+ outcome = { ...outcome, appliedFields };
+ return { characters: list.map((c, i) => (i === idx ? next : c)) };
+ });
+
+ if (outcome.missing) throw notFound(entryId);
+ if (outcome.stale) {
+ throw new ServerError(
+ 'This character changed since the proposal was generated — re-run the review and try again.',
+ { status: 409, code: 'UNIVERSE_CHARACTER_AUGMENT_STALE' },
+ );
+ }
+ const universe = updated || await getUniverse(universeId);
+ const entry = castOf(universe).find((c) => c.id === entryId) || null;
+ if (outcome.locked) return { locked: true, entry, universe, appliedFields: [] };
+ console.log(`🩹 Character augment applied — universe=${shortId(universeId)} entry=${shortId(entryId)} fields=${outcome.appliedFields.length}`);
+ return {
+ universe,
+ entry,
+ appliedFields: outcome.appliedFields,
+ fingerprint: entry ? characterFingerprint(entry) : null,
+ };
+}