Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: report cast integrity in the Writers Room synced review (#6415)
[._.]/ Adam Eivy557d67f0b513
diff --git a/client/src/components/universe/CastIntegrityPanel.jsx b/client/src/components/universe/CastIntegrityPanel.jsxindex fe00468396..070b6ecc82 100644--- a/client/src/components/universe/CastIntegrityPanel.jsx+++ b/client/src/components/universe/CastIntegrityPanel.jsx@@ -37,6 +37,7 @@ import {REVIEW_STATUS_META,castIntegrityPassed,findingIsRepairable,+ humanizeIntegrityField,incompleteCoverage,} from '../../lib/characterIntegrity';@@ -56,12 +57,6 @@ const Badge = ({ tone, children, title }) => (</span>);-/** `psychology.drives.status.fear` → `Psychology › drives › status › fear`. */-const humanizeField = (field) => field- .split('.')- .map((part) => part.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()).trim())- .join(' › ');-export default function CastIntegrityPanel({ open, universeId, onClose, onUniverseChange }) {const mountedRef = useMounted();const [report, setReport] = useState(null);@@ -290,7 +285,7 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniverid={checkboxId}checked={selected.has(f.id)}onChange={() => toggleFinding(f.id)}- aria-label={`Select ${humanizeField(f.field)} on ${f.characterName || f.characterId} for augmentation`}+ aria-label={`Select ${humanizeIntegrityField(f.field)} on ${f.characterName || f.characterId} for augmentation`}className="mt-0.5 accent-port-accent"/>) : <span className="w-3" aria-hidden="true" />}@@ -298,7 +293,7 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver<label htmlFor={meta.repairable ? checkboxId : undefined} className="flex flex-wrap items-center gap-1.5"><span className="text-gray-200">{f.characterName || f.characterId}</span><span className="text-gray-500">·</span>- <span className="text-gray-400 font-mono text-[11px]">{humanizeField(f.field)}</span>+ <span className="text-gray-400 font-mono text-[11px]">{humanizeIntegrityField(f.field)}</span><Badge tone={meta.tone} title={meta.hint}>{meta.label || f.kind}</Badge>{f.dimension ? <Badge tone="slate">{DIMENSION_LABELS[f.dimension] || f.dimension}</Badge> : null}</label>@@ -353,7 +348,7 @@ export default function CastIntegrityPanel({ open, universeId, onClose, onUniver})}className="accent-port-accent"/>- <span className="font-mono text-[11px]">{humanizeField(p.field)}</span>+ <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">diff --git a/client/src/components/writers-room/SyncedReview.jsx b/client/src/components/writers-room/SyncedReview.jsxindex 9dea74666c..5700644f4c 100644--- a/client/src/components/writers-room/SyncedReview.jsx+++ b/client/src/components/writers-room/SyncedReview.jsx@@ -1,12 +1,18 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {- AlertTriangle, Clapperboard, FileText, Image as ImageIcon, Link2, Loader2, RefreshCw, X,+ AlertTriangle, Clapperboard, FileText, Image as ImageIcon, Link2, Loader2, RefreshCw, Users, X,} from 'lucide-react';import { getWritersRoomSyncedReview } from '../../services/apiWritersRoom';import { timeAgo } from '../../utils/formatters';import useMounted from '../../hooks/useMounted';+import {+ DEPTH_META,+ FINDING_KIND_META,+ REVIEW_STATUS_META,+ humanizeIntegrityField,+} from '../../lib/characterIntegrity';-// Phase 4 synchronized review: prose ↔ script ↔ media in three sync'd panes.+// Phase 4 synchronized review: prose ↔ script ↔ media ↔ cast in sync'd panes.// Selecting any item highlights — and scrolls to — what it maps to in the// other panes. The mapping + provenance is assembled server-side// (GET /synced-review); see services/writersRoom/syncedReview.js.@@ -15,10 +21,26 @@ const PANES = [{ key: 'prose', label: 'Prose', icon: FileText },{ key: 'script', label: 'Script', icon: Clapperboard },{ key: 'media', label: 'Media', icon: ImageIcon },+ { key: 'cast', label: 'Cast', icon: Users },];const imgUrl = (ref) => `/data/images/${ref}`;+// The cast block a payload without one reads as. A work whose server predates+// the cast pane, or whose bible is empty, must render the same shape as a+// populated one rather than crashing a pane on a missing key.+const EMPTY_CAST = Object.freeze({+ available: false,+ findings: [],+ coverage: [],+ castCount: 0,+ reviewedCount: 0,+ semanticReviewedCount: 0,+ passed: false,+ staging: Object.freeze({ available: false, stale: false, stagedCount: 0, unstagedCount: 0, unmatchedNames: [] }),+});+const castOf = (data) => data?.cast || EMPTY_CAST;+// Scroll a pane's scroll container so the element tagged with `data-sync-id`// lands near the top, WITHOUT scrolling the whole window (manual scrollTop// rather than scrollIntoView, which walks every scrollable ancestor).@@ -39,24 +61,37 @@ function computeHighlights(data, selection) {const proseIds = new Set();const sceneIds = new Set();const mediaSceneIds = new Set(); // media items are keyed by their source sceneId- if (!data || !selection) return { proseIds, sceneIds, mediaSceneIds };+ const castIds = new Set();+ const highlights = { proseIds, sceneIds, mediaSceneIds, castIds };+ if (!data || !selection) return highlights;+ const sceneCast = (id) => (data.script.scenes.find((s) => s.id === id)?.castCharacterIds || []);if (selection.type === 'prose') {proseIds.add(selection.id);const seg = data.prose.segments.find((s) => s.id === selection.id);(seg?.scriptSceneIds || []).forEach((id) => sceneIds.add(id));(seg?.media || []).forEach((m) => mediaSceneIds.add(m.sceneId));+ (seg?.castCharacterIds || []).forEach((id) => castIds.add(id));} else if (selection.type === 'script') {sceneIds.add(selection.id);const sc = data.script.scenes.find((s) => s.id === selection.id);(sc?.proseSegmentIds || []).forEach((id) => proseIds.add(id));+ (sc?.castCharacterIds || []).forEach((id) => castIds.add(id));if (sc?.media) mediaSceneIds.add(selection.id);} else if (selection.type === 'media') {mediaSceneIds.add(selection.id);const item = data.media.items.find((m) => m.sceneId === selection.id);(item?.proseSegmentIds || []).forEach((id) => proseIds.add(id));- if (item && !item.orphan) sceneIds.add(selection.id);+ if (item && !item.orphan) {+ sceneIds.add(selection.id);+ sceneCast(selection.id).forEach((id) => castIds.add(id));+ }+ } else if (selection.type === 'cast') {+ castIds.add(selection.id);+ const row = castOf(data).coverage.find((c) => c.characterId === selection.id);+ (row?.scriptSceneIds || []).forEach((id) => sceneIds.add(id));+ (row?.proseSegmentIds || []).forEach((id) => proseIds.add(id));}- return { proseIds, sceneIds, mediaSceneIds };+ return highlights;}// The id the selection anchors on within `paneType`, or null when the selection@@ -97,6 +132,7 @@ export default function SyncedReview({ work }) {const proseRef = useRef(null);const scriptRef = useRef(null);const mediaRef = useRef(null);+ const castRef = useRef(null);// Derived (not stored) so disabling the active pane on desktop can't leave the// narrow layout pointing at a pane that is no longer rendered.@@ -120,10 +156,22 @@ export default function SyncedReview({ work }) {refresh();}, [refresh]);- const { proseIds, sceneIds, mediaSceneIds } = useMemo(+ const { proseIds, sceneIds, mediaSceneIds, castIds } = useMemo(() => computeHighlights(data, selection),[data, selection],);+ const cast = castOf(data);+ // Findings grouped by character so a coverage row renders its own evidence.+ const findingsByCharacter = useMemo(() => {+ const map = new Map();+ for (const finding of cast.findings) {+ const own = map.get(finding.characterId) || [];+ own.push(finding);+ map.set(finding.characterId, own);+ }+ return map;+ }, [cast]);+ const castGapCount = cast.coverage.filter((row) => row.findingCount > 0).length;// Resolve prose segment ids → headings for provenance labels.const segHeading = useMemo(() => {@@ -141,7 +189,8 @@ export default function SyncedReview({ work }) {if (selection.type !== 'prose' && proseIds.size) scrollPaneTo(proseRef.current, [...proseIds][0]);if (selection.type !== 'script' && sceneIds.size) scrollPaneTo(scriptRef.current, [...sceneIds][0]);if (selection.type !== 'media' && mediaSceneIds.size) scrollPaneTo(mediaRef.current, [...mediaSceneIds][0]);- }, [selection, data, proseIds, sceneIds, mediaSceneIds, activePane]);+ if (selection.type !== 'cast' && castIds.size) scrollPaneTo(castRef.current, [...castIds][0]);+ }, [selection, data, proseIds, sceneIds, mediaSceneIds, castIds, activePane]);const select = useCallback((type, id) => {setSelection((prev) => (prev && prev.type === type && prev.id === id ? null : { type, id }));@@ -169,7 +218,9 @@ export default function SyncedReview({ work }) {const hasSelection = !!selection;const visibleCount = [...visible].length;- const colClass = visibleCount === 1 ? 'lg:grid-cols-1' : visibleCount === 2 ? 'lg:grid-cols-2' : 'lg:grid-cols-3';+ const colClass = visibleCount === 1 ? 'lg:grid-cols-1'+ : visibleCount === 2 ? 'lg:grid-cols-2'+ : visibleCount === 3 ? 'lg:grid-cols-3' : 'lg:grid-cols-4';// Every pane renders; below `lg` all but the active one are display:none.const paneClass = (key) => `${key === activePane ? '' : 'hidden'} lg:block`;@@ -237,6 +288,23 @@ export default function SyncedReview({ work }) {))}</div>+ {cast.available && (+ <button+ type="button"+ onClick={() => showPane('cast')}+ className={`flex items-center gap-1 text-[10px] rounded px-1.5 py-0.5 border ${+ castGapCount > 0+ ? 'text-port-warning border-port-warning/40 hover:bg-port-warning/10'+ : 'text-gray-400 border-port-border hover:text-gray-200'+ }`}+ title={castGapCount > 0+ ? `${castGapCount} of ${cast.castCount} characters have unauthored framework fields — open the Cast pane.`+ : 'Every framework field is authored — which is not the same as the cast holding together. No model has read it. Open the Cast pane.'}+ >+ <Users size={10} /> {castGapCount > 0 ? `${castGapCount} cast gap${castGapCount === 1 ? '' : 's'}` : 'cast fields filled'}+ </button>+ )}+{data.script.stale && (<span className="flex items-center gap-1 text-[10px] text-port-warning border border-port-warning/40 rounded px-1.5 py-0.5" title="The draft changed after this script was generated — re-run Adapt to refresh the mapping."><AlertTriangle size={10} /> Script is stale@@ -311,6 +379,18 @@ export default function SyncedReview({ work }) {onSelect={(sceneId) => select('media', sceneId)}/>)}+ {visible.has('cast') && (+ <CastPane+ className={paneClass('cast')}+ containerRef={castRef}+ cast={cast}+ findingsByCharacter={findingsByCharacter}+ castIds={castIds}+ selectedId={selectedIdFor(selection, 'cast')}+ hasSelection={hasSelection}+ onSelect={(id) => select('cast', id)}+ />+ )}</div>)}</div>@@ -455,3 +535,113 @@ function MediaPane({ containerRef, className, items, mediaSceneIds, selectedId,</ScrollPane>);}++// ---- Cast pane ----+//+// The author-knowledge half of the review, kept visibly apart from the cold+// read beside it (see services/writersRoom/syncedReview.js):+// - **Findings** are measured against the AUTHORED bible only. A character+// the prose stages vividly still reports every unauthored field — an+// interior that lives only in the author's head is the defect, not the fix.+// - **Staged in** is what the script extraction saw, labelled as such. It+// never closes a finding, and an unstaged character is reported as a fact+// rather than flagged: writing someone who stays offstage is a choice.+// - **Named only in the script** lists cold-read names with no bible entry.+// They are not findings — there is no record to hang a field path on.+//+// Nothing here calls a provider, and the deterministic sweep alone never reads+// as a clean pass: the footer says so explicitly rather than leaving a cast+// with no gaps looking reviewed.+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 }) {+ const { staging } = cast;+ return (+ <ScrollPane containerRef={containerRef} className={className} paneKey="cast" icon={Users} label="Cast" count={cast.castCount}>+ {!cast.available ? (+ <div className="p-4 text-[11px] text-gray-500 text-center">+ No characters in this work’s bible yet — add them from the Cast panel, or run “Characters” to extract them from the draft.+ </div>+ ) : (+ <div className="p-3 space-y-2">+ {cast.coverage.map((row) => {+ const state = cardState(row.characterId === selectedId, castIds.has(row.characterId), hasSelection);+ 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) || [];+ 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'}+ </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>+ )}+ </button>+ );+ })}++ {staging.unmatchedNames.length > 0 && (+ <div className="rounded border border-port-border bg-port-card/40 px-3 py-2">+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Named only in the script</div>+ <div className="text-[10px] text-gray-400">{staging.unmatchedNames.join(', ')}</div>+ <div className="text-[9px] text-gray-600 mt-1">+ The scene extraction found these on the page but the bible has no entry for them. Add them to the Cast panel if they matter.+ </div>+ </div>+ )}++ <p className="text-[9px] text-gray-600 leading-snug pt-1">+ Deterministic pass only — no model has read this cast, so nothing here is a clean bill of health.+ {staging.stale && ' The draft changed after this script was generated, so the “staged in” counts are out of date.'}+ </p>+ </div>+ )}+ </ScrollPane>+ );+}diff --git a/client/src/components/writers-room/SyncedReview.test.jsx b/client/src/components/writers-room/SyncedReview.test.jsxindex 218a9bbdaf..d8754510a7 100644--- a/client/src/components/writers-room/SyncedReview.test.jsx+++ b/client/src/components/writers-room/SyncedReview.test.jsx@@ -202,3 +202,112 @@ describe('SyncedReview', () => {expect(await screen.findByText(/run .*Adapt/i)).toBeTruthy();});});++// ---- cast pane (#6415 / #6417) ----++function castPayload(overrides = {}) {+ const base = payload();+ return payload({+ prose: {+ segments: base.prose.segments.map((seg, i) => ({ ...seg, castCharacterIds: i === 0 ? ['wr-char-hero'] : [] })),+ },+ script: { ...base.script, scenes: base.script.scenes.map((sc) => ({ ...sc, castCharacterIds: ['wr-char-hero'] })) },+ cast: {+ available: true,+ castCount: 2,+ reviewedCount: 2,+ semanticReviewedCount: 0,+ passed: false,+ findings: [+ {+ id: 'wr-char-hero::missing::lie', characterId: 'wr-char-hero', characterName: 'Hero',+ kind: 'missing', field: 'psychology.drives.status.fear', dimension: null,+ evidence: 'The status drive has no fear.', suggestion: '',+ },+ ],+ coverage: [+ {+ characterId: 'wr-char-hero', characterName: 'Hero', depth: 'full', status: 'findings',+ findingCount: 1, semanticReviewed: false, staged: true,+ scriptSceneIds: ['scene-01'], proseSegmentIds: ['seg-001'],+ },+ {+ characterId: 'wr-char-aunt', characterName: 'Offstage Aunt', depth: 'light', status: 'passed',+ findingCount: 0, semanticReviewed: false, staged: false,+ scriptSceneIds: [], proseSegmentIds: [],+ },+ ],+ staging: {+ available: true, stale: false, stagedCount: 1, unstagedCount: 1,+ unmatchedNames: ['The Ferryman'],+ },+ ...overrides,+ },+ });+}++describe('SyncedReview — cast pane', () => {+ it('opens the cast pane from the toolbar gap chip and lists findings by field path', async () => {+ getWritersRoomSyncedReview.mockResolvedValue(castPayload());+ render(<SyncedReview work={work} />);+ fireEvent.click(await screen.findByText(/1 cast gap/));+ expect(await screen.findByText('Hero')).toBeTruthy();+ expect(screen.getByText(/Psychology › Drives › Status › Fear/)).toBeTruthy();+ expect(screen.getByText(/The status drive has no fear/)).toBeTruthy();+ });++ it('never presents the deterministic sweep as a clean bill of health', async () => {+ getWritersRoomSyncedReview.mockResolvedValue(castPayload({ findings: [], coverage: [] }));+ render(<SyncedReview work={work} />);+ fireEvent.click(await screen.findByText(/cast fields filled/));+ expect(await screen.findByText(/no model has read this cast/i)).toBeTruthy();+ });++ it('keeps the cold read separate from author knowledge', async () => {+ getWritersRoomSyncedReview.mockResolvedValue(castPayload());+ render(<SyncedReview work={work} />);+ fireEvent.click(await screen.findByText(/1 cast gap/));+ // A script-only name is reported as such, never as a finding.+ expect(await screen.findByText(/Named only in the script/)).toBeTruthy();+ expect(screen.getByText('The Ferryman')).toBeTruthy();+ // An unstaged authored character is a fact, not a defect.+ expect(screen.getByText(/not staged in the script/)).toBeTruthy();+ expect(screen.getByText('Offstage Aunt')).toBeTruthy();+ });++ it('cross-links a character to the scenes and prose segments that stage them', async () => {+ getWritersRoomSyncedReview.mockResolvedValue(castPayload());+ const { container } = render(<SyncedReview work={work} />);+ fireEvent.click(await screen.findByText(/1 cast gap/));+ const card = (pane, syncId) => container.querySelector(`[data-pane="${pane}"] [data-sync-id="${syncId}"]`);+ fireEvent.click(await screen.findByText('Hero'));+ await waitFor(() => expect(card('cast', 'wr-char-hero').getAttribute('aria-pressed')).toBe('true'));+ expect(card('script', 'scene-01').className).toMatch(/border-port-accent\/50/);+ expect(card('prose', 'seg-001').className).toMatch(/border-port-accent\/50/);+ // Selecting the prose segment highlights the character it stages.+ fireEvent.click(card('prose', 'seg-001'));+ await waitFor(() => expect(card('cast', 'wr-char-hero').className).toMatch(/border-port-accent\/50/));+ });++ 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: [] },+ coverage: [{+ characterId: 'wr-char-hero', characterName: 'Hero', depth: 'full', status: 'passed',+ findingCount: 0, semanticReviewed: false, staged: false, scriptSceneIds: [], proseSegmentIds: [],+ }],+ findings: [],+ }));+ render(<SyncedReview work={work} />);+ fireEvent.click(await screen.findByText(/cast fields filled/));+ expect(await screen.findByText(/staging unknown/)).toBeTruthy();+ });++ it('hides the cast chip entirely for a work with no character bible', async () => {+ getWritersRoomSyncedReview.mockResolvedValue(payload());+ render(<SyncedReview work={work} />);+ await screen.findByText('The hero wakes.');+ expect(screen.queryByText(/cast gap/)).toBeNull();+ expect(screen.queryByText(/cast fields filled/)).toBeNull();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6c61513ac9..86c3b79032 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -52,7 +52,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |-| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — the finding kinds, review statuses and dimension ids mirrored from `server/lib/characterIntegrity.js` (guarded by `characterIntegrity.mirror.test.js`), plus `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy, `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `castIntegrityPassed` and `incompleteCoverage`. |+| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — the finding kinds, review statuses and dimension ids mirrored from `server/lib/characterIntegrity.js` (guarded by `characterIntegrity.mirror.test.js`), plus `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy, `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `castIntegrityPassed`, `incompleteCoverage` and `humanizeIntegrityField` (a dotted field path rendered for a reader). || `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. || `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |diff --git a/client/src/lib/characterIntegrity.js b/client/src/lib/characterIntegrity.jsindex c4bd248f7b..1900e878fd 100644--- a/client/src/lib/characterIntegrity.js+++ b/client/src/lib/characterIntegrity.js@@ -91,3 +91,12 @@ export const castIntegrityPassed = (report) => {/** Coverage rows that keep the report from being a clean pass, for the summary line. */export const incompleteCoverage = (report) =>(report?.coverage || []).filter((c) => INCOMPLETE_REVIEW_STATUSES.includes(c.status));++/**+ * `psychology.drives.status.fear` → `Psychology › Drives › Status › Fear`.+ * Shared so every surface that lists findings names a field path the same way.+ */+export const humanizeIntegrityField = (field) => String(field || '')+ .split('.')+ .map((part) => part.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()).trim())+ .join(' › ');diff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdindex a8f3862e8b..e7e10aa522 100644--- a/docs/features/writers-room.md+++ b/docs/features/writers-room.md@@ -87,9 +87,12 @@ The mapping model is a **relational read-model derived on request** rather than- Prose segments come from the active draft's `segmentIndex`.- Script scenes come from the latest `script` analysis, whose scenes carry `sourceSegmentIds` back-references.- Media comes from the analysis snapshot's scene-image map.+- Cast integrity comes from the per-work character bible, measured by the shared `server/lib/characterIntegrity.js` contract (#6415) and joined to the scenes that stage each character.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.+## FederationWriters Room content syncs across peers: record kinds `writersRoomWork`, `writersRoomFolder`, and `writersRoomExercise` (`syncLogic.js`) map to the sync categories `writersRoomWorks`/`writersRoomFolders`/`writersRoomExercises` registered in `server/lib/schemaVersions.js`, with per-record peer-sync push (#1565/#1645). `local.js` emits record events through `sharing/recordEvents.js`; draft `.md` bodies ride a dedicated `draftBodyManifest` lane on work pushes (SHA256 per draft), while scene images sync through the work's linked media collection's asset path rather than the Writers Room records themselves. Conflict-restore handlers cover exercises and bodyless records.diff --git a/server/services/writersRoom/syncedReview.js b/server/services/writersRoom/syncedReview.jsindex 41cd6253cd..9aff17dd5c 100644--- a/server/services/writersRoom/syncedReview.js+++ b/server/services/writersRoom/syncedReview.js@@ -7,6 +7,9 @@* - script scenes ← the `script` analysis snapshot's `result.scenes[]`,* each carrying `sourceSegmentIds` back to prose* - media refs ← the same snapshot's `sceneImages` map (scene → image)+ * - cast integrity ← the per-work character bible, measured by the shared+ * characterIntegrity.js contract and joined to the+ * scenes that stage each character (#6415/#6417)** Deriving on read (instead of a persisted render-plan store) means there is no* second source of truth to keep in sync, and staleness falls straight out of@@ -22,8 +25,11 @@* exactly these cross-references.*/+import { buildCastIntegrityReport, castIntegrityPassed } from '../../lib/characterIntegrity.js';+import { normalizeBibleName } from '../../lib/storyBible.js';import { getWorkWithBody } from './local.js';import { getAnalysis } from './evaluator.js';+import { listCharacters } from './characters.js';import { assertValidWorkId } from './_shared.js';const SCRIPT_ANALYSIS_ID = 'script';@@ -61,13 +67,134 @@ function buildMediaItem(sceneId, img, sceneById) {};}+/** normalized name/alias → character id, so a scene's cast names resolve to bible ids. */+function castNameIndex(characters) {+ const index = new Map();+ for (const entry of characters) {+ if (!entry?.id) continue;+ const names = [entry.name, ...(Array.isArray(entry.aliases) ? entry.aliases : [])];+ for (const name of names) {+ const key = normalizeBibleName(name);+ // First writer wins: two characters sharing an alias must not make the+ // later one silently steal every scene from the earlier one.+ if (key && !index.has(key)) index.set(key, entry.id);+ }+ }+ return index;+}++/**+ * Cast integrity for the synced review (#6415, and the remaining half of #6417).+ *+ * The synced review is the one Writers Room surface where a COLD READ of the+ * draft (the `script` analysis, which derives scenes and their speaking cast+ * from the prose alone) sits beside AUTHOR KNOWLEDGE (the per-work character+ * bible, which holds the framework the reader never sees). Reporting cast+ * integrity here is what lets the author see the two disagree.+ *+ * The two are deliberately kept apart, in both directions:+ *+ * - **Script evidence never closes a framework gap.** The integrity findings+ * are measured by `buildCastIntegrityReport` against the AUTHORED record+ * only. A character who is vividly on the page and blank in the bible still+ * reports every gap — an interior that exists only in the author's head is+ * exactly the defect this contract was written for.+ * - **The bible never invents a scene, and the cold read never invents a+ * character.** A name the extraction found that matches no bible entry is+ * reported as `unmatchedNames`, NOT as a finding: the report has no record+ * to attach a field path to, and inventing one would be the same failure as+ * inventing a field. Symmetrically, an authored character no scene stages is+ * reported `staged: false` and is NOT a finding — an offstage character is a+ * legitimate authoring choice, not an integrity defect.+ *+ * Zero provider calls, exactly like every other pane here: this is the+ * deterministic completeness pass plus a join against scenes that already+ * exist. The semantic pass is an explicitly-invoked action elsewhere, so+ * `semanticReviewedCount` is 0 and `passed` is false by construction — a+ * deterministic pass alone never licenses "this cast is clean".+ */++/**+ * Assemble the cast block described above. No I/O.+ *+ * Reads the already-derived scenes (which carry their validated+ * `proseSegmentIds`) rather than re-deriving the mapping, and stamps each one+ * with the `castCharacterIds` its cold-read names resolved to, so the script+ * pane can cross-highlight without a second join on the client.+ */+function buildCastPane({ characters, scenes, scriptAvailable, scriptStale }) {+ const cast = characters.filter((c) => c?.id);+ const index = castNameIndex(cast);+ const sceneIdsByCharacter = new Map();+ const proseIdsByCharacter = new Map();+ const unmatched = new Map();++ for (const scene of scenes) {+ const resolved = [];+ for (const name of scene.characters) {+ const key = normalizeBibleName(name);+ const characterId = index.get(key);+ if (!characterId) {+ // Keep the first spelling the extraction used rather than the lowercased+ // key — the author is going to read this name and add the character.+ if (key && !unmatched.has(key)) unmatched.set(key, String(name).trim());+ continue;+ }+ if (resolved.includes(characterId)) continue;+ resolved.push(characterId);+ const sceneIds = sceneIdsByCharacter.get(characterId) || [];+ sceneIds.push(scene.id);+ sceneIdsByCharacter.set(characterId, sceneIds);+ const proseIds = proseIdsByCharacter.get(characterId) || new Set();+ for (const segId of scene.proseSegmentIds) proseIds.add(segId);+ proseIdsByCharacter.set(characterId, proseIds);+ }+ scene.castCharacterIds = resolved;+ }++ const report = buildCastIntegrityReport(cast);+ const coverage = report.coverage.map((row) => {+ const sceneIds = sceneIdsByCharacter.get(row.characterId) || [];+ return {+ ...row,+ // The cold read's view of this character, kept as its own field so it can+ // never be mistaken for part of the authored assessment above.+ staged: sceneIds.length > 0,+ scriptSceneIds: sceneIds,+ proseSegmentIds: [...(proseIdsByCharacter.get(row.characterId) || [])],+ };+ });++ return {+ available: cast.length > 0,+ findings: report.findings,+ coverage,+ castCount: report.castCount,+ reviewedCount: report.reviewedCount,+ semanticReviewedCount: report.semanticReviewedCount,+ // Always false here — see the module note. Carried explicitly so a consumer+ // reads the contract's answer rather than inferring one from `findings`.+ passed: castIntegrityPassed(report),+ staging: {+ // Without a script analysis nothing is staged, and that is not evidence+ // the cast is absent from the page — it is evidence nobody has looked.+ available: scriptAvailable,+ // The join is only as fresh as the script it joined against.+ stale: scriptStale,+ stagedCount: coverage.filter((row) => row.staged).length,+ unstagedCount: coverage.filter((row) => !row.staged).length,+ unmatchedNames: [...unmatched.values()],+ },+ };+}+/*** Pure assembler — no I/O. Given the work manifest, the active draft body, and* the (possibly absent / failed) `script` analysis snapshot, produce the full* synced-review payload. Kept pure so the mapping logic is unit-testable* without touching the filesystem.*/-export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null }) {+export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null, characters = [] }) {const { draftVersionId, contentHash, segmentIndex } = activeDraftMeta(manifest);const text = String(body || '');@@ -84,6 +211,7 @@ export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null }// filled in below once we know which scenes map back to each segmentscriptSceneIds: [],media: [],+ castCharacterIds: [],}));const proseSegmentIds = new Set(proseSegments.map((s) => s.id));const proseById = new Map(proseSegments.map((s) => [s.id, s]));@@ -139,6 +267,26 @@ export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null }&& !!contentHash&& scriptAnalysis.sourceContentHash !== contentHash;+ // Cast integrity last: it joins the authored bible against the scenes above,+ // and stamps each scene with the bible ids its cold-read names resolved to.+ const cast = buildCastPane({+ characters: Array.isArray(characters) ? characters : [],+ scenes,+ scriptAvailable: available,+ scriptStale: stale,+ });+ // Mirror scene → cast onto prose, so selecting a segment can highlight the+ // characters the script says it stages.+ for (const scene of scenes) {+ for (const segId of scene.proseSegmentIds) {+ const seg = proseById.get(segId);+ if (!seg) continue;+ for (const characterId of scene.castCharacterIds) {+ if (!seg.castCharacterIds.includes(characterId)) seg.castCharacterIds.push(characterId);+ }+ }+ }+return {workId: manifest?.id || null,title: manifest?.title || null,@@ -159,20 +307,27 @@ export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null }scenes,},media: { items: mediaItems },+ cast,};}/**- * Orchestrator — load the work + active body + script analysis and assemble the- * synced-review read-model. A missing script analysis (never run, or a fresh- * work) is a normal empty state, not an error.+ * Orchestrator — load the work + active body + script analysis + cast bible and+ * assemble the synced-review read-model. A missing script analysis (never run,+ * or a fresh work) is a normal empty state, not an error.+ *+ * The cast bible is a local file read, not a provider call — opening the review+ * still starts no AI work.*/export async function getSyncedReview(workId) {assertValidWorkId(workId);const { manifest, body } = await getWorkWithBody(workId);- const scriptAnalysis = await getAnalysis(workId, SCRIPT_ANALYSIS_ID).catch((err) => {- if (err?.code === 'NOT_FOUND') return null;- throw err;- });- return buildSyncedReview({ manifest, body, scriptAnalysis });+ const [scriptAnalysis, characters] = await Promise.all([+ getAnalysis(workId, SCRIPT_ANALYSIS_ID).catch((err) => {+ if (err?.code === 'NOT_FOUND') return null;+ throw err;+ }),+ listCharacters(workId),+ ]);+ return buildSyncedReview({ manifest, body, scriptAnalysis, characters });}diff --git a/server/services/writersRoom/syncedReview.test.js b/server/services/writersRoom/syncedReview.test.jsindex 4021b3a5f1..84e7e43638 100644--- a/server/services/writersRoom/syncedReview.test.js+++ b/server/services/writersRoom/syncedReview.test.js@@ -150,3 +150,150 @@ describe('buildSyncedReview — media pane & provenance', () => {expect(out.script.scenes[0].media).toBeNull();});});++// ---- cast integrity (#6415 / #6417) ----++// A fully authored lead: every framework field plus a complete psychology+// profile, so the deterministic pass has nothing to report about it.+const COMPLETE_PSYCHOLOGY = {+ theoryOfControl: 'If I am the one who strikes first, nobody gets to leave me.',+ strategy: 'Pre-empt every goodbye with a fight.',+ protectiveBenefit: 'Never has to hear the words out loud.',+ presentCost: 'Burns every alliance before it can hold weight.',+ testingPressure: 'A partner who refuses to fight back.',+ candidateChange: 'Stays in the room through one argument.',+ assessment: 'assessed',+ assessmentNote: '',+ drives: {+ survival: { desire: 'A locked door of her own', fear: 'Sleeping where she can be reached' },+ connection: { desire: 'One person who stays', fear: 'Being the one who is left' },+ status: { desire: 'To be the one who decides', fear: 'Being spoken about as a burden' },+ },+};++const hero = (overrides = {}) => ({+ id: 'wr-char-hero',+ name: 'Hero',+ aliases: ['The Kid'],+ role: 'protagonist',+ arcType: 'positive',+ motivations: 'Get her brother out of the valley before winter.',+ ghost: 'Her mother walked out during a blizzard.',+ wound: 'Nobody came back for her.',+ lie: 'Anyone who can leave will.',+ need: 'To let someone stay.',+ want: 'A house with a door that locks.',+ secrets: ['She sold the last horse.'],+ psychology: COMPLETE_PSYCHOLOGY,+ ...overrides,+});++const build = (characters, { scriptAnalysis = makeScriptAnalysis() } = {}) =>+ buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis, characters });++describe('buildSyncedReview — cast integrity', () => {+ it('reports authored gaps by character id and field path, with evidence', () => {+ const out = build([{ id: 'wr-char-thin', name: 'Hero', role: 'protagonist' }]);+ const fields = out.cast.findings.map((f) => f.field);+ expect(out.cast.available).toBe(true);+ expect(fields).toContain('lie');+ expect(fields).toContain('psychology');+ for (const finding of out.cast.findings) {+ expect(finding.characterId).toBe('wr-char-thin');+ expect(finding.kind).toBe('missing');+ expect(finding.evidence).toBeTruthy();+ }+ });++ it('never reports a clean pass from the deterministic sweep alone', () => {+ const out = build([hero()]);+ expect(out.cast.findings).toHaveLength(0);+ expect(out.cast.coverage[0].status).toBe('passed');+ // Fully populated is NOT integrity — no model has read this cast.+ expect(out.cast.coverage[0].semanticReviewed).toBe(false);+ expect(out.cast.semanticReviewedCount).toBe(0);+ expect(out.cast.passed).toBe(false);+ });++ it('holds a declared minor role to the lighter depth instead of the full framework', () => {+ const out = build([{ id: 'wr-char-guard', name: 'Gate Guard', role: 'minor background guard' }]);+ const [row] = out.cast.coverage;+ expect(row.depth).toBe('light');+ // Light asks for the conscious pursuit only — never a Ghost or a Wound.+ const fields = out.cast.findings.map((f) => f.field);+ expect(fields).toEqual(['motivations', 'want']);+ });++ it('asks nothing further of an interior the author explicitly ruled out', () => {+ const out = build([{+ id: 'wr-char-oracle',+ name: 'The Oracle',+ psychology: { assessment: 'not-applicable', assessmentNote: 'Deliberately unknowable; the reader never gets inside.' },+ }]);+ expect(out.cast.coverage[0].depth).toBe('explained');+ expect(out.cast.findings).toHaveLength(0);+ });++ it('joins each character to the scenes and prose segments that stage them, by name or alias', () => {+ const analysis = makeScriptAnalysis();+ analysis.result.scenes[1].characters = ['The Kid'];+ const out = build([hero()], { scriptAnalysis: analysis });+ const [row] = out.cast.coverage;+ expect(row.staged).toBe(true);+ expect(row.scriptSceneIds).toEqual(['scene-01', 'scene-02']);+ expect(row.proseSegmentIds).toEqual(['seg-001', 'seg-002']);+ // Mirrored onto both other panes so a selection can cross-highlight.+ expect(out.script.scenes[0].castCharacterIds).toEqual(['wr-char-hero']);+ expect(out.prose.segments[0].castCharacterIds).toEqual(['wr-char-hero']);+ });++ it('keeps the cold read separate from author knowledge in both directions', () => {+ const analysis = makeScriptAnalysis();+ analysis.result.scenes[1].characters = ['The Ferryman'];+ const out = build([hero(), { ...hero(), id: 'wr-char-ghost', name: 'Offstage Aunt', aliases: [] }], {+ scriptAnalysis: analysis,+ });+ // A name only the cold read saw never becomes a finding — there is no+ // record to hang a field path on.+ expect(out.cast.staging.unmatchedNames).toEqual(['The Ferryman']);+ expect(out.cast.findings).toHaveLength(0);+ // An authored character no scene stages is a fact, not a defect.+ const offstage = out.cast.coverage.find((c) => c.characterId === 'wr-char-ghost');+ expect(offstage.staged).toBe(false);+ expect(offstage.status).toBe('passed');+ expect(out.cast.staging.stagedCount).toBe(1);+ expect(out.cast.staging.unstagedCount).toBe(1);+ });++ it('reports gaps for a character the prose stages vividly but the bible leaves blank', () => {+ const out = build([{ id: 'wr-char-hero', name: 'Hero', role: 'protagonist' }]);+ expect(out.cast.coverage[0].staged).toBe(true);+ // Being on the page does not close an authored gap.+ expect(out.cast.findings.length).toBeGreaterThan(0);+ });++ it('marks the staging join stale when the script no longer matches the draft', () => {+ const fresh = build([hero()]);+ expect(fresh.cast.staging).toMatchObject({ available: true, stale: false });+ const drifted = buildSyncedReview({+ manifest: makeManifest({ contentHash: 'hash-new' }),+ body: BODY,+ scriptAnalysis: makeScriptAnalysis(),+ characters: [hero()],+ });+ expect(drifted.cast.staging.stale).toBe(true);+ });++ it('reports an empty bible as unavailable rather than as a clean cast', () => {+ const out = build([]);+ expect(out.cast.available).toBe(false);+ expect(out.cast.castCount).toBe(0);+ expect(out.cast.passed).toBe(false);+ });++ it('does not stage anybody when no script analysis has run', () => {+ const out = build([hero()], { scriptAnalysis: null });+ expect(out.cast.staging).toMatchObject({ available: false, stagedCount: 0 });+ expect(out.cast.coverage[0].staged).toBe(false);+ });+});