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: author the five-stage character evolution lens in the FableLoom plan and series arc editors (#6441)

[._.]/ Adam Eivy7e2591213468
diff --git a/client/src/components/character/CharacterEvolutionLens.jsx b/client/src/components/character/CharacterEvolutionLens.jsx
new file mode 100644
index 0000000000..eedca34810
--- /dev/null
+++ b/client/src/components/character/CharacterEvolutionLens.jsx
@@ -0,0 +1,312 @@
+/**
+ * The OPTIONAL five-stage character evolution lens, as an editor (#6441).
+ *
+ * ONE component for both authoring surfaces — the FableLoom series plan's
+ * "Cast evolution" section and the Pipeline series character-arc cards —
+ * because the lens shape is shared and a second hand-written copy would drift
+ * the moment a stage field or an anchor vocabulary moved. What differs between
+ * the hosts is only which evidence anchors they own, and that already has a
+ * single source of truth in `EVOLUTION_EVIDENCE_FIELDS`; the `host` prop
+ * selects which anchor row to render.
+ *
+ * Three rules this surface must never break, carried from epic #6418:
+ * - The lens is OPTIONAL and never a gate. Nothing here blocks a save, marks
+ * an unset lens as a defect, or requires a stage before another one.
+ * - A declared `flat-testing` / `tragic-refusal` outcome is a first-class
+ * ending, not a finding — the outcome picker states that in its hint copy
+ * and renders no warning for either.
+ * - World-level psychology (`characters[].psychology`, #6414) is the BASELINE
+ * and is read-only here. It renders as collapsed reference context, and the
+ * only place it can be edited stays `universe/CharacterDetailEditor.jsx`.
+ *
+ * A stale anchor — a pointer to an episode / scene / transition that no longer
+ * resolves — is preserved, marked, and given a one-click clear so it can be
+ * re-picked. It must never silently vanish and must never read as satisfied.
+ */
+
+import { AlertTriangle } from 'lucide-react';
+import FormField from '../ui/FormField';
+import {
+ CHARACTER_EVOLUTION_LIMITS,
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_OUTCOME_HINTS,
+ EVOLUTION_STAGES,
+ EVOLUTION_STAGE_EDITOR_FIELDS,
+ EVOLUTION_STAGE_LABELS,
+ evolutionEvidenceStatus,
+ evolutionStage,
+ patchEvolution,
+ patchEvolutionEvidence,
+ patchEvolutionStage,
+} from '../../lib/characterEvolution.js';
+import { CHARACTER_PSYCHOLOGY_EDITOR_FIELDS } from '../../lib/characterFramework.js';
+
+const inputClass = 'w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm';
+const labelClass = 'block text-[11px] uppercase tracking-wider text-gray-500 mb-1';
+
+const ids = (list) => new Set((list || []).map((item) => item?.id).filter(Boolean));
+
+// Which reference sets the host can resolve an anchor against. Mirrors
+// `characterArcEvidenceRefs` / `fableLoomEvolutionEvidenceRefs` on the server,
+// derived from the option lists the host already hands this editor so the two
+// cannot disagree about what exists.
+const evidenceRefsFor = (host, anchors) => (host === 'fableLoom'
+ ? { episodeIds: ids(anchors?.episodes), sceneKeys: ids(anchors?.scenes) }
+ : { transitionIds: ids(anchors?.transitions) });
+
+/**
+ * The anchor fields of one stage that no longer resolve, as a clearing patch.
+ * Asked field-by-field rather than by reading a list of pointer names here, so
+ * the set of resolvable anchors stays owned by `evolutionEvidenceStatus` — an
+ * authored locator with nothing to resolve against (a free-text scene anchor,
+ * an issue number) never reports stale and is therefore never cleared.
+ */
+const staleAnchorPatch = (evidence, refs) => Object.fromEntries(
+ Object.entries(evidence || {})
+ .filter(([field, value]) => value && evolutionEvidenceStatus({ [field]: value }, refs) === 'stale')
+ .map(([field]) => [field, '']),
+);
+
+/**
+ * A blank-first `<select>` that keeps an unresolvable value visible.
+ *
+ * A stale pointer is not in `options`, so a plain select would render blank and
+ * quietly drop the author's evidence on the next edit. Re-adding it as a
+ * "(missing)" option is what makes the staleness legible at the field itself.
+ */
+function AnchorSelect({ id, label, ariaLabel, value, options, emptyLabel, onChange }) {
+ const missing = Boolean(value) && !options.some((option) => option.id === value);
+ return (
+ <FormField label={label} labelClassName={labelClass}>
+ <select id={id} aria-label={ariaLabel} className={inputClass} value={value} onChange={(event) => onChange(event.target.value)}>
+ <option value="">{emptyLabel}</option>
+ {options.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}
+ {missing ? <option value={value}>{value} (missing)</option> : null}
+ </select>
+ </FormField>
+ );
+}
+
+/**
+ * The universe-level psychology profile as READ-ONLY reference context.
+ * Collapsed by default and explicitly labelled world-level, so an author sees
+ * the baseline the story is testing without this surface ever becoming a second
+ * place that identity can be edited.
+ */
+function UniverseBaseline({ psychology }) {
+ const filled = CHARACTER_PSYCHOLOGY_EDITOR_FIELDS
+ .map((field) => [field.label, String(psychology?.[field.name] || '').trim()])
+ .filter(([, value]) => value);
+ if (!filled.length) return null;
+ return (
+ <details className="rounded border border-port-border/60 bg-port-bg/40 p-2">
+ <summary className="min-h-[32px] cursor-pointer text-[11px] uppercase tracking-wider text-gray-500">
+ Universe baseline (read-only)
+ </summary>
+ <p className="mt-1 text-[11px] text-gray-500">
+ The world-level psychology profile this story puts under test. Edit it in the Universe cast, not here.
+ </p>
+ <dl className="mt-2 space-y-1 text-xs">
+ {filled.map(([label, value]) => (
+ <div key={label}>
+ <dt className="text-[11px] text-gray-500">{label}</dt>
+ <dd className="text-gray-300">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ </details>
+ );
+}
+
+// The anchors this host owns, rendered for one stage. Every control is
+// individually clearable, so an author can drop a single pointer without
+// dismantling the stage.
+function StageEvidence({ host, anchors, idPrefix, stageId, stageLabel, evidence, onPatch }) {
+ const named = (label) => `${stageLabel} — ${label}`;
+ if (host === 'fableLoom') {
+ const episodes = anchors?.episodes || [];
+ const scenes = (anchors?.scenes || [])
+ .filter((scene) => !evidence?.episodeId || scene.episodeId === evidence.episodeId);
+ return (
+ <div className="grid gap-2 sm:grid-cols-2">
+ <AnchorSelect
+ id={`${idPrefix}-${stageId}-episode`}
+ label="Evidence episode"
+ ariaLabel={named('Evidence episode')}
+ value={evidence?.episodeId || ''}
+ options={episodes}
+ emptyLabel="No episode anchor"
+ onChange={(episodeId) => onPatch({ episodeId })}
+ />
+ <AnchorSelect
+ id={`${idPrefix}-${stageId}-scene`}
+ label="Evidence scene"
+ ariaLabel={named('Evidence scene')}
+ value={evidence?.sceneKey || ''}
+ options={scenes}
+ emptyLabel="No scene anchor"
+ onChange={(sceneKey) => onPatch({ sceneKey })}
+ />
+ </div>
+ );
+ }
+ return (
+ <div className="grid gap-2 sm:grid-cols-3">
+ <AnchorSelect
+ id={`${idPrefix}-${stageId}-transition`}
+ label="Evidence beat"
+ ariaLabel={named('Evidence beat')}
+ value={evidence?.transitionId || ''}
+ options={anchors?.transitions || []}
+ emptyLabel="No transition beat"
+ onChange={(transitionId) => onPatch({ transitionId })}
+ />
+ <FormField label="At issue" labelClassName={labelClass}>
+ <input
+ id={`${idPrefix}-${stageId}-issue`}
+ aria-label={named('At issue')}
+ type="number"
+ min={0}
+ max={CHARACTER_EVOLUTION_LIMITS.atIssue}
+ className={inputClass}
+ value={Number.isFinite(evidence?.atIssue) ? evidence.atIssue : ''}
+ placeholder="#"
+ onChange={(event) => {
+ const parsed = parseInt(event.target.value, 10);
+ // Clamp here rather than lean on `max`: on a number input `max` only
+ // fails constraint validation on submit, and this editor has no
+ // <form>, so an unclamped value would reach the wholesale series
+ // PATCH and 400 the entire save (same reason the transition editor
+ // beside it clamps).
+ onPatch({
+ atIssue: Number.isFinite(parsed)
+ ? Math.min(Math.max(parsed, 0), CHARACTER_EVOLUTION_LIMITS.atIssue)
+ : null,
+ });
+ }}
+ />
+ </FormField>
+ <FormField label="Scene anchor" labelClassName={labelClass}>
+ <input
+ id={`${idPrefix}-${stageId}-anchor`}
+ aria-label={named('Scene anchor')}
+ className={inputClass}
+ value={evidence?.atSceneAnchor || ''}
+ maxLength={CHARACTER_EVOLUTION_LIMITS.atSceneAnchor}
+ placeholder="Where in the issue"
+ onChange={(event) => onPatch({ atSceneAnchor: event.target.value })}
+ />
+ </FormField>
+ </div>
+ );
+}
+
+export default function CharacterEvolutionLens({
+ idPrefix, evolution, onChange, host = 'pipelineSeries', anchors, psychology,
+}) {
+ const refs = evidenceRefsFor(host, anchors);
+ const outcomeId = `${idPrefix}-outcome`;
+ const noteId = `${idPrefix}-outcome-note`;
+
+ return (
+ <div className="space-y-3">
+ <p className="text-[11px] text-gray-500">
+ Optional. Five stages of a belief under test — sparse is fine, and a deliberately
+ flat or refused arc is a first-class ending, not a gap. Nothing here gates a save.
+ </p>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <FormField
+ label="Declared outcome"
+ hint={EVOLUTION_OUTCOME_HINTS[evolution?.outcome] || 'Declaring how the arc lands is what stops a review reading it as unfinished.'}
+ labelClassName={labelClass}
+ >
+ <select
+ id={outcomeId}
+ className={inputClass}
+ value={evolution?.outcome || ''}
+ onChange={(event) => onChange(patchEvolution(evolution, { outcome: event.target.value }))}
+ >
+ <option value="">Not declared yet</option>
+ {EVOLUTION_OUTCOMES.map((outcome) => <option key={outcome} value={outcome}>{outcome}</option>)}
+ </select>
+ </FormField>
+ <FormField label="Outcome note" labelClassName={labelClass}>
+ <input
+ id={noteId}
+ className={inputClass}
+ value={evolution?.outcomeNote || ''}
+ maxLength={CHARACTER_EVOLUTION_LIMITS.outcomeNote}
+ placeholder="Why it lands that way"
+ onChange={(event) => onChange(patchEvolution(evolution, { outcomeNote: event.target.value }))}
+ />
+ </FormField>
+ </div>
+
+ <UniverseBaseline psychology={psychology} />
+
+ <ol className="space-y-2">
+ {EVOLUTION_STAGES.map((stageId, index) => {
+ const stage = evolutionStage(evolution, stageId);
+ const stageLabel = EVOLUTION_STAGE_LABELS[stageId];
+ const stale = evolutionEvidenceStatus(stage?.evidence, refs) === 'stale';
+ const patchEvidence = (patch) => onChange(patchEvolutionEvidence(evolution, stageId, patch));
+ return (
+ <li key={stageId} className="rounded border border-port-border p-2 bg-port-bg/40">
+ <div className="flex items-center justify-between gap-2">
+ <h5 className="text-xs font-medium text-gray-300">{index + 1}. {stageLabel}</h5>
+ {stale ? (
+ <span className="flex items-center gap-1 text-[11px] text-port-warning" role="status">
+ <AlertTriangle size={12} /> Stale anchor
+ </span>
+ ) : null}
+ </div>
+ {stale ? (
+ <div className="mt-1 flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/5 p-2">
+ <p className="text-[11px] text-gray-400">
+ This evidence points at something that no longer exists, so the stage stays unproven.
+ </p>
+ <button
+ type="button"
+ className="min-h-[32px] rounded border border-port-warning px-2 text-[11px] text-port-warning hover:bg-port-warning/10"
+ onClick={() => patchEvidence(staleAnchorPatch(stage.evidence, refs))}
+ >
+ Re-pick {stageLabel} anchor
+ </button>
+ </div>
+ ) : null}
+ <div className="mt-2 grid gap-2 sm:grid-cols-2">
+ {EVOLUTION_STAGE_EDITOR_FIELDS.map((field) => (
+ <FormField key={field.name} label={field.label} labelClassName={labelClass}>
+ <textarea
+ id={`${idPrefix}-${stageId}-${field.name}`}
+ aria-label={`${stageLabel} — ${field.label}`}
+ rows={2}
+ className={inputClass}
+ value={stage?.[field.name] || ''}
+ maxLength={field.max}
+ placeholder={field.placeholder}
+ onChange={(event) => onChange(
+ patchEvolutionStage(evolution, stageId, { [field.name]: event.target.value }),
+ )}
+ />
+ </FormField>
+ ))}
+ </div>
+ <div className="mt-2">
+ <StageEvidence
+ host={host}
+ anchors={anchors}
+ idPrefix={idPrefix}
+ stageId={stageId}
+ stageLabel={stageLabel}
+ evidence={stage?.evidence}
+ onPatch={patchEvidence}
+ />
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ </div>
+ );
+}
diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsx
index 551b40b8a0..def97c3e7c 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx
@@ -29,11 +29,14 @@ import { fieldClass, labelClass } from './fieldStyles';
import LoomAiRunStatus from './LoomAiRunStatus';
import LoomEditorialAutomation from './LoomEditorialAutomation';
import { fableLoomPlotPointKind } from '../../../../server/lib/fableLoomOutline.js';
+import CharacterEvolutionLens from '../character/CharacterEvolutionLens';
+import { EVOLUTION_STAGES, isDeclaredEvolution } from '../../lib/characterEvolution.js';
const PLAN_SECTIONS = [
{ id: 'arc', label: 'Story arc' },
{ id: 'challenges', label: 'Plot & challenges' },
{ id: 'quests', label: 'Side quests' },
+ { id: 'cast', label: 'Cast evolution' },
{ id: 'episodes', label: 'Episode outlines' },
{ id: 'editorial', label: 'AI editor' },
{ id: 'handoffs', label: 'Viewer handoffs' },
@@ -57,8 +60,25 @@ const normalizePlan = (plan) => ({
interEpisodeVoicemails: Array.isArray(plan?.interEpisodeVoicemails)
? plan.interEpisodeVoicemails : [],
nextSeasonTeaser: plan?.nextSeasonTeaser || null,
+ // The OPTIONAL five-stage lens per cast member (#6440). Normalized to an
+ // array so the draft round-trips it through the single seriesPlan save; the
+ // save payload drops it again when empty (see planSavePayload).
+ characterEvolutions: Array.isArray(plan?.characterEvolutions) ? plan.characterEvolutions : [],
});
+/**
+ * The plan body the save PATCH actually sends.
+ *
+ * `characterEvolutions` is OMITTED when nothing is authored, so a plan that
+ * never opted into the lens produces a request body byte-identical to the
+ * pre-lens one (the server sanitizer omits the key on exactly that rule). An
+ * absent key on this WHOLESALE-`seriesPlan` PATCH is itself the clear, so
+ * removing the last lens still persists as a clear rather than a no-op.
+ */
+const planSavePayload = ({ characterEvolutions, ...rest }) => (
+ characterEvolutions?.length ? { ...rest, characterEvolutions } : rest
+);
+
const episodeBoundaryKey = (fromEpisodeId, toEpisodeId) => `${fromEpisodeId}::${toEpisodeId}`;
const withVoicemailDrafts = (plan, episodes) => {
@@ -77,7 +97,7 @@ const withVoicemailDrafts = (plan, episodes) => {
});
};
-export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
+export default function LoomSeriesPlan({ loom, universe, onLoomUpdate }) {
const [requestedSection, setSection] = useDrawerTab('section', 'arc', PLAN_SECTIONS.map(({ id }) => id));
const contentRef = useRef(null);
const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));
@@ -136,7 +156,7 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
const [save, saving] = useAsyncAction(async () => {
const submittedRevision = revisionRef.current;
- const updated = await updateLoom(loom.id, { seriesPlan: plan }, { silent: true });
+ const updated = await updateLoom(loom.id, { seriesPlan: planSavePayload(plan) }, { silent: true });
savedRevisionRef.current = submittedRevision;
onLoomUpdate(updated);
setDirty(revisionRef.current > submittedRevision);
@@ -234,6 +254,15 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
/>
</div>
+ <div hidden={requestedSection !== 'cast'} role="tabpanel" aria-labelledby="tab-cast" id="series-section-cast" tabIndex={-1} className="focus:outline-none">
+ <CastEvolutionPlan
+ loom={loom}
+ universe={universe}
+ entries={plan.characterEvolutions}
+ onChange={(characterEvolutions) => changePlan((current) => ({ ...current, characterEvolutions }))}
+ />
+ </div>
+
<div hidden={requestedSection !== 'episodes'} role="tabpanel" aria-labelledby="tab-episodes" id="series-section-episodes">
<EpisodeBeatReadiness loom={loom} />
</div>
@@ -703,6 +732,146 @@ function SeriesDeliveryPlan({ plan, episodes, onChange }) {
);
}
+// Stable per-entry key. The canon `chr-` pointer is the identity the lens is
+// stored under; a name-only entry (a peer that authored one before linking the
+// cast) falls back to its name, and the index keeps two blanks distinct.
+const castEntryKey = (entry, index) => entry.characterId || `name:${entry.characterName || index}`;
+
+/**
+ * "Cast evolution" — one OPTIONAL five-stage lens per cast member, stored in
+ * `seriesPlan.characterEvolutions[]` and saved through the same single
+ * `updateLoom({ seriesPlan })` request as every other plan section, so a lens
+ * edit rides the existing dirty/unsaved-changes affordance instead of racing
+ * its own PATCH.
+ *
+ * Cast members are PICKED from the linked universe, never invented here — the
+ * lens links by canon `chr-` id and denormalizes the name only for display, so
+ * a rename in the universe never orphans the lens. The universe-level
+ * psychology profile rides along as read-only baseline context.
+ */
+function CastEvolutionPlan({ loom, universe, entries, onChange }) {
+ const cast = Array.isArray(universe?.characters) ? universe.characters : [];
+ // Open a just-added card so the lens is ready to author, the same affordance
+ // PlanCollection gives a new plot point.
+ const collectionRef = useRef(null);
+ const previousKeys = useRef(new Set(entries.map(castEntryKey)));
+ useEffect(() => {
+ const keys = entries.map(castEntryKey);
+ const added = keys.find((key) => !previousKeys.current.has(key));
+ previousKeys.current = new Set(keys);
+ if (!added) return;
+ const row = Array.from(collectionRef.current?.querySelectorAll('[data-cast-entry]') || [])
+ .find((element) => element.dataset.castEntry === added);
+ if (row) row.open = true;
+ row?.scrollIntoView?.({ block: 'nearest' });
+ }, [entries]);
+ const episodes = loom.episodes.map((episode) => ({
+ id: episode.id,
+ label: `${episode.number}. ${episode.title || 'Untitled'}`,
+ }));
+ // Outline scene keys resolve loom-wide (matching fableLoomEvolutionEvidenceRefs
+ // on the server), so a key reused across two episodes is ONE anchor — dedupe
+ // it rather than rendering two options that mean the same thing.
+ const scenes = [];
+ const seenSceneKeys = new Set();
+ for (const episode of loom.episodes) {
+ for (const scene of episode.storyOutline?.scenes || []) {
+ if (!scene?.key || seenSceneKeys.has(scene.key)) continue;
+ seenSceneKeys.add(scene.key);
+ scenes.push({ id: scene.key, label: `${episode.number}. ${scene.key}`, episodeId: episode.id });
+ }
+ }
+ const claimed = new Set(entries.map((entry) => entry.characterId).filter(Boolean));
+ const available = cast.filter((character) => !claimed.has(character.id));
+
+ const addCharacter = (characterId) => {
+ const character = cast.find((candidate) => candidate.id === characterId);
+ if (!character) return;
+ onChange([...entries, { characterId: character.id, characterName: character.name || '', evolution: null }]);
+ };
+ const patchEntry = (index, evolution) => onChange(entries
+ .map((entry, i) => (i === index ? { ...entry, evolution } : entry)));
+ const removeEntry = (index) => onChange(entries.filter((_, i) => i !== index));
+ const moveEntry = (index, direction) => {
+ const next = [...entries];
+ const target = index + direction;
+ if (target < 0 || target >= next.length) return;
+ [next[index], next[target]] = [next[target], next[index]];
+ onChange(next);
+ };
+
+ return (
+ <div ref={collectionRef} className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">
+ <div className="flex flex-col sm:flex-row items-start justify-between gap-3">
+ <div>
+ <h3 className="font-semibold">Cast evolution</h3>
+ <p className="text-xs text-port-text-muted mt-1">
+ The belief each cast member has under test, the pressure on it, and what their choices cause.
+ Optional per character — an unset lens changes nothing about the plan.
+ </p>
+ </div>
+ {available.length ? (
+ <FormField label="Add cast member" labelClassName={labelClass} className="w-full sm:w-64 shrink-0">
+ <select
+ id="series-cast-add"
+ className={fieldClass}
+ value=""
+ onChange={(event) => addCharacter(event.target.value)}
+ >
+ <option value="">Pick a character…</option>
+ {available.map((character) => (
+ <option key={character.id} value={character.id}>{character.name || character.id}</option>
+ ))}
+ </select>
+ </FormField>
+ ) : null}
+ </div>
+
+ {!cast.length ? (
+ <p className="text-xs text-port-text-muted">
+ {universe
+ ? 'The linked universe has no cast yet. Add characters there to author their evolution here.'
+ : 'Link a universe to this loom to pick the cast whose evolution you want to plan.'}
+ </p>
+ ) : null}
+
+ {!entries.length ? (
+ <p className="text-xs text-port-text-muted">No character evolution authored yet.</p>
+ ) : entries.map((entry, index) => {
+ const character = cast.find((candidate) => candidate.id === entry.characterId);
+ const name = character?.name || entry.characterName || entry.characterId || 'Unnamed character';
+ const authoredStages = entry.evolution?.stages?.length || 0;
+ return (
+ <details key={castEntryKey(entry, index)} data-cast-entry={castEntryKey(entry, index)} className="rounded border border-port-border p-3">
+ <summary className="min-h-[44px] cursor-pointer text-sm leading-6">
+ <span className="font-medium">{name}</span>
+ <span className="ml-2 text-xs text-port-text-muted">
+ {isDeclaredEvolution(entry.evolution) ? entry.evolution.outcome : 'outcome not declared'}
+ {' · '}{authoredStages}/{EVOLUTION_STAGES.length} stages
+ </span>
+ </summary>
+ <div className="space-y-3 pt-3">
+ <div className="flex justify-end gap-1.5">
+ <button type="button" aria-label={`Move ${name} up`} disabled={index === 0} onClick={() => moveEntry(index, -1)} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-text-muted hover:text-port-text disabled:opacity-30"><ChevronUp size={15} /></button>
+ <button type="button" aria-label={`Move ${name} down`} disabled={index === entries.length - 1} onClick={() => moveEntry(index, 1)} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-text-muted hover:text-port-text disabled:opacity-30"><ChevronDown size={15} /></button>
+ <button type="button" aria-label={`Remove ${name} evolution lens`} onClick={() => removeEntry(index)} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-text-muted hover:text-port-error"><Trash2 size={15} /></button>
+ </div>
+ <CharacterEvolutionLens
+ idPrefix={`series-cast-${entry.characterId || index}`}
+ host="fableLoom"
+ evolution={entry.evolution}
+ anchors={{ episodes, scenes }}
+ psychology={character?.psychology}
+ onChange={(evolution) => patchEntry(index, evolution)}
+ />
+ </div>
+ </details>
+ );
+ })}
+ </div>
+ );
+}
+
function PlanCollection({
title, description, items, episodes, sideQuests = false,
onAdd, onAddChallenge, onUpdate, onRemove, onMove,
diff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
index 7425ccf462..b56aaf8bf7 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.test.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
@@ -292,3 +292,197 @@ describe('LoomSeriesPlan', () => {
));
});
});
+
+// The OPTIONAL five-stage character evolution lens (#6441). Its own fixture so
+// the outline-scene keys and linked cast this section needs stay out of the
+// plan fixture every other test shares.
+const castLoom = (plan = {}) => ({
+ id: 'loom-1',
+ name: 'Example Loom',
+ episodes: [
+ { id: 'ep-1', number: 1, title: 'Pilot', storyOutline: { scenes: [{ key: 'the-blockade' }] } },
+ { id: 'ep-2', number: 2, title: 'Finale', storyOutline: { scenes: [{ key: 'the-cost' }] } },
+ ],
+ seriesPlan: { storyArc: 'An old arc.', plotPoints: [], sideQuests: [], ...plan },
+});
+
+const castUniverse = {
+ id: 'uni-1',
+ characters: [
+ {
+ id: 'chr-1111',
+ name: 'Vale',
+ psychology: { theoryOfControl: 'If I stay useful, nobody leaves.' },
+ },
+ { id: 'chr-2222', name: 'Roan' },
+ ],
+};
+
+const renderCastPlan = (props, entry = '/?section=cast') => render(<RouterProvider router={createMemoryRouter([
+ { path: '/', element: <LoomSeriesPlan universe={castUniverse} onLoomUpdate={vi.fn()} {...props} /> },
+], { initialEntries: [entry] })} />);
+
+const savedPlan = () => api.updateLoom.mock.calls.at(-1)[1].seriesPlan;
+
+describe('LoomSeriesPlan — cast evolution lens', () => {
+ it('deep-links straight to the cast section and offers the linked universe cast', () => {
+ renderCastPlan({ loom: castLoom() });
+
+ expect(screen.getByRole('heading', { name: 'Cast evolution' })).toBeVisible();
+ expect(screen.getByRole('combobox', { name: 'Add cast member' })).toBeVisible();
+ expect(screen.getByText('No character evolution authored yet.')).toBeVisible();
+ });
+
+ it('sends a plan with no lens as a body byte-identical to the pre-lens one', async () => {
+ api.updateLoom.mockResolvedValue(castLoom());
+ renderCastPlan({ loom: castLoom() });
+
+ fireEvent.click(screen.getByRole('tab', { name: 'Story arc' }));
+ fireEvent.change(screen.getByRole('textbox', { name: /story arc/i }), { target: { value: 'A stronger arc.' } });
+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalled());
+ expect(Object.keys(savedPlan())).toEqual([
+ 'storyArc', 'plotPoints', 'sideQuests', 'deliveryOptions', 'interEpisodeVoicemails', 'nextSeasonTeaser',
+ ]);
+ });
+
+ it('authors a full five-stage lens against episode and scene evidence', async () => {
+ const user = userEvent.setup();
+ api.updateLoom.mockResolvedValue(castLoom());
+ renderCastPlan({ loom: castLoom() });
+
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Add cast member' }), 'chr-1111');
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Declared outcome' }), 'full-change');
+ for (const stage of ['control strategy failing', 'pressure forces exploration', 'commitment to change', 'cost tested', 'final proof']) {
+ fireEvent.change(screen.getByRole('textbox', { name: `${stage} — Belief under test` }), {
+ target: { value: `${stage}: usefulness buys safety` },
+ });
+ }
+ await user.selectOptions(screen.getByRole('combobox', { name: 'final proof — Evidence episode' }), 'ep-2');
+ await user.selectOptions(screen.getByRole('combobox', { name: 'final proof — Evidence scene' }), 'the-cost');
+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalled());
+ const [lens] = savedPlan().characterEvolutions;
+ expect(lens).toMatchObject({ characterId: 'chr-1111', characterName: 'Vale' });
+ expect(lens.evolution.outcome).toBe('full-change');
+ expect(lens.evolution.stages.map((s) => s.stageId)).toEqual([
+ 'control-strategy-failing', 'pressure-forces-exploration', 'commitment-to-change', 'cost-tested', 'final-proof',
+ ]);
+ expect(lens.evolution.stages.at(-1).evidence).toMatchObject({ episodeId: 'ep-2', sceneKey: 'the-cost' });
+ });
+
+ it('keeps a sparse lens sparse and treats a declared flat arc as complete, not a defect', async () => {
+ const user = userEvent.setup();
+ api.updateLoom.mockResolvedValue(castLoom());
+ renderCastPlan({ loom: castLoom() });
+
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Add cast member' }), 'chr-2222');
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Declared outcome' }), 'flat-testing');
+ fireEvent.change(screen.getByRole('textbox', { name: 'control strategy failing — External pressure' }), {
+ target: { value: 'The town votes to abandon the relay.' },
+ });
+ fireEvent.change(screen.getByRole('textbox', { name: 'commitment to change — Character choice' }), {
+ target: { value: 'Stays, and changes the vote instead.' },
+ });
+
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /save plan/i })).toBeEnabled();
+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalled());
+ const [lens] = savedPlan().characterEvolutions;
+ expect(lens.evolution.outcome).toBe('flat-testing');
+ expect(lens.evolution.stages.map((s) => s.stageId))
+ .toEqual(['control-strategy-failing', 'commitment-to-change']);
+ });
+
+ it('marks an unresolvable evidence anchor stale and re-picks it in one click', async () => {
+ const user = userEvent.setup();
+ api.updateLoom.mockResolvedValue(castLoom());
+ renderCastPlan({
+ loom: castLoom({
+ characterEvolutions: [{
+ characterId: 'chr-1111',
+ characterName: 'Vale',
+ evolution: {
+ outcome: 'partial-open',
+ outcomeNote: '',
+ stages: [{
+ stageId: 'cost-tested',
+ testedBelief: 'Usefulness buys safety.',
+ externalPressure: '',
+ characterChoice: '',
+ causalConsequence: '',
+ evidence: { atIssue: null, atSceneAnchor: '', transitionId: '', episodeId: 'ep-deleted', sceneKey: '' },
+ }],
+ },
+ }],
+ }),
+ });
+
+ await user.click(screen.getByText('Vale'));
+ expect(screen.getByText('Stale anchor')).toBeVisible();
+ expect(screen.getByRole('combobox', { name: 'cost tested — Evidence episode' }))
+ .toHaveValue('ep-deleted');
+ await user.click(screen.getByRole('button', { name: 'Re-pick cost tested anchor' }));
+
+ expect(screen.queryByText('Stale anchor')).not.toBeInTheDocument();
+ await user.selectOptions(screen.getByRole('combobox', { name: 'cost tested — Evidence episode' }), 'ep-1');
+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalled());
+ expect(savedPlan().characterEvolutions[0].evolution.stages[0].evidence)
+ .toMatchObject({ episodeId: 'ep-1' });
+ });
+
+ it('persists a fully cleared lens as a clear rather than a no-op', async () => {
+ const user = userEvent.setup();
+ api.updateLoom.mockResolvedValue(castLoom());
+ renderCastPlan({
+ loom: castLoom({
+ characterEvolutions: [{
+ characterId: 'chr-1111',
+ characterName: 'Vale',
+ evolution: {
+ outcome: 'tragic-refusal',
+ outcomeNote: 'He never lets go.',
+ stages: [{
+ stageId: 'final-proof',
+ testedBelief: 'Usefulness buys safety.',
+ externalPressure: '',
+ characterChoice: '',
+ causalConsequence: '',
+ evidence: null,
+ }],
+ },
+ }],
+ }),
+ });
+
+ await user.click(screen.getByText('Vale'));
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Declared outcome' }), '');
+ fireEvent.change(screen.getByRole('textbox', { name: 'Outcome note' }), { target: { value: '' } });
+ fireEvent.change(screen.getByRole('textbox', { name: 'final proof — Belief under test' }), { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalled());
+ expect(savedPlan().characterEvolutions[0].evolution).toBeNull();
+ });
+
+ it('shows the universe psychology profile as read-only baseline context', async () => {
+ const user = userEvent.setup();
+ renderCastPlan({
+ loom: castLoom({
+ characterEvolutions: [{ characterId: 'chr-1111', characterName: 'Vale', evolution: null }],
+ }),
+ });
+
+ await user.click(screen.getByText('Vale'));
+ await user.click(screen.getByText('Universe baseline (read-only)'));
+ expect(screen.getByText('Universe baseline (read-only)')).toBeVisible();
+ expect(screen.getByText('If I stay useful, nobody leaves.')).toBeVisible();
+ expect(screen.queryByRole('textbox', { name: /theory of control/i })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 1c36cf70c5..b9a32d1a44 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -51,7 +51,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
| `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. |
-| `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), and adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` and `EVOLUTION_OUTCOME_HINTS` (#6440). |
+| `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |
| `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`, `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. |
diff --git a/client/src/lib/characterEvolution.js b/client/src/lib/characterEvolution.js
index 1bb926a42b..7f533eb550 100644
--- a/client/src/lib/characterEvolution.js
+++ b/client/src/lib/characterEvolution.js
@@ -81,3 +81,92 @@ export const EVOLUTION_OUTCOME_HINTS = Object.freeze({
'flat-testing': 'the belief is tested and deliberately holds — they change the world instead',
'partial-open': 'only part of the change is earned, or the ending leaves it open',
});
+
+// Every anchor field either host can author, derived from the shared per-host
+// table rather than restated, so a sixth anchor lands here for free.
+const ALL_EVIDENCE_FIELDS = Object.freeze([
+ ...new Set(Object.values(EVOLUTION_EVIDENCE_FIELDS).flat()),
+]);
+// `atIssue` is the one numeric anchor; the rest are strings.
+const TEXT_EVIDENCE_FIELDS = ALL_EVIDENCE_FIELDS.filter((field) => field !== 'atIssue');
+
+const asText = (value) => (typeof value === 'string' ? value : '');
+
+/** The authored stage for `stageId`, or `null` — the lens stores stages sparsely. */
+export const evolutionStage = (evolution, stageId) => (
+ (Array.isArray(evolution?.stages) ? evolution.stages : [])
+ .find((stage) => stage?.stageId === stageId) || null
+);
+
+// Mirror of the server's "authored?" rules (`sanitizeEvolutionEvidence` /
+// `sanitizeEvolutionStage` / `sanitizeCharacterEvolution`) so an editor's draft
+// collapses to the same shape the sanitizer would produce. That is what makes a
+// present-but-empty field a REAL clear instead of an empty husk the server then
+// drops on the next save, and what keeps an untouched lens byte-stable across a
+// round trip. Text is kept verbatim (not clause-trimmed) — the caps live on the
+// inputs, and trimming mid-type would fight the author.
+const cleanEvidence = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const evidence = { atIssue: Number.isFinite(raw.atIssue) ? raw.atIssue : null };
+ for (const field of TEXT_EVIDENCE_FIELDS) evidence[field] = asText(raw[field]).trim();
+ const authored = evidence.atIssue !== null
+ || TEXT_EVIDENCE_FIELDS.some((field) => evidence[field]);
+ return authored ? evidence : null;
+};
+
+const cleanStage = (raw) => {
+ if (!EVOLUTION_STAGES.includes(raw?.stageId)) return null;
+ const stage = { stageId: raw.stageId };
+ let authored = false;
+ for (const field of EVOLUTION_STAGE_TEXT_FIELDS) {
+ stage[field] = asText(raw[field]);
+ if (stage[field].trim()) authored = true;
+ }
+ stage.evidence = cleanEvidence(raw.evidence);
+ return authored || stage.evidence ? stage : null;
+};
+
+// A lens with no declared outcome, no note and no stage is nothing at all —
+// returning null (rather than an empty husk) is what lets a host omit the key
+// and keep a never-authored record byte-identical.
+const finishEvolution = (evolution) => (
+ evolution.outcome || evolution.outcomeNote.trim() || evolution.stages.length ? evolution : null
+);
+
+const asEvolution = (raw) => ({
+ outcome: EVOLUTION_OUTCOMES.includes(raw?.outcome) ? raw.outcome : null,
+ outcomeNote: asText(raw?.outcomeNote),
+ stages: (Array.isArray(raw?.stages) ? raw.stages : []).map(cleanStage).filter(Boolean),
+});
+
+/**
+ * Apply a lens-level patch (`outcome` / `outcomeNote`). Returns the next lens,
+ * or `null` once nothing is authored — callers store that `null` verbatim so a
+ * full clear persists as a clear.
+ */
+export const patchEvolution = (evolution, patch) => (
+ finishEvolution(asEvolution({ ...asEvolution(evolution), ...patch }))
+);
+
+/**
+ * Apply a patch to ONE stage, upserting it into canonical stage order and
+ * dropping it again once its prose and anchor are both blank.
+ */
+export function patchEvolutionStage(evolution, stageId, patch) {
+ const base = asEvolution(evolution);
+ const merged = cleanStage({ ...(evolutionStage(base, stageId) || {}), ...patch, stageId });
+ const byStage = new Map(base.stages.map((stage) => [stage.stageId, stage]));
+ if (merged) byStage.set(stageId, merged);
+ else byStage.delete(stageId);
+ return finishEvolution({
+ ...base,
+ stages: EVOLUTION_STAGES.map((id) => byStage.get(id)).filter(Boolean),
+ });
+}
+
+/** Apply a patch to one stage's evidence anchor, merging over what it already holds. */
+export const patchEvolutionEvidence = (evolution, stageId, patch) => patchEvolutionStage(
+ evolution,
+ stageId,
+ { evidence: { ...(evolutionStage(evolution, stageId)?.evidence || {}), ...patch } },
+);
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index b600f9ed83..8efffc723a 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -598,7 +598,7 @@ export default function FableLoomStory({ view = 'graph' }) {
</header>
{seriesPlanOpen ? (
- <LoomSeriesPlan loom={loom} onLoomUpdate={setLoom} />
+ <LoomSeriesPlan loom={loom} universe={linkedUniverse} onLoomUpdate={setLoom} />
) : !episode ? (
<div className="flex-1 grid place-items-center p-8 text-center">
<div>
diff --git a/client/src/pages/PipelineSeries.evolutionLens.test.jsx b/client/src/pages/PipelineSeries.evolutionLens.test.jsx
new file mode 100644
index 0000000000..4f0638a3bf
--- /dev/null
+++ b/client/src/pages/PipelineSeries.evolutionLens.test.jsx
@@ -0,0 +1,147 @@
+/**
+ * The OPTIONAL five-stage evolution lens on a Pipeline series character arc
+ * (#6441). The lens nests inside `series.characterArcs[]`, which already rides
+ * the wholesale bible flush (`ARC_FLUSH_FIELDS`), so the regression worth
+ * pinning here is the AUTHORING behavior — a partial lens stays partial, a
+ * declared flat arc raises nothing, and an anchor that no longer resolves is
+ * marked rather than silently dropped.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import PipelineSeries from './PipelineSeries';
+
+const getPipelineSeries = vi.fn();
+const listPipelineIssues = vi.fn();
+const listUniverses = vi.fn();
+
+vi.mock('../services/api', () => ({
+ getPipelineSeries: (...args) => getPipelineSeries(...args),
+ updatePipelineSeries: vi.fn(),
+ listPipelineIssues: (...args) => listPipelineIssues(...args),
+ listUniverses: (...args) => listUniverses(...args),
+ generateSeriesTitleLogo: vi.fn(),
+ discoverSeriesVoice: vi.fn(),
+ SERIES_TITLE_LOGO_MAX: 1_000,
+}));
+
+vi.mock('../hooks/useArcCanvasSync', () => ({
+ useArcCanvasSync: () => ({
+ updateSeriesFromServer: vi.fn(),
+ handleIssuesUpdate: vi.fn(),
+ flushPending: vi.fn(async () => false),
+ }),
+}));
+vi.mock('../hooks/useLocalStorageBool', () => ({ useLocalStorageBool: () => [false, vi.fn()] }));
+vi.mock('../components/pipeline/ArcCanvas', () => ({ default: () => <div>arc canvas</div> }));
+vi.mock('../components/pipeline/AutopilotPanel', () => ({ default: () => <div>autopilot</div> }));
+vi.mock('../components/pipeline/SeriesReviewPanel', () => ({ default: () => <div>series review</div> }));
+vi.mock('../components/pipeline/SeriesLoomsPanel', () => ({ default: () => <div>branching narratives</div> }));
+vi.mock('../components/CatalogCastPanel', () => ({ default: () => <div>cast</div> }));
+vi.mock('../components/pipeline/AuthorPicker', () => ({ default: () => <div>author</div> }));
+vi.mock('../components/VoiceExemplarEditor', () => ({ default: () => <div>voice exemplars</div>, VOICE_EXEMPLARS_MAX: 5 }));
+vi.mock('../components/imageGen/RecordRenderPinRow', () => ({ default: () => <div>render backend</div> }));
+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const universe = {
+ id: 'uni-1',
+ name: 'Example Universe',
+ characters: [{
+ id: 'chr-1111',
+ name: 'Vale',
+ psychology: { theoryOfControl: 'If I stay useful, nobody leaves.' },
+ }],
+};
+
+const seriesWith = (arc) => ({
+ id: 'series-1',
+ name: 'Example Series',
+ universeId: 'uni-1',
+ characterArcs: [{
+ characterId: 'chr-1111',
+ characterName: 'Vale',
+ want: '', need: '', startState: '', endState: '',
+ transitions: [{ id: 'trn-1111', kind: 'decision', label: 'Stays for the relay', atIssue: 3 }],
+ ...arc,
+ }],
+});
+
+function renderPage() {
+ return render(
+ <MemoryRouter initialEntries={['/pipeline/series/series-1']}>
+ <Routes>
+ <Route path="/pipeline/series/:seriesId" element={<PipelineSeries />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+const openLens = async (user) => {
+ await screen.findByRole('heading', { name: 'Example Series' });
+ await user.click(screen.getByText('Evolution lens'));
+};
+
+describe('Pipeline series — character-arc evolution lens', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listPipelineIssues.mockResolvedValue([]);
+ listUniverses.mockResolvedValue([universe]);
+ });
+
+ it('authors a sparse lens and declares a flat arc without raising a blocking state', async () => {
+ const user = userEvent.setup();
+ getPipelineSeries.mockResolvedValue(seriesWith());
+ renderPage();
+ await openLens(user);
+
+ expect(screen.getByText('not declared · 0/5 stages')).toBeVisible();
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Declared outcome' }), 'flat-testing');
+ await user.type(
+ screen.getByRole('textbox', { name: 'cost tested — Causal consequence' }),
+ 'The relay holds.',
+ );
+
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByText('flat-testing · 1/5 stages')).toBeVisible();
+ });
+
+ it('anchors a stage to an authored transition beat and clears a stale one in a click', async () => {
+ const user = userEvent.setup();
+ getPipelineSeries.mockResolvedValue(seriesWith({
+ evolution: {
+ outcome: 'partial-open',
+ outcomeNote: '',
+ stages: [{
+ stageId: 'final-proof',
+ testedBelief: 'Usefulness buys safety.',
+ externalPressure: '', characterChoice: '', causalConsequence: '',
+ evidence: { atIssue: null, atSceneAnchor: '', transitionId: 'trn-deleted', episodeId: '', sceneKey: '' },
+ }],
+ },
+ }));
+ renderPage();
+ await openLens(user);
+
+ expect(screen.getByText('Stale anchor')).toBeVisible();
+ const beat = screen.getByRole('combobox', { name: 'final proof — Evidence beat' });
+ expect(beat).toHaveValue('trn-deleted');
+
+ await user.click(screen.getByRole('button', { name: 'Re-pick final proof anchor' }));
+ expect(screen.queryByText('Stale anchor')).not.toBeInTheDocument();
+
+ await user.selectOptions(beat, 'trn-1111');
+ expect(beat).toHaveValue('trn-1111');
+ });
+
+ it('surfaces universe psychology as read-only context, never as an editable field', async () => {
+ const user = userEvent.setup();
+ getPipelineSeries.mockResolvedValue(seriesWith());
+ renderPage();
+ await openLens(user);
+ await user.click(screen.getByText('Universe baseline (read-only)'));
+
+ expect(screen.getByText('If I stay useful, nobody leaves.')).toBeVisible();
+ expect(screen.queryByRole('textbox', { name: /theory of control/i })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 8228539d7d..c184310018 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -41,6 +41,8 @@ import { recommendStructure, describeStructure } from '../lib/seasonStructure';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow';
+import CharacterEvolutionLens from '../components/character/CharacterEvolutionLens';
+import { EVOLUTION_STAGES, isDeclaredEvolution } from '../lib/characterEvolution.js';
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
@@ -457,7 +459,7 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
<FactReferenceSection series={series} patchSeries={patchSeries} />
- <CharacterArcsSection series={series} patchSeries={patchSeries} />
+ <CharacterArcsSection series={series} universes={universes} patchSeries={patchSeries} />
<div className="block">
<div className="flex items-center justify-between mb-1">
@@ -894,8 +896,11 @@ function FactReferenceSection({ series, patchSeries }) {
// permissive — a freshly-added blank arc simply doesn't persist until named. The
// arc.transitions editorial check reconciles its detected change moments against
// what's authored here and flags characters with no transition scenes (flat arcs).
-function CharacterArcsSection({ series, patchSeries }) {
+function CharacterArcsSection({ series, universes, patchSeries }) {
const arcs = Array.isArray(series.characterArcs) ? series.characterArcs : [];
+ // The linked universe's cast, for the read-only psychology baseline beside
+ // each lens. Absent when no universe is linked — the lens still authors fine.
+ const cast = universes?.find((u) => u.id === series.universeId)?.characters || [];
const setArcs = (next) => patchSeries({ characterArcs: next });
const setArc = (i, patch) => setArcs(arcs.map((a, idx) => (idx === i ? { ...a, ...patch } : a)));
const addArc = () => setArcs([...arcs, { characterName: '', want: '', need: '', startState: '', endState: '', transitions: [] }]);
@@ -1032,6 +1037,30 @@ function CharacterArcsSection({ series, patchSeries }) {
))}
</div>
</div>
+
+ <details className="mt-2">
+ <summary className="min-h-[32px] cursor-pointer text-[10px] uppercase tracking-wider text-gray-600">
+ Evolution lens
+ <span className="ml-2 normal-case tracking-normal text-[11px] text-gray-500">
+ {isDeclaredEvolution(arc.evolution) ? arc.evolution.outcome : 'not declared'}
+ {' · '}{arc.evolution?.stages?.length || 0}/{EVOLUTION_STAGES.length} stages
+ </span>
+ </summary>
+ <div className="pt-2">
+ <CharacterEvolutionLens
+ idPrefix={`arc-${i}`}
+ host="pipelineSeries"
+ evolution={arc.evolution || null}
+ anchors={{
+ transitions: transitions
+ .filter((t) => t.id)
+ .map((t) => ({ id: t.id, label: t.label || t.kind || t.id })),
+ }}
+ psychology={cast.find((c) => c.id === arc.characterId)?.psychology}
+ onChange={(evolution) => setArc(i, { evolution })}
+ />
+ </div>
+ </details>
</div>
);
})}