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: sharpen Writers Room cast fields in place with the shared augmentation contract (#6417)

[._.]/ Adam Eivy994f8419082d
diff --git a/client/src/components/castIntegrity/AugmentPreview.jsx b/client/src/components/castIntegrity/AugmentPreview.jsx
new file mode 100644
index 0000000000..e5e3413918
--- /dev/null
+++ b/client/src/components/castIntegrity/AugmentPreview.jsx
@@ -0,0 +1,68 @@
+import { Check, Loader2 } from 'lucide-react';
+import { humanizeIntegrityField } from '../../lib/characterIntegrity';
+
+/**
+ * The before/after review block for a character-augmentation proposal
+ * (#6415 / #6417), shared by the Universe cast panel and the Writers Room
+ * synced review's Cast pane.
+ *
+ * The rule this renders — and the reason it is one component rather than two —
+ * is that a proposal is applied ONE TICKED FIELD AT A TIME. Both columns are
+ * always shown, so the author is deciding against what is currently written
+ * rather than against a blank; an empty `before` says "(empty)" out loud rather
+ * than rendering as an ambiguous gap. `Apply` stays disabled until something is
+ * ticked, so a model's rewrite can never land by momentum.
+ *
+ * Purely presentational: the propose/apply calls and their state live in
+ * `hooks/useCharacterAugmentation.js`.
+ */
+export default function AugmentPreview({
+ preview, accepted, applying, onToggleField, onDiscard, onApply, idPrefix = 'augment',
+}) {
+ if (!preview) return null;
+ return (
+ <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 = `${idPrefix}-${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={() => onToggleField(p.field)}
+ className="accent-port-accent"
+ />
+ <span className="font-mono text-[11px]">{humanizeIntegrityField(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={onDiscard} className="px-2 py-1 text-xs text-gray-400 hover:text-white">
+ Discard
+ </button>
+ <button
+ type="button"
+ onClick={onApply}
+ 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>
+ );
+}
diff --git a/client/src/components/universe/CastIntegrityPanel.jsx b/client/src/components/universe/CastIntegrityPanel.jsx
index 070b6ecc82..eb2a68ba42 100644
--- a/client/src/components/universe/CastIntegrityPanel.jsx
+++ b/client/src/components/universe/CastIntegrityPanel.jsx
@@ -20,10 +20,12 @@
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { Loader2, ShieldCheck, Sparkles, X, Check } from 'lucide-react';
+import { Loader2, ShieldCheck, Sparkles, X } from 'lucide-react';
import Modal from '../ui/Modal';
import toast from '../ui/Toast';
import useMounted from '../../hooks/useMounted';
+import useCharacterAugmentation from '../../hooks/useCharacterAugmentation';
+import AugmentPreview from '../castIntegrity/AugmentPreview';
import {
getUniverseCastIntegrity,
reviewUniverseCastIntegrity,
@@ -64,11 +66,36 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver
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);
+
+ // The propose → tick → apply loop itself is shared with Writers Room; this
+ // panel supplies only the two universe-scoped requests and what to do after.
+ const {
+ preview, accepted, proposing, applying, toggleField, discard: discardAugment, runPropose, runApply,
+ } = useCharacterAugmentation({
+ propose: useCallback(
+ (characterId, fields) => proposeCharacterAugmentation(universeId, characterId, { fields }, { silent: true }),
+ [universeId],
+ ),
+ apply: useCallback(
+ (characterId, body) => applyCharacterAugmentation(universeId, characterId, body, { silent: true }),
+ [universeId],
+ ),
+ onApplied: useCallback((result, applied) => {
+ if (result.universe) onUniverseChange?.(result.universe);
+ 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 === applied.characterId ? { ...c, status: 'stale', semanticReviewed: false } : c
+ )),
+ } : prev));
+ }, [onUniverseChange]),
+ });
const load = useCallback(async () => {
setLoading(true);
@@ -79,9 +106,9 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver
if (result) {
setReport(result);
setSelected(new Set());
- setPreview(null);
+ discardAugment();
}
- }, [universeId, mountedRef]);
+ }, [universeId, mountedRef, discardAugment]);
useEffect(() => {
if (!open || !universeId) return;
@@ -123,70 +150,12 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver
: `Reviewed the cast — ${n} finding${n === 1 ? '' : 's'}`);
};
- const handlePropose = async () => {
- if (proposing || selectedCharacterIds.length !== 1) return;
+ const handlePropose = () => {
+ if (selectedCharacterIds.length !== 1) return;
const characterId = selectedCharacterIds[0];
+ const name = report?.coverage?.find((c) => c.characterId === characterId)?.characterName;
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));
+ runPropose(characterId, name, fields);
};
const reviewLabel = scope?.providerId
@@ -327,55 +296,14 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver
</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]">{humanizeIntegrityField(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}
+ <AugmentPreview
+ preview={preview}
+ accepted={accepted}
+ applying={applying}
+ onToggleField={toggleField}
+ onDiscard={discardAugment}
+ onApply={runApply}
+ />
</>
) : null}
</div>
diff --git a/client/src/components/writers-room/SyncedReview.jsx b/client/src/components/writers-room/SyncedReview.jsx
index 5700644f4c..84527b2a28 100644
--- a/client/src/components/writers-room/SyncedReview.jsx
+++ b/client/src/components/writers-room/SyncedReview.jsx
@@ -1,14 +1,21 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
- AlertTriangle, Clapperboard, FileText, Image as ImageIcon, Link2, Loader2, RefreshCw, Users, X,
+ AlertTriangle, Clapperboard, FileText, Image as ImageIcon, Link2, Loader2, RefreshCw, Sparkles, Users, X,
} from 'lucide-react';
-import { getWritersRoomSyncedReview } from '../../services/apiWritersRoom';
+import {
+ getWritersRoomSyncedReview,
+ proposeWritersRoomCharacterAugmentation,
+ applyWritersRoomCharacterAugmentation,
+} from '../../services/apiWritersRoom';
import { timeAgo } from '../../utils/formatters';
import useMounted from '../../hooks/useMounted';
+import useCharacterAugmentation from '../../hooks/useCharacterAugmentation';
+import AugmentPreview from '../castIntegrity/AugmentPreview';
import {
DEPTH_META,
FINDING_KIND_META,
REVIEW_STATUS_META,
+ findingIsRepairable,
humanizeIntegrityField,
} from '../../lib/characterIntegrity';
@@ -173,6 +180,23 @@ export default function SyncedReview({ work }) {
}, [cast]);
const castGapCount = cast.coverage.filter((row) => row.findingCount > 0).length;
+ // Selective augmentation over the per-work bible (#6417). Same contract the
+ // Universe cast panel uses — the pane only supplies the work-scoped requests.
+ // `refresh` after an apply rather than patching the cast block in place: the
+ // findings, the depth ruling and the staging join are all DERIVED from the
+ // record that just changed, so a local patch would leave three of them stale.
+ const augment = useCharacterAugmentation({
+ propose: useCallback(
+ (characterId, fields) => proposeWritersRoomCharacterAugmentation(work.id, characterId, { fields }, { silent: true }),
+ [work.id],
+ ),
+ apply: useCallback(
+ (characterId, body) => applyWritersRoomCharacterAugmentation(work.id, characterId, body, { silent: true }),
+ [work.id],
+ ),
+ onApplied: refresh,
+ });
+
// Resolve prose segment ids → headings for provenance labels.
const segHeading = useMemo(() => {
const map = new Map();
@@ -389,6 +413,7 @@ export default function SyncedReview({ work }) {
selectedId={selectedIdFor(selection, 'cast')}
hasSelection={hasSelection}
onSelect={(id) => select('cast', id)}
+ augment={augment}
/>
)}
</div>
@@ -555,8 +580,9 @@ function MediaPane({ containerRef, className, items, mediaSceneIds, selectedId,
const BADGE_CLASS = 'inline-flex items-center px-1 py-0.5 rounded border text-[9px] uppercase tracking-wider';
const KIND_TONE = { amber: 'text-amber-300 border-amber-500/40', rose: 'text-rose-300 border-rose-500/40' };
-function CastPane({ containerRef, className, cast, findingsByCharacter, castIds, selectedId, hasSelection, onSelect }) {
+function CastPane({ containerRef, className, cast, findingsByCharacter, castIds, selectedId, hasSelection, onSelect, augment }) {
const { staging } = cast;
+ const { preview, accepted, applying, proposing, toggleField, discard, runPropose, runApply } = augment;
return (
<ScrollPane containerRef={containerRef} className={className} paneKey="cast" icon={Users} label="Cast" count={cast.castCount}>
{!cast.available ? (
@@ -570,59 +596,87 @@ function CastPane({ containerRef, className, cast, findingsByCharacter, castIds,
const depth = DEPTH_META[row.depth] || DEPTH_META.full;
const status = REVIEW_STATUS_META[row.status] || REVIEW_STATUS_META['not-reviewed'];
const findings = findingsByCharacter.get(row.characterId) || [];
+ // Only `missing` / `underspecified` can be machine-repaired: a
+ // `contradictory` finding needs the author, because nothing here can
+ // know which of two disagreeing fields is the wrong one.
+ const repairable = findings.filter(findingIsRepairable);
return (
- <button
- key={row.characterId}
- data-sync-id={row.characterId}
- aria-pressed={state === 'selected'}
- onClick={() => onSelect(row.characterId)}
- className={`w-full text-left rounded border px-3 py-2 transition-all ${CARD_CLASS[state]}`}
- >
- <div className="flex items-center justify-between gap-2 mb-1">
- <span className="text-[11px] font-medium text-gray-200 truncate">{row.characterName || row.characterId}</span>
- <span className="flex items-center gap-1 shrink-0">
- <span className={`${BADGE_CLASS} text-gray-400 border-port-border`} title={depth.hint}>{depth.label}</span>
- <span
- className={`${BADGE_CLASS} ${row.findingCount ? KIND_TONE.amber : 'text-gray-400 border-port-border'}`}
- title={row.findingCount ? `${row.findingCount} unauthored field(s)` : 'Nothing unauthored at this depth.'}
- >
- {status.label}
- </span>
- </span>
- </div>
-
- <div className="flex items-center gap-1.5 flex-wrap mb-1">
- {row.staged ? (
- <span className="flex items-center gap-0.5 text-[9px] text-gray-400 bg-port-card border border-port-border rounded px-1 py-0.5">
- <Clapperboard size={8} /> staged in {row.scriptSceneIds.length}
- </span>
- ) : (
- <span className="text-[9px] text-gray-600 italic" title={staging.available
- ? 'No extracted scene names this character. Offstage is a choice, not a defect.'
- : 'No script yet — run “Adapt” before reading anything into this.'}>
- {staging.available ? 'not staged in the script' : 'staging unknown'}
+ <div key={row.characterId} className="space-y-1">
+ <button
+ data-sync-id={row.characterId}
+ aria-pressed={state === 'selected'}
+ onClick={() => onSelect(row.characterId)}
+ className={`w-full text-left rounded border px-3 py-2 transition-all ${CARD_CLASS[state]}`}
+ >
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <span className="text-[11px] font-medium text-gray-200 truncate">{row.characterName || row.characterId}</span>
+ <span className="flex items-center gap-1 shrink-0">
+ <span className={`${BADGE_CLASS} text-gray-400 border-port-border`} title={depth.hint}>{depth.label}</span>
+ <span
+ className={`${BADGE_CLASS} ${row.findingCount ? KIND_TONE.amber : 'text-gray-400 border-port-border'}`}
+ title={row.findingCount ? `${row.findingCount} unauthored field(s)` : 'Nothing unauthored at this depth.'}
+ >
+ {status.label}
+ </span>
</span>
+ </div>
+
+ <div className="flex items-center gap-1.5 flex-wrap mb-1">
+ {row.staged ? (
+ <span className="flex items-center gap-0.5 text-[9px] text-gray-400 bg-port-card border border-port-border rounded px-1 py-0.5">
+ <Clapperboard size={8} /> staged in {row.scriptSceneIds.length}
+ </span>
+ ) : (
+ <span className="text-[9px] text-gray-600 italic" title={staging.available
+ ? 'No extracted scene names this character. Offstage is a choice, not a defect.'
+ : 'No script yet — run “Adapt” before reading anything into this.'}>
+ {staging.available ? 'not staged in the script' : 'staging unknown'}
+ </span>
+ )}
+ </div>
+
+ {findings.length > 0 && (
+ <ul className="space-y-1">
+ {findings.map((f) => {
+ const meta = FINDING_KIND_META[f.kind];
+ return (
+ <li key={f.id} className="text-[10px] text-gray-400 leading-snug">
+ <span className={`${BADGE_CLASS} mr-1 ${KIND_TONE[meta?.tone] || 'text-gray-400 border-port-border'}`} title={meta?.hint}>
+ {meta?.label || f.kind}
+ </span>
+ <span className="font-mono text-gray-300">{humanizeIntegrityField(f.field)}</span>
+ {f.evidence && <span className="text-gray-500"> — {f.evidence}</span>}
+ {f.suggestion && <span className="text-gray-500 italic"> {f.suggestion}</span>}
+ </li>
+ );
+ })}
+ </ul>
)}
- </div>
-
- {findings.length > 0 && (
- <ul className="space-y-1">
- {findings.map((f) => {
- const meta = FINDING_KIND_META[f.kind];
- return (
- <li key={f.id} className="text-[10px] text-gray-400 leading-snug">
- <span className={`${BADGE_CLASS} mr-1 ${KIND_TONE[meta?.tone] || 'text-gray-400 border-port-border'}`} title={meta?.hint}>
- {meta?.label || f.kind}
- </span>
- <span className="font-mono text-gray-300">{humanizeIntegrityField(f.field)}</span>
- {f.evidence && <span className="text-gray-500"> — {f.evidence}</span>}
- {f.suggestion && <span className="text-gray-500 italic"> {f.suggestion}</span>}
- </li>
- );
- })}
- </ul>
+ </button>
+ {repairable.length > 0 && (
+ <button
+ type="button"
+ onClick={() => runPropose(row.characterId, row.characterName, repairable.map((f) => f.field))}
+ disabled={proposing}
+ title="Ask the configured model for a sharper version of these fields. Writes nothing — you tick what to keep."
+ className="inline-flex items-center gap-1 rounded border border-port-accent/40 bg-port-accent/10 px-2 py-1 text-[10px] text-port-accent hover:bg-port-accent/20 disabled:opacity-40"
+ >
+ {proposing ? <Loader2 size={10} className="animate-spin" /> : <Sparkles size={10} />}
+ Sharpen {repairable.length} field{repairable.length === 1 ? '' : 's'}
+ </button>
)}
- </button>
+ {preview?.characterId === row.characterId && (
+ <AugmentPreview
+ preview={preview}
+ accepted={accepted}
+ applying={applying}
+ onToggleField={toggleField}
+ onDiscard={discard}
+ onApply={runApply}
+ idPrefix="wr-augment"
+ />
+ )}
+ </div>
);
})}
diff --git a/client/src/components/writers-room/SyncedReview.test.jsx b/client/src/components/writers-room/SyncedReview.test.jsx
index d8754510a7..2698a5d09a 100644
--- a/client/src/components/writers-room/SyncedReview.test.jsx
+++ b/client/src/components/writers-room/SyncedReview.test.jsx
@@ -3,9 +3,15 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
// Mock the API so the component renders a deterministic synced-review payload.
const getWritersRoomSyncedReview = vi.fn();
+const proposeAugment = vi.fn();
+const applyAugment = vi.fn();
vi.mock('../../services/apiWritersRoom', () => ({
getWritersRoomSyncedReview: (...args) => getWritersRoomSyncedReview(...args),
+ proposeWritersRoomCharacterAugmentation: (...args) => proposeAugment(...args),
+ applyWritersRoomCharacterAugmentation: (...args) => applyAugment(...args),
}));
+const toastMock = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('../ui/Toast', () => ({ default: toastMock }));
import SyncedReview from './SyncedReview';
@@ -36,6 +42,10 @@ function payload(overrides = {}) {
beforeEach(() => {
getWritersRoomSyncedReview.mockReset();
+ proposeAugment.mockReset();
+ applyAugment.mockReset();
+ toastMock.error.mockReset();
+ toastMock.success.mockReset();
});
const work = { id: 'wr-work-1', title: 'Test' };
@@ -289,6 +299,66 @@ describe('SyncedReview — cast pane', () => {
await waitFor(() => expect(card('cast', 'wr-char-hero').className).toMatch(/border-port-accent\/50/));
});
+ // ---- selective augmentation (#6417) ----
+
+ it('sharpens only the ticked field, and only from an explicit click', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(castPayload());
+ proposeAugment.mockResolvedValue({
+ entry: { id: 'wr-char-hero', name: 'Hero' },
+ fingerprint: 'fp-1',
+ proposals: [
+ { field: 'psychology.drives.status.fear', before: '', after: 'Being thanked instead of hired.', rationale: 'names the moment' },
+ { field: 'lie', before: 'A generic belief.', after: 'A sharper belief.', rationale: '' },
+ ],
+ });
+ applyAugment.mockResolvedValue({ entry: { id: 'wr-char-hero' }, appliedFields: ['lie'], fingerprint: 'fp-2' });
+
+ render(<SyncedReview work={work} />);
+ fireEvent.click(await screen.findByText(/1 cast gap/));
+ // Opening the pane spends nothing.
+ expect(proposeAugment).not.toHaveBeenCalled();
+
+ fireEvent.click(await screen.findByText(/Sharpen 1 field/));
+ await waitFor(() => expect(screen.getByText(/tick what to keep/)).toBeTruthy());
+ expect(proposeAugment).toHaveBeenCalledWith(
+ 'wr-work-1', 'wr-char-hero', { fields: ['psychology.drives.status.fear'] }, { silent: true },
+ );
+
+ // Nothing is accepted until the author ticks it.
+ const applyButton = screen.getByRole('button', { name: /Apply/ });
+ expect(applyButton.disabled).toBe(true);
+ fireEvent.click(screen.getByLabelText(/Lie/));
+ fireEvent.click(screen.getByRole('button', { name: /Apply/ }));
+
+ await waitFor(() => expect(applyAugment).toHaveBeenCalledWith(
+ 'wr-work-1', 'wr-char-hero',
+ { fields: [{ field: 'lie', value: 'A sharper belief.' }], fingerprint: 'fp-1' },
+ { silent: true },
+ ));
+ // The findings, the depth ruling and the staging join are all derived from
+ // the record that just changed, so the pane re-reads rather than patching.
+ await waitFor(() => expect(getWritersRoomSyncedReview).toHaveBeenCalledTimes(2));
+ });
+
+ it('offers no repair for a contradictory finding — only the author can settle it', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(castPayload({
+ findings: [{
+ id: 'wr-char-hero::contradictory::lie', characterId: 'wr-char-hero', characterName: 'Hero',
+ kind: 'contradictory', field: 'lie', dimension: 'control-predicts-behavior',
+ evidence: 'The belief and the described behavior disagree.', suggestion: '',
+ }],
+ coverage: [{
+ characterId: 'wr-char-hero', characterName: 'Hero', depth: 'full', status: 'findings',
+ findingCount: 1, semanticReviewed: true, staged: true,
+ scriptSceneIds: ['scene-01'], proseSegmentIds: ['seg-001'],
+ }],
+ }));
+ render(<SyncedReview work={work} />);
+ fireEvent.click(await screen.findByText(/1 cast gap/));
+ expect(await screen.findByText('Hero')).toBeTruthy();
+ expect(screen.queryByText(/Sharpen/)).toBeNull();
+ });
+
it('says staging is unknown rather than absent when no script has run', async () => {
getWritersRoomSyncedReview.mockResolvedValue(castPayload({
staging: { available: false, stale: false, stagedCount: 0, unstagedCount: 2, unmatchedNames: [] },
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9e1edc2926..1af8a41242 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -83,6 +83,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
+| `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
| `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. |
| `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 168f69f80e..0dd1150ebf 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -57,6 +57,7 @@ export { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';
export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';
export { default as useMusicVideoYoutubeImport } from './useMusicVideoYoutubeImport.js';
export { default as useMoltworldWs } from './useMoltworldWs.js';
+export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';
export { default as useMounted } from './useMounted.js';
export { default as usePendingListRows } from './usePendingListRows.js';
export { default as usePopoverPosition } from './usePopoverPosition.js';
diff --git a/client/src/hooks/useCharacterAugmentation.js b/client/src/hooks/useCharacterAugmentation.js
new file mode 100644
index 0000000000..8961e157cd
--- /dev/null
+++ b/client/src/hooks/useCharacterAugmentation.js
@@ -0,0 +1,98 @@
+import { useCallback, useState } from 'react';
+import toast from '../components/ui/Toast';
+import useMounted from './useMounted';
+
+/**
+ * The propose → review → selectively-apply loop for character augmentation
+ * (#6415 / #6417), shared by the Universe cast panel and the Writers Room
+ * synced review's Cast pane.
+ *
+ * Both surfaces run the identical three-step dance over the same server
+ * contract — one call proposes, the author ticks individual fields, a second
+ * call takes back only what was ticked — and it is the *rules* in that dance,
+ * not the layout, that must not drift between them:
+ *
+ * - **Nothing is accepted until it is ticked.** A fresh proposal opens with
+ * an empty selection, so a bulk "apply" can never sweep in a rewrite the
+ * author didn't read.
+ * - **"No improvement offered" is a success, not an error.** A model that
+ * honestly declines to paraphrase must not read as a failed call.
+ * - **A locked character stops the flow at both ends**, because a lock can be
+ * set between the proposal and the apply.
+ *
+ * The caller supplies only the two request thunks (which host, which record)
+ * and an `onApplied` for whatever its own view has to refresh.
+ *
+ * @param {object} args
+ * @param {(characterId: string, fields: string[]) => Promise<object>} args.propose
+ * @param {(characterId: string, body: { fields: Array<{field: string, value: string}>, fingerprint?: string }) => Promise<object>} args.apply
+ * @param {(result: object, preview: object) => void} [args.onApplied] runs after a successful apply
+ */
+export default function useCharacterAugmentation({ propose, apply, onApplied }) {
+ const mountedRef = useMounted();
+ // `{ characterId, entryName, fingerprint, proposals: [] }` awaiting review.
+ const [preview, setPreview] = useState(null);
+ const [accepted, setAccepted] = useState(() => new Set());
+ const [proposing, setProposing] = useState(false);
+ const [applying, setApplying] = useState(false);
+
+ const discard = useCallback(() => {
+ setPreview(null);
+ setAccepted(new Set());
+ }, []);
+
+ const toggleField = useCallback((field) => setAccepted((prev) => {
+ const next = new Set(prev);
+ if (next.has(field)) next.delete(field); else next.add(field);
+ return next;
+ }), []);
+
+ const runPropose = useCallback(async (characterId, entryName, fields) => {
+ if (proposing || !fields?.length) return;
+ setProposing(true);
+ const result = await propose(characterId, fields)
+ .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 || entryName || '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 || entryName || 'Character',
+ fingerprint: result.fingerprint,
+ proposals: result.proposals,
+ });
+ // Opt-IN: nothing is accepted until the author ticks it.
+ setAccepted(new Set());
+ }, [propose, proposing, mountedRef]);
+
+ const runApply = useCallback(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 apply(preview.characterId, { fields, fingerprint: preview.fingerprint })
+ .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;
+ }
+ const n = result.appliedFields?.length || 0;
+ toast.success(`Applied ${n} field${n === 1 ? '' : 's'} to ${preview.entryName}`);
+ onApplied?.(result, preview);
+ setPreview(null);
+ setAccepted(new Set());
+ }, [apply, applying, preview, accepted, onApplied, mountedRef]);
+
+ return { preview, accepted, proposing, applying, toggleField, discard, runPropose, runApply };
+}
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 5a98b31731..60526e726f 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -177,6 +177,25 @@ export const deleteWritersRoomCharacter = (workId, characterId, options = {}) =>
...options,
});
+// Selective cast augmentation (#6417) — the write half of the synced review's
+// Cast pane. Propose sharpens POPULATED framework fields and writes NOTHING,
+// returning `{ proposals: [{ field, before, after, rationale }], fingerprint }`;
+// apply takes back only the fields the author ticked. The `fingerprint` is the
+// character state the preview was reviewed against — a mismatch is a 409 rather
+// than an overwrite of an edit that landed while the model was thinking.
+export const proposeWritersRoomCharacterAugmentation = (workId, characterId, { fields, providerId, model } = {}, options = {}) =>
+ request(`/writers-room/works/${enc(workId)}/characters/${enc(characterId)}/augment`, {
+ method: 'POST',
+ body: JSON.stringify({ fields, providerId, model }),
+ ...options,
+ });
+export const applyWritersRoomCharacterAugmentation = (workId, characterId, { fields, fingerprint } = {}, options = {}) =>
+ request(`/writers-room/works/${enc(workId)}/characters/${enc(characterId)}/augment/apply`, {
+ method: 'POST',
+ body: JSON.stringify({ fields, fingerprint }),
+ ...options,
+ });
+
// Places / world bible (editable, persists across analysis runs, drives
// scene image gen via slugline match in SceneCard)
export const listWritersRoomPlaces = (workId) =>
diff --git a/data.reference/prompts/stages/writers-room-evaluate.md b/data.reference/prompts/stages/writers-room-evaluate.md
index bdac26dbe4..52a10cf8a3 100644
--- a/data.reference/prompts/stages/writers-room-evaluate.md
+++ b/data.reference/prompts/stages/writers-room-evaluate.md
@@ -18,7 +18,9 @@ You are an editorial reader giving a single round of constructive feedback on a
{{#castFrameworkJson}}
## Authored character framework
-The writer has already declared the following for this cast — their motivations, the Ghost that wounded them, the Wound itself, the Lie they believe, the Need that answers it, the Want they chase, the arc they intend, and the secrets they keep. This is the PLAN, not a description of the draft.
+The writer has already declared the following for this cast — their motivations, the Ghost that wounded them, the Wound itself, the Lie they believe, the Need that answers it, the Want they chase, the arc they intend, and the secrets they keep. A character may also carry a `psychology` profile (the theory of control they operate by, the strategy it produces, what it protects, what it costs now, the pressure that would test it, and the change it might undergo — plus the survival / connection / status drives) and `sliders` rating a few axes from 1 to 5. This is the PLAN, not a description of the draft.
+
+Only what the writer authored is included, so a field you do not see was left blank on purpose. A `psychology.assessment` of `unknown` or `not-applicable` is a decision the writer made about this character, not a gap.
```json
{{castFrameworkJson}}
diff --git a/docs/features/writers-room.md b/docs/features/writers-room.md
index e7e10aa522..8e941b2d97 100644
--- a/docs/features/writers-room.md
+++ b/docs/features/writers-room.md
@@ -91,7 +91,9 @@ The mapping model is a **relational read-model derived on request** rather than
Selecting prose highlights the mapped script and media; media cards show provenance (source segments, prompt, model, render job). Staleness falls out of the pinned analysis `sourceContentHash` — when the draft's hash differs, the UI shows stale badges and requires a deliberate re-run. Media attached to scenes that no longer exist after re-extraction is surfaced explicitly as orphaned rather than silently dropped.
-The **Cast pane** is where the cold read of the draft meets author knowledge, and the two are deliberately kept apart. Findings are the deterministic, zero-provider completeness pass over the AUTHORED bible — a character the prose stages vividly still reports every unauthored framework field, because an interior that lives only in the author's head is the defect. What the script extraction saw is reported beside it as `staged` (never as a repair): an authored character no scene stages is a fact rather than a flag, and a name the extraction found with no bible entry is listed under `staging.unmatchedNames` rather than becoming a finding the report has no record to attach. Depth rulings come from the same contract, so a declared minor role or flat arc is held to the conscious pursuit only. No model reads this cast here (`semanticReviewedCount` is 0 and `passed` is false by construction) — the semantic review and selective augmentation live in the Universe Bible's Cast Integrity panel.
+The **Cast pane** is where the cold read of the draft meets author knowledge, and the two are deliberately kept apart. Findings are the deterministic, zero-provider completeness pass over the AUTHORED bible — a character the prose stages vividly still reports every unauthored framework field, because an interior that lives only in the author's head is the defect. What the script extraction saw is reported beside it as `staged` (never as a repair): an authored character no scene stages is a fact rather than a flag, and a name the extraction found with no bible entry is listed under `staging.unmatchedNames` rather than becoming a finding the report has no record to attach. Depth rulings come from the same contract, so a declared minor role or flat arc is held to the conscious pursuit only. No model reads the cast to BUILD this report (`semanticReviewedCount` is 0 and `passed` is false by construction); the cast-wide semantic review still lives in the Universe Bible's Cast Integrity panel.
+
+**Selective augmentation** (#6417) is the write half, reached from a per-character *Sharpen* button that appears only on findings a model can actually repair — a `contradictory` finding never offers one, because nothing but the author can decide which of two disagreeing fields is wrong. Propose writes nothing and returns before/after per field; the author ticks what to keep and only those paths are applied. The proposal carries the character's fingerprint, so an edit that lands while the model is thinking gets a 409 rather than an overwrite. Peers sent to the model are this work's OWN cast — a work bible is work-local, and a universe roster would pull a draft toward a cast it has not been promoted into. The call, the field contract and the prompt stage are shared with the Universe cast editor via `server/services/characterAugmentation.js`.
## Federation
@@ -109,6 +111,7 @@ All under `/api/writers-room` (`server/routes/writersRoom.js`, client wrapper `c
- **Live director** — `POST /works/:id/live-suggest`, `POST /works/:id/live-render-preview`, `POST /works/:id/cd-bridge/{suggest,send}`
- **Synced review** — `GET /works/:id/synced-review`
- **Story bible** — `GET/POST /works/:id/{characters,places,objects}`, `PATCH/DELETE /works/:id/{characters,places,objects}/:entityId`
+- **Cast augmentation** — `POST /works/:id/characters/:characterId/augment` (propose, writes nothing), `POST /works/:id/characters/:characterId/augment/apply` (apply the ticked subset; 409 on a stale fingerprint)
Route inputs are Zod-validated at the boundary (`server/lib/validation.js`), except the scene-image attach route, which validates its fields inside `attachSceneImage` instead.
diff --git a/scripts/migrations/362-writers-room-character-framework.js b/scripts/migrations/362-writers-room-character-framework.js
index e66eaa8a89..e7c3390c63 100644
--- a/scripts/migrations/362-writers-room-character-framework.js
+++ b/scripts/migrations/362-writers-room-character-framework.js
@@ -22,7 +22,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
"writers-room-characters.md": "4b19f6538ff3a602007ef8e32c8e5047",
- "writers-room-evaluate.md": "d3b2b40bcabc9ca690fa67b69d64d628"
+ "writers-room-evaluate.md": "286e9498966187ed74126680da4a6a54"
};
const { applyMigration, up } = makePromptReplaceMigration({
accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,
diff --git a/scripts/migrations/366-writers-room-evaluate-psychology.js b/scripts/migrations/366-writers-room-evaluate-psychology.js
new file mode 100644
index 0000000000..f594267dbc
--- /dev/null
+++ b/scripts/migrations/366-writers-room-evaluate-psychology.js
@@ -0,0 +1,34 @@
+/**
+ * Name the psychology profile and the Three Sliders in the Writers Room
+ * evaluate prompt (#6417).
+ *
+ * `pickCharacterFramework` began projecting `psychology` and `sliders` into the
+ * author-side review payload, but the template's prose still enumerated only
+ * the Ghost → Wound → Lie → Need → Want chain — so a reader following the
+ * instructions had no idea what the extra JSON keys were, and no ruling on how
+ * to read them. This adds that sentence plus the one rule the projection makes
+ * necessary: an absent field was left blank on purpose, and a `psychology`
+ * ruled `unknown` / `not-applicable` is an authoring decision rather than a gap
+ * to report as a defect.
+ *
+ * Copy-only — no variables changed, so an install still on the previous shipped
+ * template keeps working either way; this just stops the prose from describing
+ * half the payload.
+ */
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ "writers-room-evaluate.md": [
+ "d3b2b40bcabc9ca690fa67b69d64d628"
+ ]
+};
+export const NEW_SHIPPED_MD5 = {
+ "writers-room-evaluate.md": "286e9498966187ed74126680da4a6a54"
+};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,
+ label: 'writers-room evaluate psychology',
+ customizedHint: (filename) => ` Merge the psychology / sliders paragraph and the "an absent field was left blank on purpose" rule from data.reference/prompts/stages/${filename}.`,
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/366-writers-room-evaluate-psychology.test.js b/scripts/migrations/366-writers-room-evaluate-psychology.test.js
new file mode 100644
index 0000000000..13b1fec4c9
--- /dev/null
+++ b/scripts/migrations/366-writers-room-evaluate-psychology.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './366-writers-room-evaluate-psychology.js';
+import { runPromptMigrationTests } from './_testHelpers.js';
+describe('migration 366 — writers-room evaluate psychology/sliders prose', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-366-' });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index c25e59e57b..5153938269 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -39,7 +39,7 @@ const EXPECTED_STAGE_OLD = {
'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],
'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],
'writers-room-characters.md': ['cdd99c7a3ef92bf798f30fa2fb4465f1'],
- 'writers-room-evaluate.md': ['d3374472820df264731f435141e05270'],
+ 'writers-room-evaluate.md': ['d3374472820df264731f435141e05270', 'd3b2b40bcabc9ca690fa67b69d64d628'],
'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],
'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],
'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],
@@ -91,7 +91,7 @@ const EXPECTED_STAGE_NEW = {
'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43',
'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',
'writers-room-characters.md': '4b19f6538ff3a602007ef8e32c8e5047',
- 'writers-room-evaluate.md': 'd3b2b40bcabc9ca690fa67b69d64d628',
+ 'writers-room-evaluate.md': '286e9498966187ed74126680da4a6a54',
'cos-agent-briefing.md': 'a01c81d3a7f4ac0ca9e8d5137735c0e3',
'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd',
'story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0',
diff --git a/server/lib/README.md b/server/lib/README.md
index a2fcac85f8..892aa99d59 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. |
| `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). |
+| `characterAugmentValidation.js` | Zod schemas for selective character augmentation (#6417): `characterAugmentProposeSchema` and `characterAugmentApplySchema`, both pinned to `AUGMENTABLE_FIELD_PATHS`. Shared by the Universe cast routes and the Writers Room work-bible routes so the two surfaces cannot drift on which field paths a proposal may name. |
| `characterEvolution.js` | The OPTIONAL five-stage character evolution lens (#6440): `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `CHARACTER_EVOLUTION_LIMITS`, `sanitizeCharacterEvolution` + `sanitizeCharacterEvolutionList` (null when unauthored, unknown stage/outcome rejected not coerced), `evolutionEvidenceStatus` (derived on read — only `anchored` counts as verified, a pointer to a deleted beat reports `stale`), `isDeclaredEvolution`, `renderCharacterEvolutionForPrompt`, and the per-character story-list primitives both hosts share (`isCanonCharacterId`, `isStoryBeatId`, `characterIdentityKey`, `optIssueNumber`, `EVOLUTION_EVIDENCE_FIELDS`). A pure leaf over `bibleLimits.js` + `textUtils.js` so `client/src/lib/characterEvolution.js` mirrors it into the browser bundle. |
| `characterEvolutionCoverage.js` | Branch coverage for the evolution lens (#6444): `analyzeCharacterEvolutionCoverage` walks every bounded playthrough and flags `EVOLUTION_UNEARNED_INHERITANCE` — a stage proved on one incoming branch of a reconvergence and not another, so a viewer inherits a change they never watched be earned — plus unproven declared endings, out-of-sequence stage anchors and dead evidence pointers (`EVOLUTION_COVERAGE_CODES`). Introduces `unreviewed` (`EVOLUTION_COVERAGE_STATUSES`): a bounded-out enumeration, a cycle or an unresolvable anchor is explicitly NOT `verified` and NOT a defect. Deterministic and provider-free; returns `null` when no lens is authored, so a loom that never opted in is byte-identical. |
| `characterEvolutionValidation.js` | Zod schemas for the evolution lens — `characterEvolutionSchema` (one lens), `characterEvolutionStageSchema`, `characterEvolutionEvidenceSchema` and `characterEvolutionListSchema` (the FableLoom plan's per-character list). Its own module rather than a `sharedSchemas.js` fragment so `validation.js` (which nearly every suite reaches) doesn't grow an eager edge for a shape only two hosts validate. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 0b88e27924..de21fd8cc2 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -17601,6 +17601,22 @@
"server/routes/writersRoom.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/writers-room/works/:id/characters/:characterId/augment",
+ "mountPath": "/api/writers-room",
+ "sources": [
+ "server/routes/writersRoom.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/writers-room/works/:id/characters/:characterId/augment/apply",
+ "mountPath": "/api/writers-room",
+ "sources": [
+ "server/routes/writersRoom.js"
+ ]
+ },
{
"method": "PUT",
"path": "/api/writers-room/works/:id/draft",
@@ -17988,8 +18004,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2228,
- "declarations": 2236,
+ "operations": 2230,
+ "declarations": 2238,
"sourceFiles": 233
}
}
diff --git a/server/lib/characterAugmentValidation.js b/server/lib/characterAugmentValidation.js
new file mode 100644
index 0000000000..a887a5acc6
--- /dev/null
+++ b/server/lib/characterAugmentValidation.js
@@ -0,0 +1,36 @@
+/**
+ * Route schemas for selective character augmentation (#6415 / #6417).
+ *
+ * The Universe cast editor and the Writers Room work bible expose the same two
+ * endpoints over the same field contract, so they validate against the same two
+ * schemas — a second hand-written copy is how one surface ends up accepting a
+ * path the other rejects.
+ *
+ * Both are pinned to `AUGMENTABLE_FIELD_PATHS`, which is the string-valued
+ * subset of the integrity contract. That is deliberately narrower than "any
+ * character field": it keeps a request from reaching the service (and the
+ * provider) with a path the before/after preview cannot render.
+ */
+
+import { z } from 'zod';
+import { AUGMENTABLE_FIELD_PATHS } from './characterIntegrity.js';
+
+/** Propose sharper values for the named populated fields. Writes nothing. */
+export const characterAugmentProposeSchema = 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(),
+});
+
+/**
+ * Apply only the proposals the author accepted. `fingerprint` is the character
+ * state the preview was reviewed against — the service turns a mismatch into a
+ * 409 rather than overwriting whatever was edited in the meantime.
+ */
+export const characterAugmentApplySchema = 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(),
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index a8f96e691d..be77a02957 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -27,6 +27,7 @@ export * as agentContextValidation from './agentContextValidation.js';
export * as appleHealthValidation from './appleHealthValidation.js';
export * as brainValidation from './brainValidation.js';
export * as catalogValidation from './catalogValidation.js';
+export * as characterAugmentValidation from './characterAugmentValidation.js';
export * as characterEvolutionValidation from './characterEvolutionValidation.js';
export * as cosValidation from './cosValidation.js';
export * from './cosToolContracts.js';
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index d0733b06c4..c8932ac1a0 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -437,7 +437,7 @@
"server/services/universeCastIntegrity.js"
],
"universe-character-augment": [
- "server/services/universeCastIntegrity.js"
+ "server/services/characterAugmentation.js"
],
"universe-character-expand": [
"server/services/universeCharacterExpand.js"
diff --git a/server/routes/universeBuilder/canon.js b/server/routes/universeBuilder/canon.js
index aa93810ea0..88495eb9b5 100644
--- a/server/routes/universeBuilder/canon.js
+++ b/server/routes/universeBuilder/canon.js
@@ -19,7 +19,7 @@ import {
proposeCharacterAugmentation,
applyCharacterAugmentation,
} from '../../services/universeCastIntegrity.js';
-import { AUGMENTABLE_FIELD_PATHS } from '../../lib/characterIntegrity.js';
+import { characterAugmentProposeSchema, characterAugmentApplySchema } from '../../lib/characterAugmentValidation.js';
import { getUniverseCanonUsage, listLinkedSeriesNames } from '../../services/canonUsage.js';
import { mapServiceError, lockParamsSchema } from './shared.js';
@@ -98,13 +98,8 @@ router.post('/:id/characters/integrity/review', asyncHandler(async (req, res) =>
// 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 body = validateRequest(characterAugmentProposeSchema, req.body ?? {});
const result = await proposeCharacterAugmentation(req.params.id, req.params.entryId, body)
.catch((err) => { throw mapServiceError(err); });
res.json(result);
@@ -113,15 +108,8 @@ router.post('/:id/characters/:entryId/augment', asyncHandler(async (req, res) =>
// 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 body = validateRequest(characterAugmentApplySchema, req.body ?? {});
const result = await applyCharacterAugmentation(req.params.id, req.params.entryId, body)
.catch((err) => { throw mapServiceError(err); });
res.json(result);
diff --git a/server/routes/writersRoom.castAugment.test.js b/server/routes/writersRoom.castAugment.test.js
new file mode 100644
index 0000000000..2835862354
--- /dev/null
+++ b/server/routes/writersRoom.castAugment.test.js
@@ -0,0 +1,238 @@
+/**
+ * Route → Zod → service → store round trip for Writers Room cast augmentation
+ * (#6417).
+ *
+ * Only the PROVIDER boundary is stubbed (`runPromptRefineRaw`) — the router,
+ * the shared schemas, `characterAugmentation.js` and the real per-work bible
+ * store all run, against a temp data root. That is what makes the load-bearing
+ * assertions meaningful: "propose writes nothing" and "apply persists only the
+ * ticked field" are both claims about the store, and a mocked store would let a
+ * dropped `editableFields` entry pass silently.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import express from 'express';
+import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+let tempRoot;
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tempRoot });
+});
+
+const refineRawMock = vi.fn();
+vi.mock('../services/pipeline/refineHelpers.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ runPromptRefineRaw: (...args) => refineRawMock(...args),
+}));
+
+// Everything else on the router that would reach a provider, Postgres, or a PTY.
+vi.mock('../services/writersRoom/evaluator.js', () => ({
+ runAnalysis: vi.fn(),
+ listAnalyses: vi.fn(async () => []),
+ getAnalysis: vi.fn(),
+ persistSceneImage: vi.fn(),
+}));
+vi.mock('../services/writersRoom/polish.js', () => ({
+ startPolish: vi.fn(), attachClient: vi.fn(), cancelPolish: vi.fn(),
+ isPolishActive: vi.fn(() => false), listSnapshots: vi.fn(async () => []),
+ getSnapshot: vi.fn(), revertToSnapshot: vi.fn(),
+}));
+vi.mock('../services/writersRoom/syncedReview.js', () => ({ getSyncedReview: vi.fn() }));
+vi.mock('../services/writersRoom/liveDirector.js', () => ({
+ suggestContinuation: vi.fn(), reserveRenderPreview: vi.fn(),
+ suggestCdBridge: vi.fn(), sendToCreativeDirector: vi.fn(),
+}));
+vi.mock('../services/writersRoom/promoteToPipeline.js', () => ({
+ promoteWorkToPipeline: vi.fn(), ERR_NO_DRAFT_BODY: 'WR_PROMOTE_NO_DRAFT_BODY',
+}));
+vi.mock('../services/catalogExtraction.js', () => ({
+ scanProseForIngredientRefs: vi.fn(async () => []),
+}));
+
+const { default: writersRoomRouter } = await import('./writersRoom.js');
+const { createWork } = await import('../services/writersRoom/local.js');
+const { createCharacter, getCharacter, updateCharacter } = await import('../services/writersRoom/characters.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/writers-room', writersRoomRouter);
+app.use(errorMiddleware);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-cast-augment-'));
+});
+afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+const LEAD = {
+ name: 'Wren',
+ role: 'protagonist',
+ lie: 'If I hold the chart, nobody else dies.',
+ want: 'Sole command of the northern survey.',
+ psychology: {
+ theoryOfControl: 'If I carry every decision, the cost lands on me.',
+ assessment: 'assessed',
+ drives: {
+ survival: { desire: 'A steady berth.', fear: 'Being put ashore.' },
+ status: { desire: 'To be the name asked for.', fear: 'Being read as lucky.' },
+ },
+ },
+};
+
+/** A work with a two-character bible; returns the base path plus both ids. */
+async function seed() {
+ const work = await createWork({ title: 'Example Work', kind: 'short-story' });
+ const lead = await createCharacter(work.id, LEAD);
+ const peer = await createCharacter(work.id, { name: 'Dockhand', role: 'minor' });
+ return { workId: work.id, leadId: lead.id, peerId: peer.id, base: `/api/writers-room/works/${work.id}/characters` };
+}
+
+/**
+ * Set the canon lock bit directly in the persisted bible.
+ *
+ * Writers Room has no lock toggle of its own — a locked entry gets here by
+ * arriving already locked (a peer-synced work, a merged extraction), which
+ * `sanitizeCharacter` round-trips. So the guard is real, and the only honest
+ * way to set up the fixture is to write the record the way it would arrive.
+ */
+function lockInStore(workId, characterId) {
+ const path = join(tempRoot, 'writers-room', 'works', workId, 'characters.json');
+ const doc = JSON.parse(readFileSync(path, 'utf8'));
+ doc.characters = doc.characters.map((c) => (c.id === characterId ? { ...c, locked: true } : c));
+ writeFileSync(path, JSON.stringify(doc, null, 2));
+}
+
+const proposalResponse = (proposals) => ({
+ content: { proposals }, rationale: 'ok', runId: 'run-1', providerId: 'prov-1', model: 'test-model',
+});
+
+/** The fingerprint a client can only ever obtain from a real propose call. */
+async function fingerprintFor(base, characterId) {
+ refineRawMock.mockResolvedValue(proposalResponse([{ field: 'lie', value: 'A sharper lie.' }]));
+ const res = await request(app).post(`${base}/${characterId}/augment`).send({ fields: ['lie'] });
+ return res.body.fingerprint;
+}
+
+describe('POST /works/:id/characters/:characterId/augment — propose', () => {
+ it('returns before/after and writes NOTHING to the bible', async () => {
+ const { workId, leadId, base } = await seed();
+ 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(app).post(`${base}/${leadId}/augment`).send({ fields: ['lie'] });
+ expect(res.status).toBe(200);
+ expect(res.body.proposals[0]).toMatchObject({ field: 'lie', before: LEAD.lie });
+ expect(res.body.fingerprint).toEqual(expect.any(String));
+ expect((await getCharacter(workId, leadId)).lie).toBe(LEAD.lie);
+ });
+
+ it('sends the SIBLING cast as peers, so the model keeps this work self-contained', async () => {
+ const { leadId, base } = await seed();
+ refineRawMock.mockResolvedValue(proposalResponse([]));
+ await request(app).post(`${base}/${leadId}/augment`).send({ fields: ['lie'] });
+ const peers = JSON.parse(refineRawMock.mock.calls[0][0].variables.peersJson);
+ expect(peers.map((p) => p.name)).toEqual(['Dockhand']);
+ });
+
+ it('drops a proposal for a field the user did not request', async () => {
+ const { leadId, base } = await seed();
+ refineRawMock.mockResolvedValue(proposalResponse([
+ { field: 'lie', value: 'sharper lie' },
+ { field: 'want', value: 'an unrequested rewrite' },
+ ]));
+ const res = await request(app).post(`${base}/${leadId}/augment`).send({ fields: ['lie'] });
+ expect(res.body.proposals.map((p) => p.field)).toEqual(['lie']);
+ });
+
+ it('rejects a field path outside the contract at the schema, before any call', async () => {
+ const { leadId, base } = await seed();
+ const res = await request(app).post(`${base}/${leadId}/augment`).send({ fields: ['physicalDescription'] });
+ expect(res.status).toBe(400);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+
+ it('skips the provider entirely for a locked character', async () => {
+ const { workId, leadId, base } = await seed();
+ lockInStore(workId, leadId);
+ const res = await request(app).post(`${base}/${leadId}/augment`).send({ fields: ['lie'] });
+ expect(res.body.locked).toBe(true);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+
+ it('404s on a character that is not in this work', async () => {
+ const { base } = await seed();
+ const res = await request(app).post(`${base}/wr-char-00000000-0000-0000-0000-000000000000/augment`).send({ fields: ['lie'] });
+ expect(res.status).toBe(404);
+ expect(refineRawMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /works/:id/characters/:characterId/augment/apply — selective apply', () => {
+ it('applies ONLY the selected field and leaves the rest untouched', async () => {
+ const { workId, leadId, base } = await seed();
+ const fingerprint = await fingerprintFor(base, leadId);
+ const res = await request(app).post(`${base}/${leadId}/augment/apply`)
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.status).toBe(200);
+ expect(res.body.appliedFields).toEqual(['lie']);
+ const stored = await getCharacter(workId, leadId);
+ expect(stored.lie).toBe('A sharper lie.');
+ expect(stored.want).toBe(LEAD.want);
+ });
+
+ it('writes a psychology leaf without dropping its siblings', async () => {
+ const { workId, leadId, base } = await seed();
+ const fingerprint = await fingerprintFor(base, leadId);
+ await request(app).post(`${base}/${leadId}/augment/apply`)
+ .send({ fields: [{ field: 'psychology.drives.status.fear', value: 'Being thanked instead of hired.' }], fingerprint });
+ const { psychology } = await getCharacter(workId, leadId);
+ expect(psychology.drives.status.fear).toBe('Being thanked instead of hired.');
+ expect(psychology.drives.status.desire).toBe(LEAD.psychology.drives.status.desire);
+ expect(psychology.theoryOfControl).toBe(LEAD.psychology.theoryOfControl);
+ });
+
+ it('409s instead of clobbering a character edited since the proposal', async () => {
+ const { workId, leadId, base } = await seed();
+ const fingerprint = await fingerprintFor(base, leadId);
+ await updateCharacter(workId, leadId, { lie: 'the author rewrote this by hand' });
+ const res = await request(app).post(`${base}/${leadId}/augment/apply`)
+ .send({ fields: [{ field: 'lie', value: 'the model version' }], fingerprint });
+ expect(res.status).toBe(409);
+ expect((await getCharacter(workId, leadId)).lie).toBe('the author rewrote this by hand');
+ });
+
+ it('does not go stale on an edit to an UNRELATED field', async () => {
+ const { workId, leadId, base } = await seed();
+ const fingerprint = await fingerprintFor(base, leadId);
+ await updateCharacter(workId, leadId, { physicalDescription: 'a newly written description' });
+ const res = await request(app).post(`${base}/${leadId}/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 { workId, leadId, base } = await seed();
+ const fingerprint = await fingerprintFor(base, leadId);
+ lockInStore(workId, leadId);
+ const res = await request(app).post(`${base}/${leadId}/augment/apply`)
+ .send({ fields: [{ field: 'lie', value: 'A sharper lie.' }], fingerprint });
+ expect(res.body.locked).toBe(true);
+ expect((await getCharacter(workId, leadId)).lie).toBe(LEAD.lie);
+ });
+
+ it('rejects an out-of-contract field path at the schema', async () => {
+ const { workId, leadId, base } = await seed();
+ const res = await request(app).post(`${base}/${leadId}/augment/apply`)
+ .send({ fields: [{ field: 'wardrobes', value: 'x' }] });
+ expect(res.status).toBe(400);
+ expect((await getCharacter(workId, leadId)).lie).toBe(LEAD.lie);
+ });
+});
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 06c15b60db..e7f74621f9 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -51,6 +51,12 @@ import {
import {
listCharacters, createCharacter, updateCharacter, deleteCharacter,
} from '../services/writersRoom/characters.js';
+import {
+ proposeWorkCharacterAugmentation, applyWorkCharacterAugmentation,
+} from '../services/writersRoom/castAugment.js';
+import {
+ characterAugmentProposeSchema, characterAugmentApplySchema,
+} from '../lib/characterAugmentValidation.js';
import {
listPlaces, createPlace, updatePlace, deletePlace,
} from '../services/writersRoom/places.js';
@@ -325,6 +331,25 @@ router.delete('/works/:id/characters/:characterId', asyncHandler(async (req, res
res.json(await deleteCharacter(req.params.id, req.params.characterId));
}));
+// ---------- cast augmentation (#6417) ----------
+//
+// The write half of the Cast pane's integrity report: sharpen a framework field
+// that is populated but too generic to predict behavior. Same contract as the
+// Universe cast editor (services/characterAugmentation.js) — propose writes
+// nothing and returns before/after per field; apply takes back only the paths
+// the author ticked, and refuses (409) when the character moved underneath the
+// proposal. Both are explicit user actions; nothing here runs on a page load.
+
+router.post('/works/:id/characters/:characterId/augment', asyncHandler(async (req, res) => {
+ const data = validateRequest(characterAugmentProposeSchema, req.body || {});
+ res.json(await proposeWorkCharacterAugmentation(req.params.id, req.params.characterId, data));
+}));
+
+router.post('/works/:id/characters/:characterId/augment/apply', asyncHandler(async (req, res) => {
+ const data = validateRequest(characterAugmentApplySchema, req.body || {});
+ res.json(await applyWorkCharacterAugmentation(req.params.id, req.params.characterId, data));
+}));
+
// ---------- places (locations / universe bible) ----------
router.get('/works/:id/places', asyncHandler(async (req, res) => {
diff --git a/server/services/characterAugmentation.js b/server/services/characterAugmentation.js
new file mode 100644
index 0000000000..d52863a5f3
--- /dev/null
+++ b/server/services/characterAugmentation.js
@@ -0,0 +1,209 @@
+/**
+ * Selective character augmentation — the surface-agnostic half (#6417).
+ *
+ * "Sharpen a field that is already written" is the same operation whether the
+ * character lives in a universe's canon array or in a Writers Room work's
+ * per-work bible: same field contract (`lib/characterIntegrity.js`), same
+ * prompt, same before/after preview, same staleness rule. Only *where the
+ * record is read from and written back to* differs.
+ *
+ * So the steps that do not depend on storage live here, and each caller keeps
+ * the one that does:
+ *
+ * - `proposeAugmentation` — one provider call over a character record the
+ * caller already loaded. Writes NOTHING; returns before/after per field
+ * plus the fingerprint the apply must match.
+ * - `applyAugmentationToCharacter` — the pure merge + re-sanitize, so the
+ * caller only has to persist the record it gets back.
+ * - `augmentationIsStale` / the shared error constructors — the guards both
+ * surfaces must enforce identically, because "the author edited this while
+ * the model was thinking" has exactly one correct answer (refuse, 409).
+ *
+ * Both callers run those guards against the FRESHEST record they can read —
+ * `universeCastIntegrity.js` inside its write queue, `writersRoom/castAugment.js`
+ * immediately before its store write — rather than against the copy the
+ * proposal was generated from.
+ *
+ * The prompt stage is shared too. `universe-character-augment` is written
+ * against the field contract, not against universes: every rule in it is about
+ * what a `psychology.drives.status.fear` may say, so a second near-identical
+ * template for Writers Room would be a clone that drifts, and renaming the
+ * shipped stage would drop any install's customized copy of it.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { sanitizeBibleField } from '../lib/storyBible.js';
+import {
+ characterFingerprint,
+ characterIntegrityDepth,
+ characterIntegrityDimensions,
+ isAugmentableFieldPath,
+ readIntegrityField,
+ withIntegrityField,
+} from '../lib/characterIntegrity.js';
+
+/** The shipped stage both surfaces render — see the module note. */
+const CHARACTER_AUGMENT_STAGE = 'universe-character-augment';
+
+/**
+ * The character record the review/augment prompts see: the integrity framework
+ * plus the fields the dimensions judge against. Deliberately NOT the whole
+ * record — wardrobes, identity packs and image refs cost context and answer
+ * none of the questions being asked.
+ */
+export 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 || '',
+ })),
+});
+
+/** 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)))];
+};
+
+/**
+ * The `{ field, value }` pairs an apply may act on. Anything outside the
+ * contract, or carrying a non-string / blank value, is dropped here rather than
+ * reaching the merge — the route schema already rejects them, and this keeps a
+ * direct service caller honest too.
+ */
+export const acceptedAugmentFields = (fields) => (Array.isArray(fields) ? fields : []).filter((f) => (
+ typeof f?.field === 'string' && isAugmentableFieldPath(f.field)
+ && typeof f.value === 'string' && f.value.trim()
+));
+
+const noAugmentFieldsError = () => new ServerError('No augmentable fields requested', {
+ status: 400, code: 'CHARACTER_AUGMENT_NO_FIELDS',
+});
+
+export const noAugmentSelectionError = () => new ServerError('No fields selected to apply', {
+ status: 400, code: 'CHARACTER_AUGMENT_NO_SELECTION',
+});
+
+export const staleAugmentError = () => new ServerError(
+ 'This character changed since the proposal was generated — re-run the review and try again.',
+ { status: 409, code: 'CHARACTER_AUGMENT_STALE' },
+);
+
+/**
+ * Whether `current` has moved since the proposal was generated against
+ * `fingerprint`. An absent fingerprint is an unchecked apply (a direct service
+ * caller), not a match — the caller decides whether to require one.
+ */
+export const augmentationIsStale = (current, fingerprint) => (
+ !!fingerprint && characterFingerprint(current) !== fingerprint
+);
+
+/**
+ * Propose sharper values for POPULATED fields of one character. 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").
+ *
+ * @param {object} args
+ * @param {object} args.entry the character to sharpen (already loaded by the caller)
+ * @param {Array} args.peers sibling cast, so the model keeps this character distinct from them
+ * @param {Array} args.fields requested integrity field paths
+ */
+export async function proposeAugmentation({ entry, peers = [], fields, providerId, model }) {
+ if (entry?.locked === true) return { locked: true, entry, proposals: [] };
+
+ const paths = resolveAugmentPaths(fields);
+ if (paths.length === 0) throw noAugmentFieldsError();
+
+ // Deferred: `refineHelpers` drags the whole staged-LLM runner, and this
+ // module is reached from the Writers Room ROUTER — a static edge would pull
+ // that subtree into every suite that mounts those routes (server/AGENTS.md,
+ // "Import scoping").
+ const { runPromptRefineRaw } = await import('./pipeline/refineHelpers.js');
+ const { content, rationale, runId, providerId: usedProvider, model: usedModel } = await runPromptRefineRaw({
+ templateName: CHARACTER_AUGMENT_STAGE,
+ variables: {
+ characterJson: JSON.stringify(characterForReview(entry), null, 2),
+ fieldsJson: JSON.stringify(paths.map((path) => ({ field: path, current: readIntegrityField(entry, path) })), null, 2),
+ peersJson: JSON.stringify(peers.map((c) => ({ id: c.id, name: c.name, role: c.role || '' }))),
+ },
+ options: { providerId, model },
+ source: CHARACTER_AUGMENT_STAGE,
+ logTag: null,
+ emptyError: {
+ code: '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(entry, field);
+ if (!after || after === before) continue;
+ seen.add(field);
+ proposals.push({
+ field,
+ before,
+ after,
+ rationale: typeof raw.rationale === 'string' ? raw.rationale.trim() : '',
+ });
+ }
+
+ return {
+ entry,
+ 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(entry),
+ rationale,
+ runId,
+ providerId: usedProvider || null,
+ model: usedModel || null,
+ };
+}
+
+/**
+ * Merge accepted proposals into a character record. Pure: the caller persists
+ * the result through whatever store owns the record.
+ *
+ * Touched containers are re-sanitized so caps/enums are enforced on values that
+ * came back from a model and then round-tripped through the client.
+ */
+export function applyAugmentationToCharacter(current, accepted) {
+ let next = current;
+ const appliedFields = [];
+ for (const { field, value } of accepted) {
+ next = withIntegrityField(next, field, value.trim());
+ appliedFields.push(field);
+ }
+ 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]) };
+ }
+ return { next, appliedFields };
+}
diff --git a/server/services/universeCastIntegrity.js b/server/services/universeCastIntegrity.js
index ba75998611..4ccd7fd262 100644
--- a/server/services/universeCastIntegrity.js
+++ b/server/services/universeCastIntegrity.js
@@ -15,7 +15,9 @@
* 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.
+ * takes back only the paths the user selected. Both are thin wrappers over
+ * `characterAugmentation.js`, which Writers Room shares (#6417) — this
+ * module contributes only the universe read/write.
*
* Reports are derived, never stored, so "invalidate stale reports on relevant
* edits" is a fingerprint comparison rather than a cache: `applyCharacterAugmentation`
@@ -27,22 +29,24 @@ 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 {
+ acceptedAugmentFields,
+ applyAugmentationToCharacter,
+ augmentationIsStale,
+ characterForReview,
+ noAugmentSelectionError,
+ proposeAugmentation,
+ staleAugmentError,
+} from './characterAugmentation.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
@@ -58,31 +62,6 @@ const notFound = (entryId) => new ServerError(`Character ${entryId} not found in
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
@@ -182,16 +161,10 @@ export async function reviewUniverseCast(universeId, { characterIds = null, prov
};
}
-/** 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").
+ * Propose sharper values for POPULATED fields of one universe character.
+ * Storage is all this layer adds — the call, the field filtering and the
+ * fingerprint live in `characterAugmentation.js`, shared with Writers Room.
*/
export async function proposeCharacterAugmentation(universeId, entryId, {
fields, providerId, model,
@@ -200,66 +173,13 @@ export async function proposeCharacterAugmentation(universeId, entryId, {
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 {
+ return proposeAugmentation({
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,
- };
+ peers: cast.filter((c) => c.id !== entryId),
+ fields,
+ providerId,
+ model,
+ });
}
/**
@@ -271,13 +191,8 @@ export async function proposeCharacterAugmentation(universeId, entryId, {
* 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',
- });
- }
+ const accepted = acceptedAugmentFields(fields);
+ if (accepted.length === 0) throw noAugmentSelectionError();
let outcome = { locked: false, stale: false, missing: false, appliedFields: [] };
const updated = await updateUniverse(universeId, (latest) => {
@@ -292,34 +207,17 @@ export async function applyCharacterAugmentation(universeId, entryId, { fields =
outcome = { ...outcome, locked: true };
return null;
}
- if (fingerprint && characterFingerprint(current) !== fingerprint) {
+ if (augmentationIsStale(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]) };
- }
+ const { next, appliedFields } = applyAugmentationToCharacter(current, accepted);
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' },
- );
- }
+ if (outcome.stale) throw staleAugmentError();
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: [] };
diff --git a/server/services/writersRoom/castAugment.js b/server/services/writersRoom/castAugment.js
new file mode 100644
index 0000000000..abdc041a7a
--- /dev/null
+++ b/server/services/writersRoom/castAugment.js
@@ -0,0 +1,97 @@
+/**
+ * Writers Room — selective cast augmentation (the last remaining half of #6417).
+ *
+ * The synced review's Cast pane already reports where a character's authored
+ * framework is thin (`syncedReview.js`, via the shared
+ * `lib/characterIntegrity.js` contract). This is the write surface that answers
+ * those findings: propose a sharper value for a populated-but-generic field,
+ * show the author before/after, and take back only what they tick.
+ *
+ * Everything except the storage is shared with the Universe cast editor via
+ * `services/characterAugmentation.js` — same prompt stage, same field contract,
+ * same fingerprint rule. What this module owns is the per-work bible:
+ *
+ * - Peers are the SIBLING CAST OF THIS WORK, never a universe roster. A work
+ * bible is work-local (`wr-char-` ids), and handing the model a universe's
+ * characters would push a Writers Room draft toward a cast it has not been
+ * promoted into.
+ * - The apply re-reads the entry through the store and re-checks the
+ * fingerprint immediately before writing, so an author edit made while the
+ * model was thinking is refused (409) rather than silently overwritten.
+ * - The write goes through `updateCharacter`, so the bible sanitizer,
+ * `editableFields` and the `source: 'user'` stamp all apply exactly as they
+ * do for a hand edit. An augmented field is authored material the writer
+ * accepted, not an extraction.
+ *
+ * No provider call happens on read. Both entry points are explicit user actions.
+ */
+
+import { shortId } from '../../lib/fileUtils.js';
+import { characterFingerprint } from '../../lib/characterIntegrity.js';
+import {
+ acceptedAugmentFields,
+ applyAugmentationToCharacter,
+ augmentationIsStale,
+ noAugmentSelectionError,
+ proposeAugmentation,
+ staleAugmentError,
+} from '../characterAugmentation.js';
+import { listCharacters, updateCharacter } from './characters.js';
+import { assertValidWorkId, notFound } from './_shared.js';
+
+/** The work's cast plus the requested entry, or a 404 when it isn't in there. */
+async function loadCast(workId, characterId) {
+ assertValidWorkId(workId);
+ const cast = (await listCharacters(workId)).filter((c) => c?.id);
+ const entry = cast.find((c) => c.id === characterId);
+ if (!entry) throw notFound('Character');
+ return { cast, entry };
+}
+
+/**
+ * Propose sharper values for populated framework fields. Writes nothing.
+ */
+export async function proposeWorkCharacterAugmentation(workId, characterId, {
+ fields, providerId, model,
+} = {}) {
+ const { cast, entry } = await loadCast(workId, characterId);
+ return proposeAugmentation({
+ entry,
+ peers: cast.filter((c) => c.id !== characterId),
+ fields,
+ providerId,
+ model,
+ });
+}
+
+/**
+ * Apply the subset of a proposal the author accepted.
+ *
+ * Locked / deleted / edited-since are all checked against the record as it is
+ * NOW, not against the copy the proposal was built from.
+ */
+export async function applyWorkCharacterAugmentation(workId, characterId, { fields = [], fingerprint } = {}) {
+ const accepted = acceptedAugmentFields(fields);
+ if (accepted.length === 0) throw noAugmentSelectionError();
+
+ const { entry } = await loadCast(workId, characterId);
+ if (entry.locked === true) return { locked: true, entry, appliedFields: [] };
+ if (augmentationIsStale(entry, fingerprint)) throw staleAugmentError();
+
+ const { next, appliedFields } = applyAugmentationToCharacter(entry, accepted);
+ // Patch only the containers the merge actually touched: a whole-record patch
+ // would hand every editable field back to the store on every apply, turning
+ // an unrelated concurrent edit into a silent revert.
+ const patch = {};
+ for (const field of appliedFields) {
+ const key = field.split('.')[0];
+ patch[key] = next[key];
+ }
+ const updated = await updateCharacter(workId, characterId, patch);
+ console.log(`🩹 Writers Room character augment — work=${shortId(workId)} entry=${shortId(characterId)} fields=${appliedFields.length}`);
+ return {
+ entry: updated,
+ appliedFields,
+ fingerprint: characterFingerprint(updated),
+ };
+}