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: map the character evolution lens onto Writers Room manuscript segments (#6445)
[._.]/ Adam Eivy45bfb0b3a85d
diff --git a/client/src/components/character/CharacterEvolutionLens.jsx b/client/src/components/character/CharacterEvolutionLens.jsxindex eedca34810..ecbf14ba17 100644--- a/client/src/components/character/CharacterEvolutionLens.jsx+++ b/client/src/components/character/CharacterEvolutionLens.jsx@@ -1,13 +1,14 @@/*** 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.+ * ONE component for every authoring surface — the FableLoom series plan's+ * "Cast evolution" section, the Pipeline series character-arc cards, and the+ * Writers Room cast bible (#6445) — 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@@ -50,9 +51,16 @@ const ids = (list) => new Set((list || []).map((item) => item?.id).filter(Boolea// `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) });+const evidenceRefsFor = (host, anchors) => {+ if (host === 'fableLoom') return { episodeIds: ids(anchors?.episodes), sceneKeys: ids(anchors?.scenes) };+ // Writers Room resolves ids only. The server additionally checks each stage's+ // `anchorQuote` against the passage its segment still holds (it has the draft+ // body; this editor has the outline). Staler than the server, never laxer —+ // an anchor this surface calls live can still come back `[stale]` from the+ // evaluate pass, which is the safe direction.+ if (host === 'writersRoom') return { segmentIds: ids(anchors?.segments) };+ return { transitionIds: ids(anchors?.transitions) };+};/*** The anchor fields of one stage that no longer resolve, as a clearing patch.@@ -123,6 +131,36 @@ function UniverseBaseline({ psychology }) {// dismantling the stage.function StageEvidence({ host, anchors, idPrefix, stageId, stageLabel, evidence, onPatch }) {const named = (label) => `${stageLabel} — ${label}`;+ if (host === 'writersRoom') {+ return (+ <div className="grid gap-2 sm:grid-cols-2">+ <AnchorSelect+ id={`${idPrefix}-${stageId}-segment`}+ label="Evidence segment"+ ariaLabel={named('Evidence segment')}+ value={evidence?.segmentId || ''}+ options={anchors?.segments || []}+ emptyLabel="No segment anchor"+ onChange={(segmentId) => onPatch({ segmentId })}+ />+ <FormField+ label="Anchor quote"+ hint="Segment numbers are rebuilt every save — a short verbatim quote is what keeps this stage pinned to the right passage."+ labelClassName={labelClass}+ >+ <input+ id={`${idPrefix}-${stageId}-quote`}+ aria-label={named('Anchor quote')}+ className={inputClass}+ value={evidence?.anchorQuote || ''}+ maxLength={CHARACTER_EVOLUTION_LIMITS.anchorQuote}+ placeholder="A few words from the passage"+ onChange={(event) => onPatch({ anchorQuote: event.target.value })}+ />+ </FormField>+ </div>+ );+ }if (host === 'fableLoom') {const episodes = anchors?.episodes || [];const scenes = (anchors?.scenes || [])diff --git a/client/src/components/writers-room/BibleSection.jsx b/client/src/components/writers-room/BibleSection.jsxindex fa9e4335ff..1ff7c4a321 100644--- a/client/src/components/writers-room/BibleSection.jsx+++ b/client/src/components/writers-room/BibleSection.jsx@@ -54,7 +54,14 @@ export function BibleAiBadge() {);}-export default function BibleSection({ workId, items: itemsProp, onItemsChange, readingTheme = 'dark', hotRefId = null, config }) {+export default function BibleSection({+ workId, items: itemsProp, onItemsChange, readingTheme = 'dark', hotRefId = null, config,+ // Extra props spread onto every `kind: 'custom'` field component. The shared+ // shell knows nothing about them — it is how a wrapper hands a structured+ // editor host context it cannot fetch for itself (the Writers Room evolution+ // lens needs the active draft's segment index to offer real anchors).+ customProps = null,+}) {const [internalItems, setInternalItems] = useState(itemsProp || []);const items = itemsProp ?? internalItems;const [editingId, setEditingId] = useState(null);@@ -120,6 +127,7 @@ export default function BibleSection({ workId, items: itemsProp, onItemsChange,item={null}items={items}config={config}+ customProps={customProps}onSaved={(record) => { upsert(record); setCreating(false); }}onCancel={() => setCreating(false)}/>@@ -136,6 +144,7 @@ export default function BibleSection({ workId, items: itemsProp, onItemsChange,item={item}items={items}config={config}+ customProps={customProps}onSaved={(updated) => { upsert(updated); setEditingId(null); }}onDeleted={() => { removeOne(item.id); setEditingId(null); }}onCancel={() => setEditingId(null)}@@ -216,7 +225,7 @@ function BibleRow({ item, config, onEdit, readingTheme }) {);}-function BibleEditor({ workId, item, items = [], config, onSaved, onDeleted, onCancel }) {+function BibleEditor({ workId, item, items = [], config, customProps = null, onSaved, onDeleted, onCancel }) {const isCreate = !item;const { primary, fields } = config;const [draft, setDraft] = useState(() => {@@ -318,6 +327,7 @@ function BibleEditor({ workId, item, items = [], config, onSaved, onDeleted, onCsiblings={items.filter((it) => it.id && it.id !== item?.id)}idPrefix={`bible-field-${f.key}`}inputCls={inputCls}+ {...customProps}/>) : (<label htmlFor={`bible-field-${f.key}`} className="block">diff --git a/client/src/components/writers-room/BibleSection.test.jsx b/client/src/components/writers-room/BibleSection.test.jsxindex 6b0bdf126a..fc5a57e16f 100644--- a/client/src/components/writers-room/BibleSection.test.jsx+++ b/client/src/components/writers-room/BibleSection.test.jsx@@ -129,7 +129,7 @@ const SCENARIOS = [motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],// Structured framework fields ride along as their empty value too — the// server tells a deliberate clear from an untouched key by presence.- sliders: {}, psychology: null, relationshipLinks: [],+ sliders: {}, psychology: null, relationshipLinks: [], evolution: null,},createdRecord: {id: 'char-2', name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '',@@ -144,7 +144,7 @@ const SCENARIOS = [motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],// Structured framework fields ride along as their empty value too — the// server tells a deliberate clear from an untouched key by presence.- sliders: {}, psychology: null, relationshipLinks: [],+ sliders: {}, psychology: null, relationshipLinks: [], evolution: null,},},];diff --git a/client/src/components/writers-room/CharacterFrameworkEditors.jsx b/client/src/components/writers-room/CharacterFrameworkEditors.jsxindex 9acf9f939a..2a91847a68 100644--- a/client/src/components/writers-room/CharacterFrameworkEditors.jsx+++ b/client/src/components/writers-room/CharacterFrameworkEditors.jsx@@ -1,7 +1,7 @@/*** Structured character-framework editors for the Writers Room cast bible* (#6417) — the psychology profile (#6414), the Three Sliders (#2175), and the- * relationship-link rows (#1287).+ * relationship-link rows (#1287), plus the five-stage evolution lens (#6445).** These are `kind: 'custom'` fields on BibleSection's field config: BibleSection* seeds each from the stored record, hands the component a value + `onChange`,@@ -32,6 +32,7 @@ import {RELATIONSHIP_LINK_TYPES,} from '../../lib/characterFramework';import { BIBLE_LIMITS } from '../../lib/bibleLimits';+import CharacterEvolutionLens from '../character/CharacterEvolutionLens';const asObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});const subLabelCls = 'block text-[9px] uppercase tracking-wider text-gray-500';@@ -282,3 +283,41 @@ export function RelationshipLinkRows({ value, onChange, siblings, idPrefix, inpu</div>);}++// ---------------------------------------------------------------------------+// Five-stage evolution lens (#6445)+// ---------------------------------------------------------------------------++// Stored verbatim; `null` on a character nobody has authored a lens for, which+// is the shape the server persists, so an untouched record round-trips.+export const seedEvolution = (item) => item?.evolution ?? null;+// `patchEvolution` already returns `null` once nothing is authored (its "clear"+// path), so the editor sends what it has rather than re-deriving that rule.+export const marshalEvolution = (value) => (value && typeof value === 'object' ? value : null);++/**+ * The shared `CharacterEvolutionLens`, hosted in the Writers Room cast bible.+ *+ * Reused rather than re-implemented: the outcome picker, the five stage cards,+ * the stale-anchor badge and its one-click re-pick are identical to the Pipeline+ * series and FableLoom plan surfaces — only the anchor row differs, and the+ * `host` prop already owns that. `segments` is the work's live segment index+ * (`{ id, kind, heading }`), mapped to the `{ id, label }` option shape the+ * anchor picker takes; a mount without it (a standalone bible render) still+ * edits the prose half and keeps an existing anchor visible as "(missing)".+ */+export function EvolutionFields({ value, onChange, idPrefix, segments }) {+ const options = (Array.isArray(segments) ? segments : [])+ .filter((segment) => segment?.id)+ .map((segment) => ({ id: segment.id, label: `${segment.id} · ${segment.heading || segment.kind || ''}`.trim() }));+ return (+ <CharacterEvolutionLens+ idPrefix={idPrefix}+ evolution={value}+ onChange={onChange}+ host="writersRoom"+ anchors={{ segments: options }}+ psychology={null}+ />+ );+}diff --git a/client/src/components/writers-room/CharactersBible.evolution.test.jsx b/client/src/components/writers-room/CharactersBible.evolution.test.jsxnew file mode 100644index 0000000000..50d9b53017--- /dev/null+++ b/client/src/components/writers-room/CharactersBible.evolution.test.jsx@@ -0,0 +1,177 @@+/**+ * The story-scoped five-stage evolution lens, authored in the Writers Room cast+ * bible (#6445, epic #6418).+ *+ * What this pins: the lens round-trips through the bible editor, a stale+ * segment anchor stays visible and re-pickable rather than vanishing, and the+ * lens never becomes a gate — a character with none is not "missing" anything.+ *+ * Obviously-fake fixtures only — never a record from a live instance.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, cleanup, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/apiWritersRoom', () => ({+ listWritersRoomCharacters: vi.fn(),+ createWritersRoomCharacter: vi.fn(),+ updateWritersRoomCharacter: vi.fn(),+ deleteWritersRoomCharacter: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },+}));++import CharactersBible from './CharactersBible';+import {+ listWritersRoomCharacters,+ updateWritersRoomCharacter,+} from '../../services/apiWritersRoom';++const CHARACTER = {+ id: 'wr-char-1',+ name: 'Wren Calloway',+ aliases: [],+ role: 'protagonist',+ physicalDescription: 'Short, silver hair, sharp eyes.',+ personality: '',+ background: '',+ notes: '',+ motivations: '',+ ghost: '',+ wound: '',+ lie: '',+ need: '',+ want: '',+ arcType: null,+ secrets: [],+ sliders: { proactivity: null, likability: null, competence: null },+ relationshipLinks: [],+ source: 'user',+};++const SEGMENTS = [+ { id: 'seg-001', kind: 'chapter', heading: 'Ledger' },+ { id: 'seg-002', kind: 'chapter', heading: 'Harbor' },+];++const withLens = (evolution) => ({ ...CHARACTER, evolution });++beforeEach(() => { vi.clearAllMocks(); });+afterEach(() => { cleanup(); });++describe('CharactersBible — five-stage evolution lens (#6445)', () => {+ it('authors an outcome, a stage and a manuscript anchor, then shows them after a reload', async () => {+ const CHOICE = 'She lets the boat go without counting.';+ const QUOTE = 'let the boat go';+ const saved = withLens({+ outcome: 'full-change',+ outcomeNote: '',+ stages: [{+ stageId: 'final-proof',+ testedBelief: '',+ externalPressure: '',+ characterChoice: CHOICE,+ causalConsequence: '',+ evidence: { atIssue: null, atSceneAnchor: '', transitionId: '', episodeId: '', sceneKey: '', segmentId: 'seg-002', anchorQuote: QUOTE },+ }],+ });+ listWritersRoomCharacters.mockResolvedValue([CHARACTER]);+ updateWritersRoomCharacter.mockResolvedValue(saved);++ const { unmount } = render(<CharactersBible workId="wr-work-1" segments={SEGMENTS} />);+ await screen.findByText('Wren Calloway');+ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));++ await userEvent.selectOptions(screen.getByLabelText('Declared outcome'), 'full-change');+ await userEvent.type(screen.getByLabelText('final proof — Character choice'), CHOICE);+ await userEvent.selectOptions(screen.getByLabelText('final proof — Evidence segment'), 'seg-002');+ await userEvent.type(screen.getByLabelText('final proof — Anchor quote'), QUOTE);+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());+ const { evolution } = updateWritersRoomCharacter.mock.calls[0][2];+ expect(evolution.outcome).toBe('full-change');+ expect(evolution.stages).toHaveLength(1);+ expect(evolution.stages[0]).toMatchObject({ stageId: 'final-proof', characterChoice: CHOICE });+ expect(evolution.stages[0].evidence).toMatchObject({ segmentId: 'seg-002', anchorQuote: QUOTE });++ unmount();+ listWritersRoomCharacters.mockResolvedValue([saved]);+ render(<CharactersBible workId="wr-work-1" segments={SEGMENTS} />);+ await userEvent.click(await screen.findByRole('button', { name: 'Edit Wren Calloway' }));+ expect(screen.getByLabelText('Declared outcome')).toHaveValue('full-change');+ expect(screen.getByLabelText('final proof — Character choice')).toHaveValue(CHOICE);+ expect(screen.getByLabelText('final proof — Evidence segment')).toHaveValue('seg-002');+ expect(screen.getByLabelText('final proof — Anchor quote')).toHaveValue(QUOTE);+ });++ it('keeps a stale segment anchor visible and re-pickable, preserving the quote', async () => {+ // The writer cut the chapter this stage pointed at; `seg-009` is gone.+ const stale = withLens({+ outcome: 'full-change',+ outcomeNote: '',+ stages: [{+ stageId: 'final-proof',+ characterChoice: 'She lets the boat go.',+ evidence: { atIssue: null, atSceneAnchor: '', transitionId: '', episodeId: '', sceneKey: '', segmentId: 'seg-009', anchorQuote: 'let the boat go' },+ }],+ });+ listWritersRoomCharacters.mockResolvedValue([stale]);+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...stale, ...patch }));++ render(<CharactersBible workId="wr-work-1" segments={SEGMENTS} />);+ await screen.findByText('Wren Calloway');+ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));++ expect(screen.getByText('Stale anchor')).toBeInTheDocument();+ // The dead pointer is still selected, labelled "(missing)" — never silently+ // dropped, and never rendered as a live anchor.+ expect(screen.getByLabelText('final proof — Evidence segment')).toHaveValue('seg-009');+ expect(screen.getByRole('option', { name: 'seg-009 (missing)' })).toBeInTheDocument();++ await userEvent.click(screen.getByRole('button', { name: /Re-pick final proof anchor/ }));+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());+ const [stageOut] = updateWritersRoomCharacter.mock.calls[0][2].evolution.stages;+ expect(stageOut.evidence.segmentId).toBe('');+ // The quote survives the re-pick — it is the hint the writer re-anchors by.+ expect(stageOut.evidence.anchorQuote).toBe('let the boat go');+ expect(stageOut.characterChoice).toBe('She lets the boat go.');+ });++ it('never gates on the lens: an unset one is not listed as missing and clears to null', async () => {+ listWritersRoomCharacters.mockResolvedValue([CHARACTER]);+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...CHARACTER, ...patch }));++ render(<CharactersBible workId="wr-work-1" segments={SEGMENTS} />);+ await screen.findByText('Wren Calloway');+ // The row's completeness warning never mentions the optional lens.+ expect(screen.queryByText(/Missing:.*evolution/i)).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());+ // Present-but-null is how the server tells a deliberate clear from an+ // untouched key; an unauthored lens sends null, not an empty husk.+ expect(updateWritersRoomCharacter.mock.calls[0][2].evolution).toBeNull();+ });++ it('still edits the prose half when the work has no segment index to anchor to', async () => {+ listWritersRoomCharacters.mockResolvedValue([CHARACTER]);+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...CHARACTER, ...patch }));++ render(<CharactersBible workId="wr-work-1" />);+ await screen.findByText('Wren Calloway');+ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));++ await userEvent.type(screen.getByLabelText('cost tested — Belief under test'), 'The ledger keeps people.');+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());+ const [stageOut] = updateWritersRoomCharacter.mock.calls[0][2].evolution.stages;+ expect(stageOut).toMatchObject({ stageId: 'cost-tested', testedBelief: 'The ledger keeps people.' });+ });+});diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsxindex 117ad673b6..ca45ba858a 100644--- a/client/src/components/writers-room/CharactersBible.jsx+++ b/client/src/components/writers-room/CharactersBible.jsx@@ -6,12 +6,15 @@ import {CHARACTER_SECRETS_FIELD,} from '../../lib/characterFramework';import {+ EvolutionFields,PsychologyFields,RelationshipLinkRows,SliderFields,+ marshalEvolution,marshalPsychology,marshalRelationshipLinks,marshalSliders,+ seedEvolution,seedPsychology,seedRelationshipLinks,seedSliders,@@ -70,6 +73,18 @@ const FRAMEWORK_FIELDS = [marshal: marshalRelationshipLinks,Component: RelationshipLinkRows,},+ // The story-scoped five-stage lens (#6445) — what THIS manuscript does to the+ // baseline above, anchored retrospectively to the draft's segment index. It+ // stays inside FRAMEWORK_FIELDS so `blanksExcludeKeys` keeps it out of the+ // row's "Missing: …" warning: the lens is optional and never a gate.+ {+ key: 'evolution',+ kind: 'custom',+ heading: 'Character evolution (five-stage lens)',+ seed: seedEvolution,+ marshal: marshalEvolution,+ Component: EvolutionFields,+ },];// The framework is optional by design — a character with no Ghost isn't// incomplete — so it stays out of the row's "Missing: …" warning, which@@ -133,7 +148,9 @@ const CHARACTER_CONFIG = {// Controlled vs. uncontrolled: caller may pass `characters` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function CharactersBible({ workId, characters, onCharactersChange, readingTheme = 'dark', hotRefId = null }) {+export default function CharactersBible({+ workId, characters, onCharactersChange, readingTheme = 'dark', hotRefId = null, segments = null,+}) {return (<BibleSectionworkId={workId}@@ -142,6 +159,9 @@ export default function CharactersBible({ workId, characters, onCharactersChangereadingTheme={readingTheme}hotRefId={hotRefId}config={CHARACTER_CONFIG}+ // The active draft's segment index, so the evolution lens can anchor a+ // stage to a real chapter/scene instead of asking for a raw `seg-NNN`.+ customProps={{ segments }}/>);}diff --git a/client/src/components/writers-room/StoryboardBibleTab.jsx b/client/src/components/writers-room/StoryboardBibleTab.jsxindex a2004fc6f4..e529c83169 100644--- a/client/src/components/writers-room/StoryboardBibleTab.jsx+++ b/client/src/components/writers-room/StoryboardBibleTab.jsx@@ -65,6 +65,7 @@ export default function StoryboardBibleTab({readingTheme,hotRefId = null,dirty = false,+ segments = null,}) {const meta = BIBLE_KINDS[kind];const Bible = meta.Component;@@ -74,6 +75,9 @@ export default function StoryboardBibleTab({[meta.changeProp]: onItemsChange,readingTheme,hotRefId,+ // Only the character bible anchors anything to the manuscript (the+ // evolution lens, #6445); places and objects ignore it.+ ...(kind === 'characters' ? { segments } : {}),};return (<div className="px-3 py-3 space-y-3">diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex f68ce9c858..7d43ea1262 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -332,6 +332,7 @@ function StoryboardPanel({dirty={dirty}readingTheme={readingTheme}hotRefId={hotRef?.kind === 'char' ? hotRef.refId : null}+ segments={activeDraft?.segmentIndex || null}/>)}{tab === TAB.WORLD && (diff --git a/client/src/lib/characterEvolution.js b/client/src/lib/characterEvolution.jsindex 7f533eb550..0e7496ebc2 100644--- a/client/src/lib/characterEvolution.js+++ b/client/src/lib/characterEvolution.js@@ -108,9 +108,13 @@ export const evolutionStage = (evolution, stageId) => (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();+ // Verbatim, exactly like the stage prose above: an anchor field can be prose+ // (`anchorQuote`, `atSceneAnchor`), and trimming on every keystroke eats the+ // space the author just typed, so a multi-word quote can never be entered.+ // The server sanitizer trims on save; whitespace alone is still not authored.+ for (const field of TEXT_EVIDENCE_FIELDS) evidence[field] = asText(raw[field]);const authored = evidence.atIssue !== null- || TEXT_EVIDENCE_FIELDS.some((field) => evidence[field]);+ || TEXT_EVIDENCE_FIELDS.some((field) => evidence[field].trim());return authored ? evidence : null;};diff --git a/data.reference/prompts/stages/writers-room-evaluate.md b/data.reference/prompts/stages/writers-room-evaluate.mdindex 52a10cf8a3..ac3d0aa37d 100644--- a/data.reference/prompts/stages/writers-room-evaluate.md+++ b/data.reference/prompts/stages/writers-room-evaluate.md@@ -29,6 +29,43 @@ Only what the writer authored is included, so a field you do not see was left blUse it only to judge delivery against intent: where the prose earns a declared beat, and where a declared Lie / Need / arc is asserted in the bible but never dramatized on the page. Do not restate the plan back as a strength, do not treat a field the writer left blank as a defect, and do not invent framework the writer has not declared. Character issues that reference the plan belong in `issues` with `category: "character"`, anchored to a real `excerpt` like every other issue.{{/castFrameworkJson}}+{{#characterEvolution}}+## Authored character evolution (five-stage lens)++The writer has also recorded an OPTIONAL five-stage lens for the characters below. It states the causal chain this manuscript runs a character through:++**tested control belief → external pressure → the choice → the cost paid → the final behavioral proof**++- *control strategy failing* — the belief the character controls their world with, and the first sign it no longer works.+- *pressure forces exploration* — the external pressure that makes the old strategy unusable and forces them to look for another way.+- *commitment to change* — the choice they actually make.+- *cost tested* — what that choice costs them, and whether they can bear it.+- *final proof* — the closing BEHAVIOR that proves the change (or the refusal).++The `declared outcome` is authored intent. It changes your verdict; it never suppresses this reading:++- `full-change` — the change must endure and be proven by behavior. A payoff won only by defeating an external obstacle, with no behavioral proof on the page, IS an issue.+- `tragic-refusal` — doubling down on the control belief is the INTENDED ending. Do not flag it as a flat or failed arc. The issue here is the opposite: a refusal that was never genuinely tested — no real pressure, no cost paid — so the character never had a change to refuse.+- `flat-testing` — the belief is tested and deliberately HOLDS; the character changes the world around them instead of themselves. Constancy is the point: do not flag it as a flat arc.+- `partial-open` — partial change, or an ending left genuinely open, is a legitimate literary ending. Incompleteness itself is NOT an issue; an UNEARNED CLAIM OF COMPLETION is — prose asserting the character is transformed when the stages were never paid off.+- `undeclared` — the writer has not yet said how the arc lands. Treat the stages as provisional planning, not as intent to hold the prose to.++Evidence points at a manuscript segment (`segment seg-003`) and may carry the quote that pins it. Segment numbering is rebuilt every time the draft is saved, so a stage annotated `[stale]` points at prose that has moved or gone and `[unverified]` could not be resolved at all. Neither is proof. Missing or unresolved evidence means NOT PROVEN — never read it as passing. When a stage is `[stale]`, say so in your `suggestion` and quote the passage that should now anchor it.++Two failure modes need DIFFERENT repairs — never merge them into one issue:++- **no authored intent** — the character has no lens stage for a change the prose shows or plainly needs. Begin `note` with `No authored intent:` and make the paired `suggestions` entry name the stage to author.+- **authored intent not delivered** — a stage IS authored but the page never delivers it. Begin `note` with `Authored intent not delivered:` and make the paired `suggestions` entry name the concrete scene that would land that stage.++Both go in `issues` with `category: "character"`, anchored to a real `excerpt` like every other issue.++This is a craft lens over the authored beats — NOT a page count, a chapter count, or a percentage layout. Do not require five chapters, fixed positions, one stage per chapter, or a changed belief that is the literal opposite of the tested one. Not every character transforms, and a character with no lens is judged exactly as they were before.++```+{{characterEvolution}}+```+{{/characterEvolution}}+## TaskRead the entire draft. Then produce one editorial pass that covers:diff --git a/scripts/migrations/362-writers-room-character-framework.js b/scripts/migrations/362-writers-room-character-framework.jsindex e7c3390c63..3ebb0f65c8 100644--- a/scripts/migrations/362-writers-room-character-framework.js+++ b/scripts/migrations/362-writers-room-character-framework.js@@ -22,7 +22,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {"writers-room-characters.md": "4b19f6538ff3a602007ef8e32c8e5047",- "writers-room-evaluate.md": "286e9498966187ed74126680da4a6a54"+ "writers-room-evaluate.md": "995cfd92061b55730b0e081998e96f84"};const { applyMigration, up } = makePromptReplaceMigration({accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,diff --git a/scripts/migrations/366-writers-room-evaluate-psychology.js b/scripts/migrations/366-writers-room-evaluate-psychology.jsindex f594267dbc..e2fd28058b 100644--- a/scripts/migrations/366-writers-room-evaluate-psychology.js+++ b/scripts/migrations/366-writers-room-evaluate-psychology.js@@ -23,7 +23,7 @@ export const ACCEPTED_OLD_MD5 = {]};export const NEW_SHIPPED_MD5 = {- "writers-room-evaluate.md": "286e9498966187ed74126680da4a6a54"+ "writers-room-evaluate.md": "995cfd92061b55730b0e081998e96f84"};const { applyMigration, up } = makePromptReplaceMigration({accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,diff --git a/scripts/migrations/369-writers-room-evaluate-character-evolution.js b/scripts/migrations/369-writers-room-evaluate-character-evolution.jsnew file mode 100644index 0000000000..436f79160f--- /dev/null+++ b/scripts/migrations/369-writers-room-evaluate-character-evolution.js@@ -0,0 +1,39 @@+/**+ * Teach the Writers Room evaluate prompt to read the five-stage character+ * evolution lens (#6445, epic #6418).+ *+ * The pass already receives the authored character framework; it now also+ * receives `{{characterEvolution}}` — the OPTIONAL lens a writer maps onto the+ * manuscript retrospectively, with each stage's evidence annotated against the+ * live segment index. The template needed the rulings that block makes+ * necessary, and none of them can be inferred from the JSON alone:+ *+ * - `tragic-refusal` and `flat-testing` are INTENDED endings, so neither is a+ * flat-arc finding; `partial-open` makes incompleteness legitimate and only+ * an unearned claim of completion a finding.+ * - a `[stale]` or `[unverified]` anchor is NOT proof — segment numbering is+ * rebuilt on every draft save, so a resolving id can name prose the stage+ * was never written for.+ * - "no authored intent" and "authored intent not delivered" are different+ * defects with different repairs and must stay separate findings.+ *+ * Additive and section-gated: a work with no authored lens renders no block, so+ * its analysis is unchanged.+ */+import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ "writers-room-evaluate.md": [+ "286e9498966187ed74126680da4a6a54"+ ]+};+export const NEW_SHIPPED_MD5 = {+ "writers-room-evaluate.md": "995cfd92061b55730b0e081998e96f84"+};+const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,+ label: 'writers-room evaluate character evolution',+ customizedHint: (filename) => ` Merge the "Authored character evolution (five-stage lens)" section — the four declared outcomes, the stale/unverified evidence rule, and the two distinct failure modes — from data.reference/prompts/stages/${filename}.`,+});+export { applyMigration };+export default { up };diff --git a/scripts/migrations/369-writers-room-evaluate-character-evolution.test.js b/scripts/migrations/369-writers-room-evaluate-character-evolution.test.jsnew file mode 100644index 0000000000..99756381d2--- /dev/null+++ b/scripts/migrations/369-writers-room-evaluate-character-evolution.test.js@@ -0,0 +1,6 @@+import { describe } from 'vitest';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './369-writers-room-evaluate-character-evolution.js';+import { runPromptMigrationTests } from './_testHelpers.js';+describe('migration 369 — writers-room evaluate character-evolution lens', () => {+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-369-' });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex bcb9e51ba3..8797a93bdc 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -39,7 +39,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],'writers-room-characters.md': ['cdd99c7a3ef92bf798f30fa2fb4465f1'],- 'writers-room-evaluate.md': ['d3374472820df264731f435141e05270', 'd3b2b40bcabc9ca690fa67b69d64d628'],+ 'writers-room-evaluate.md': ['d3374472820df264731f435141e05270', 'd3b2b40bcabc9ca690fa67b69d64d628', '286e9498966187ed74126680da4a6a54'],'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],@@ -92,7 +92,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','writers-room-characters.md': '4b19f6538ff3a602007ef8e32c8e5047',- 'writers-room-evaluate.md': '286e9498966187ed74126680da4a6a54',+ 'writers-room-evaluate.md': '995cfd92061b55730b0e081998e96f84','cos-agent-briefing.md': 'a01c81d3a7f4ac0ca9e8d5137735c0e3','universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd','story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0',diff --git a/server/lib/README.md b/server/lib/README.mdindex a52aea27e4..2a95dad820 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -111,7 +111,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. || `storyBible.js` | Canonical Character / Place / Object shapes; re-exports `BIBLE_LIMITS` from `bibleLimits.js`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). || `characterAugmentValidation.js` | Zod schemas for selective character augmentation (#6417): `characterAugmentProposeSchema` and `characterAugmentApplySchema`, both pinned to `AUGMENTABLE_FIELD_PATHS`. Shared by the Universe cast routes and the Writers Room work-bible routes so the two surfaces cannot drift on which field paths a proposal may name. |-| `characterEvolution.js` | The OPTIONAL five-stage character evolution lens (#6440): `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `CHARACTER_EVOLUTION_LIMITS`, `sanitizeCharacterEvolution` + `sanitizeCharacterEvolutionList` (null when unauthored, unknown stage/outcome rejected not coerced), `evolutionEvidenceStatus` (derived on read — only `anchored` counts as verified, a pointer to a deleted beat reports `stale`), `isDeclaredEvolution`, `renderCharacterEvolutionForPrompt`, and the per-character story-list primitives both hosts share (`isCanonCharacterId`, `isStoryBeatId`, `characterIdentityKey`, `optIssueNumber`, `EVOLUTION_EVIDENCE_FIELDS`). A pure leaf over `bibleLimits.js` + `textUtils.js` so `client/src/lib/characterEvolution.js` mirrors it into the browser bundle. |+| `characterEvolution.js` | The OPTIONAL five-stage character evolution lens (#6440): `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `CHARACTER_EVOLUTION_LIMITS`, `sanitizeCharacterEvolution` + `sanitizeCharacterEvolutionList` (null when unauthored, unknown stage/outcome rejected not coerced), `evolutionEvidenceStatus` (derived on read — only `anchored` counts as verified, a pointer to a deleted beat reports `stale`), `isDeclaredEvolution`, `renderCharacterEvolutionForPrompt` + `renderCharacterEvolutionListForPrompt` (a whole cast as one prompt block), and the per-character story-list primitives the three hosts share (`isCanonCharacterId`, `isStoryBeatId`, `characterIdentityKey`, `optIssueNumber`, `EVOLUTION_EVIDENCE_FIELDS` — Pipeline series, FableLoom, and the Writers Room `segmentId` + `anchorQuote` pair whose quote is what keeps a positional segment anchor from reading as verified after a draft edit). A pure leaf over `bibleLimits.js` + `textUtils.js` so `client/src/lib/characterEvolution.js` mirrors it into the browser bundle. || `characterEvolutionCoverage.js` | Branch coverage for the evolution lens (#6444): `analyzeCharacterEvolutionCoverage` walks every bounded playthrough and flags `EVOLUTION_UNEARNED_INHERITANCE` — a stage proved on one incoming branch of a reconvergence and not another, so a viewer inherits a change they never watched be earned — plus unproven declared endings, out-of-sequence stage anchors and dead evidence pointers (`EVOLUTION_COVERAGE_CODES`). Introduces `unreviewed` (`EVOLUTION_COVERAGE_STATUSES`): a bounded-out enumeration, a cycle or an unresolvable anchor is explicitly NOT `verified` and NOT a defect. Deterministic and provider-free; returns `null` when no lens is authored, so a loom that never opted in is byte-identical. || `characterEvolutionValidation.js` | Zod schemas for the evolution lens — `characterEvolutionSchema` (one lens), `characterEvolutionStageSchema`, `characterEvolutionEvidenceSchema` and `characterEvolutionListSchema` (the FableLoom plan's per-character list). Its own module rather than a `sharedSchemas.js` fragment so `validation.js` (which nearly every suite reaches) doesn't grow an eager edge for a shape only two hosts validate. || `characterFramework.js` | The narrative-character framework as one definition: `CHARACTER_ARC_TYPES`, `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_FIELDS` (the Ghost→Wound→Lie→Need→Want chain plus motivations, arc type, secrets, relationship links, the psychology profile and the Three Sliders), `CHARACTER_FRAMEWORK_LIMITS`, the psychology/slider/link vocabularies re-exported by `storyBible.js` (`PSYCHOLOGY_DRIVE_AXES`, `PSYCHOLOGY_ASSESSMENTS`, `CHARACTER_PSYCHOLOGY_TEXT_FIELDS`, `CHARACTER_PSYCHOLOGY_LIMITS`, `CHARACTER_SLIDER_AXES`, `RELATIONSHIP_LINK_TYPES`), and `pickCharacterFramework` / `pickCastFramework` (framework-only projection for an author-side review prompt, empty entries dropped). A pure leaf over `bibleLimits.js` so the store editableFields, the Zod schemas, and the client editors share one list (#6417). |diff --git a/server/lib/characterEvolution.js b/server/lib/characterEvolution.jsindex f7e9218db7..cbcecf492a 100644--- a/server/lib/characterEvolution.js+++ b/server/lib/characterEvolution.js@@ -31,10 +31,11 @@* record per stage per lens), which needs no id generator and keeps a* round trip byte-stable.*- * Embedded by `seriesCharacterArc.js` (`series.characterArcs[].evolution`) and- * `services/fableLoom/records.js` (`loom.seriesPlan.characterEvolutions[]`),- * both of which sanitize on load/save/sync; later slices of #6418 add the- * character-arc editorial checks and the FableLoom plan review on top.+ * Embedded by `seriesCharacterArc.js` (`series.characterArcs[].evolution`),+ * `services/fableLoom/records.js` (`loom.seriesPlan.characterEvolutions[]`) and+ * `lib/storyBible.js`'s `sanitizeCharacter` (`characters[].evolution`, which is+ * how a Writers Room work carries the lens per work WITHOUT being promoted to a+ * Pipeline series — #6445), all of which sanitize on load/save/sync.*/import { BIBLE_LIMITS } from './bibleLimits.js';@@ -84,6 +85,10 @@ export const CHARACTER_EVOLUTION_LIMITS = Object.freeze({outcomeNote: BIBLE_LIMITS.EVOLUTION_OUTCOME_NOTE_MAX,characterName: BIBLE_LIMITS.NAME_MAX,atSceneAnchor: BIBLE_LIMITS.EVOLUTION_EVIDENCE_ANCHOR_MAX,+ // The verbatim manuscript snippet a Writers Room stage quotes. Same cap as+ // the free-text scene anchor it plays the same role as: an authored locator,+ // not an identifier.+ anchorQuote: BIBLE_LIMITS.EVOLUTION_EVIDENCE_ANCHOR_MAX,evidenceRef: BIBLE_LIMITS.EVOLUTION_EVIDENCE_REF_MAX,atIssue: BIBLE_LIMITS.STORY_ISSUE_NUMBER_MAX,STAGES_PER_LENS_MAX: EVOLUTION_STAGES.length,@@ -116,6 +121,11 @@ export const EVOLUTION_EVIDENCE_STATUSES = Object.freeze([const CHARACTER_ID_RE = /^chr-[a-zA-Z0-9-]+$/;const TRANSITION_ID_RE = /^trn-[a-zA-Z0-9-]+$/;const EPISODE_ID_RE = /^ep-[a-zA-Z0-9-]+$/;+// A Writers Room manuscript segment (`buildSegmentIndex`). POSITIONAL, unlike+// every other pointer here: `seg-003` is the third heading of the draft as it+// stands, and the whole index is recomputed on every draft save. That is why+// the Writers Room host pairs it with `anchorQuote` below.+const SEGMENT_ID_RE = /^seg-\d+$/;const isStr = (v) => typeof v === 'string';@@ -153,8 +163,11 @@ const shapedRef = (raw, re) => {return re.test(value) ? value.slice(0, CHARACTER_EVOLUTION_LIMITS.evidenceRef) : '';};+// A host reference set. A Map passes through unchanged (it answers `.has` like+// a Set and additionally carries the passage text a QUOTED_ANCHORS check+// needs), so a host can hand richer refs in without a second parameter.const asSet = (value) => {- if (value instanceof Set) return value;+ if (value instanceof Set || value instanceof Map) return value;if (Array.isArray(value)) return new Set(value);return null;};@@ -165,6 +178,11 @@ const asSet = (value) => {export const EVOLUTION_EVIDENCE_FIELDS = Object.freeze({pipelineSeries: Object.freeze(['atIssue', 'atSceneAnchor', 'transitionId']),fableLoom: Object.freeze(['episodeId', 'sceneKey']),+ // Writers Room maps the lens RETROSPECTIVELY onto a manuscript it never+ // promotes to a Pipeline series, so its only anchor primitive is the segment+ // index. `anchorQuote` is not a second pointer — it is what makes the first+ // one checkable across an edit.+ writersRoom: Object.freeze(['segmentId', 'anchorQuote']),});// Pointer fields that resolve against a host reference set, paired with the@@ -174,8 +192,23 @@ const RESOLVABLE_ANCHORS = Object.freeze([['transitionId', 'transitionIds'],['episodeId', 'episodeIds'],['sceneKey', 'sceneKeys'],+ ['segmentId', 'segmentIds'],]);+// Pointer fields that carry a companion QUOTE: `[pointer, refsKey, quoteField]`.+// When the host hands the matching ref set in as a Map of pointer -> passage+// text, the quote must still appear in that passage. Without it a positional+// pointer proves only that SOMETHING still occupies that slot — and a Writers+// Room `seg-003` is renumbered by any edit that adds a heading above it, so+// "the id resolves" is exactly the false pass #6418 forbids. A host that hands+// in a plain Set (or no set) is unchanged: the quote is then unverifiable, not+// wrong.+const QUOTED_ANCHORS = Object.freeze([['segmentId', 'segmentIds', 'anchorQuote']]);++// Quotes are compared whitespace-collapsed and case-folded: a manuscript edit+// that rewraps a paragraph or re-cases a heading has not moved the passage.+const normalizeQuote = (raw) => (isStr(raw) ? raw.replace(/\s+/g, ' ').trim().toLowerCase() : '');+/*** Sanitize one stage's evidence anchor. Returns `null` when nothing is* authored so an evidence-free stage carries no empty husk.@@ -187,6 +220,11 @@ const RESOLVABLE_ANCHORS = Object.freeze([* `trn-` beat that proves the stage.* - FableLoom: `episodeId` (`ep-<uuid>`) plus `sceneKey` (a* `storyOutline.scenes[].key`).+ * - Writers Room: `segmentId` (a `seg-NNN` from `buildSegmentIndex`) plus+ * `anchorQuote`, a verbatim snippet of the passage it names. The segment id+ * is positional and is rebuilt on every draft save, so the quote is what+ * lets `evolutionEvidenceStatus` tell "still the same passage" from "that+ * slot now holds a different chapter".* A field the host does not use simply stays empty.*/export function sanitizeEvolutionEvidence(raw) {@@ -200,12 +238,19 @@ export function sanitizeEvolutionEvidence(raw) {// they are length-bounded rather than shape-matched; resolution against the// episode's real keys is what separates a live anchor from a stale one.sceneKey: trimTo(raw.sceneKey, CHARACTER_EVOLUTION_LIMITS.evidenceRef),+ segmentId: shapedRef(raw.segmentId, SEGMENT_ID_RE),+ // Free text, deliberately not shape-matched: it is a verbatim snippet of+ // the author's own prose, and it is PRESERVED when its segment pointer goes+ // stale so it can drive the re-anchor.+ anchorQuote: trimTo(raw.anchorQuote, CHARACTER_EVOLUTION_LIMITS.anchorQuote),};const authored = evidence.atIssue !== null|| evidence.atSceneAnchor|| evidence.transitionId|| evidence.episodeId- || evidence.sceneKey;+ || evidence.sceneKey+ || evidence.segmentId+ || evidence.anchorQuote;return authored ? evidence : null;}@@ -228,7 +273,9 @@ export function evolutionEvidenceStatus(evidence, refs = {}) {// machine-verified, so on its own it stays `unverified`. Checked before the// ref sets are materialized so the common no-pointer case allocates nothing.if (authored.length === 0) {- return evidence.atIssue != null || evidence.atSceneAnchor ? 'unverified' : 'unanchored';+ return evidence.atIssue != null || evidence.atSceneAnchor || evidence.anchorQuote+ ? 'unverified'+ : 'unanchored';}let unchecked = false;for (const [field, refsKey] of authored) {@@ -236,6 +283,19 @@ export function evolutionEvidenceStatus(evidence, refs = {}) {if (!known) unchecked = true;else if (!known.has(evidence[field])) return 'stale';}+ // A quoted pointer that resolved still has to still SAY what it said. The+ // check runs only when the host supplied the passage text; otherwise the+ // anchor is merely unchecked, which is `unverified` below, never `anchored`.+ for (const [field, refsKey, quoteField] of QUOTED_ANCHORS) {+ const quote = normalizeQuote(evidence[quoteField]);+ if (!evidence[field] || !quote) continue;+ const known = refs[refsKey];+ if (!(known instanceof Map)) {+ unchecked = true;+ continue;+ }+ if (!normalizeQuote(known.get(evidence[field])).includes(quote)) return 'stale';+ }return unchecked ? 'unverified' : 'anchored';}@@ -373,9 +433,10 @@ const describeEvidence = (evidence) => {const bits = [];if (evidence.atIssue != null) bits.push(`issue ${evidence.atIssue}`);if (evidence.atSceneAnchor) bits.push(evidence.atSceneAnchor);- for (const [field, label] of [['transitionId', 'transition'], ['episodeId', 'episode'], ['sceneKey', 'scene']]) {+ for (const [field, label] of [['transitionId', 'transition'], ['episodeId', 'episode'], ['sceneKey', 'scene'], ['segmentId', 'segment']]) {if (evidence[field]) bits.push(`${label} ${evidence[field]}`);}+ if (evidence.anchorQuote) bits.push(`quote "${evidence.anchorQuote}"`);return bits.join(', ') || 'none';};diff --git a/server/lib/characterEvolution.test.js b/server/lib/characterEvolution.test.jsindex 53aa4dab66..cc9df14242 100644--- a/server/lib/characterEvolution.test.js+++ b/server/lib/characterEvolution.test.js@@ -170,3 +170,72 @@ describe('client mirror re-exports rather than copies', () => {}});});++describe('quoted segment anchors (#6445)', () => {+ const quoted = (segmentId, anchorQuote) => ({ segmentId, anchorQuote });+ // A Map ref set carries the passage each pointer names; a Set carries only+ // its existence.+ const passages = new Map([+ ['seg-001', 'She balanced the books before she balanced anything else.'],+ ['seg-002', 'She let the boat go without counting what it cost her.'],+ ]);++ it('keeps a well-shaped segment pointer and drops a junk one', () => {+ const lens = sanitizeCharacterEvolution({+ outcome: 'full-change',+ stages: [+ stage('cost-tested', { evidence: quoted('seg-004', ' a quoted line ') }),+ stage('final-proof', { evidence: quoted('../../etc/passwd', 'x') }),+ ],+ });+ expect(lens.stages[0].evidence).toMatchObject({ segmentId: 'seg-004', anchorQuote: 'a quoted line' });+ // The pointer is junk, but the quote alone is still authored evidence.+ expect(lens.stages[1].evidence).toMatchObject({ segmentId: '', anchorQuote: 'x' });+ });++ it('reports anchored only when the pointer resolves AND still holds its quote', () => {+ expect(evolutionEvidenceStatus(quoted('seg-002', 'let the boat go'), { segmentIds: passages }))+ .toBe('anchored');+ // Same live pointer, quote that has moved off it — the renumbering case.+ expect(evolutionEvidenceStatus(quoted('seg-001', 'let the boat go'), { segmentIds: passages }))+ .toBe('stale');+ // Pointer gone entirely.+ expect(evolutionEvidenceStatus(quoted('seg-009', 'let the boat go'), { segmentIds: passages }))+ .toBe('stale');+ });++ it('folds whitespace and case before comparing, so a rewrap is not a drift', () => {+ expect(evolutionEvidenceStatus(quoted('seg-002', 'Let The\nBoat Go'), { segmentIds: passages }))+ .toBe('anchored');+ });++ it('never reports anchored when the host supplied no passage text to check', () => {+ // A Set proves the id exists and nothing more, so a QUOTED anchor stays+ // unverified rather than being credited on existence alone.+ const ids = new Set(['seg-001', 'seg-002']);+ expect(evolutionEvidenceStatus(quoted('seg-002', 'let the boat go'), { segmentIds: ids }))+ .toBe('unverified');+ // …but a dead pointer is still dead.+ expect(evolutionEvidenceStatus(quoted('seg-009', 'let the boat go'), { segmentIds: ids }))+ .toBe('stale');+ // An unquoted pointer is judged on existence, exactly like the other hosts.+ expect(evolutionEvidenceStatus({ segmentId: 'seg-002' }, { segmentIds: ids })).toBe('anchored');+ });++ it('treats a quote with no pointer as an unresolvable locator, never as unanchored', () => {+ expect(evolutionEvidenceStatus({ anchorQuote: 'let the boat go' }, { segmentIds: passages }))+ .toBe('unverified');+ expect(evolutionEvidenceStatus({}, { segmentIds: passages })).toBe('unanchored');+ });++ it('renders the segment and its quote, annotated with the derived status', () => {+ const lens = sanitizeCharacterEvolution({+ outcome: 'full-change',+ stages: [stage('final-proof', { evidence: quoted('seg-002', 'let the boat go') })],+ });+ const block = renderCharacterEvolutionForPrompt(lens, { segmentIds: passages });+ expect(block).toContain('segment seg-002');+ expect(block).toContain('quote "let the boat go"');+ expect(block).toContain('[anchored]');+ });+});diff --git a/server/lib/characterEvolutionValidation.js b/server/lib/characterEvolutionValidation.jsindex f40b02ce5f..2f8b3d7f74 100644--- a/server/lib/characterEvolutionValidation.js+++ b/server/lib/characterEvolutionValidation.js@@ -6,9 +6,10 @@* adding an eager edge there costs one module instantiation per suite for a* shape only two hosts validate (see the Import scoping section of* server/AGENTS.md). The two consumers are `routes/pipeline/series.js`- * (`series.characterArcs[].evolution`) and `lib/fableLoomValidation.js`- * (`loom.seriesPlan.characterEvolutions[]`); sharing one definition is what- * keeps their caps and vocabularies from drifting.+ * (`series.characterArcs[].evolution`), `lib/fableLoomValidation.js`+ * (`loom.seriesPlan.characterEvolutions[]`) and `lib/pipelineValidation.js`'s+ * Writers Room cast schemas (`characters[].evolution`, #6445); sharing one+ * definition is what keeps their caps and vocabularies from drifting.*/import { z } from 'zod';@@ -43,6 +44,11 @@ export const characterEvolutionEvidenceSchema = z.object({transitionId: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.evidenceRef).optional(),episodeId: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.evidenceRef).optional(),sceneKey: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.evidenceRef).optional(),+ // Writers Room manuscript anchors (#6445). `segmentId` is shape-checked by+ // the sanitizer (a `seg-NNN`), not here, so a peer or an older client sending+ // a junk pointer is cleaned rather than 400'd; `anchorQuote` is prose.+ segmentId: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.evidenceRef).optional(),+ anchorQuote: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.anchorQuote).optional(),});export const characterEvolutionStageSchema = z.object({diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex de2c3499d4..09fb6c6c5e 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -30,6 +30,7 @@ import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_Mimport { EFFORT_LEVELS } from './providerModels.js';import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkInfra/taxonomy.js';import { SHOT_TYPES, SCREEN_DIRECTIONS } from './shotGrammar.js';+import { characterEvolutionSchema } from './characterEvolutionValidation.js';// =============================================================================// WRITERS ROOM SCHEMAS@@ -533,6 +534,14 @@ const wrCharFrameworkFields = Object.freeze({.max(BIBLE_LIMITS.SECRETS_PER_CHARACTER_MAX).optional(),psychology: wrPsychologyField.nullable().optional(),sliders: wrSlidersField.nullable().optional(),+ // The optional five-stage evolution lens (#6445), reusing the SAME schema the+ // Pipeline series arc and the FableLoom plan validate against — a second+ // definition here would drift the stage vocabulary the moment one moved.+ // `null` (or an all-blank lens) is a real clear: `sanitizeCharacterEvolution`+ // collapses it to absent so the character reads as un-authored again.+ // Anything this object accepts must also appear in `editableFields` in+ // services/writersRoom/characters.js or the write is validated and dropped.+ evolution: characterEvolutionSchema.nullable().optional(),});// Shared between create and update — the two differ only in whether `name` is// required, and drifting them apart is how `relationshipLinks` ended updiff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 5c0637024d..157515ac39 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -23,6 +23,7 @@ import {PSYCHOLOGY_DRIVE_AXES,RELATIONSHIP_LINK_TYPES,} from './characterFramework.js';+import { sanitizeCharacterEvolution } from './characterEvolution.js';// Re-export so callers (writers-room domain files) can import a single// canonical normalizer when they need to match places by slugline.@@ -946,6 +947,7 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,const voiceCanon = sanitizeVoiceCanon(raw.voiceCanon);const identityPack = sanitizeIdentityPack(raw.identityPack, imageRefs);const psychology = sanitizeCharacterPsychology(raw.psychology);+ const evolution = sanitizeCharacterEvolution(raw.evolution);return {id: ensureId(raw.id, idPrefix),name,@@ -993,6 +995,15 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,// on every record that has not been assessed, so legacy characters stay// valid and visibly unfilled rather than silently inheriting a profile....(psychology ? { psychology } : {}),+ // Optional five-stage evolution lens (#6440), STORY-SCOPED (#6445). What+ // ONE story does to the baseline above: the belief it puts under test, the+ // pressure, the choice, and what that choice causes. Absent (no key) until+ // a writer authors it, so every pre-lens character round-trips unchanged.+ // Reached today by the per-work Writers Room cast bible, whose records live+ // under data/writers-room/works/<workId>/ and are therefore already scoped+ // to one manuscript — the universe cast has no editor for it, which is what+ // keeps a story's realized change from overwriting world-level identity.+ ...(evolution ? { evolution } : {}),// Declared arc type — null (unset) unless it's one of the three known// values, so a legacy record with no arc type stays absent.arcType: trimEnum(raw.arcType, CHARACTER_ARC_TYPE_SET),diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.jsindex 56cb5b2d73..c5c9472db6 100644--- a/server/services/writersRoom/characters.js+++ b/server/services/writersRoom/characters.js@@ -10,6 +10,23 @@ import { BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';import { CHARACTER_FRAMEWORK_FIELDS } from '../../lib/characterFramework.js';import { createBibleStore } from '../bibleStore.js';+/**+ * Everything a writer may author on a Writers Room character, in one exported+ * list so a test can assert it against the route schema. The two MUST agree:+ * a field the Zod schema accepts and this list omits is validated and then+ * thrown away by `createBibleStore` (that is how `relationshipLinks`,+ * `wardrobes` and `voiceId` were silently dropped before #6417).+ */+export const CHARACTER_EDITABLE_FIELDS = Object.freeze([+ 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes',+ 'voiceCanon', 'identityPack', 'wardrobes', 'voiceId',+ ...CHARACTER_FRAMEWORK_FIELDS,+ // The optional five-stage evolution lens (#6445). Story-scoped BY+ // CONSTRUCTION: this store is per work, so authoring a lens here can never+ // reach the universe-wide cast identity the lens is layered over.+ 'evolution',+]);+export const {list: listCharacters,get: getCharacter,@@ -29,11 +46,7 @@ export const {// the route schema, then silently dropped here. Everything the create/update// Zod schema accepts must appear in this list or the write is validated and// thrown away.- editableFields: [- 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes',- 'voiceCanon', 'identityPack', 'wardrobes', 'voiceId',- ...CHARACTER_FRAMEWORK_FIELDS,- ],+ editableFields: CHARACTER_EDITABLE_FIELDS,requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Character name required'),conflictMessage: ({ name }) => `A character named "${name}" already exists`,notFoundLabel: 'Character',diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.jsindex a725ba9172..d31e55944a 100644--- a/server/services/writersRoom/characters.test.js+++ b/server/services/writersRoom/characters.test.js@@ -354,3 +354,117 @@ describe('writers room — psychology, sliders and links (#6417)', () => {expect(emptied.relationshipLinks).toEqual([]);});});++describe('writers room — story-scoped evolution lens (#6445)', () => {+ const LENS = {+ outcome: 'full-change',+ outcomeNote: 'She stops keeping score.',+ stages: [+ {+ stageId: 'control-strategy-failing',+ testedBelief: 'If the ledger balances, nobody leaves.',+ externalPressure: 'The harbor master calls in the note.',+ evidence: { segmentId: 'seg-001', anchorQuote: 'balanced the books' },+ },+ {+ stageId: 'final-proof',+ characterChoice: 'She lets the boat go without counting.',+ causalConsequence: 'The debt stays, and so does she.',+ evidence: { segmentId: 'seg-002' },+ },+ ],+ };++ it('round-trips an authored lens through create, list and update', async () => {+ const id = await newWork();+ // The write has to survive BOTH gates: the route schema (pipelineValidation)+ // and the store's `editableFields` allowlist. A field the schema accepts and+ // the allowlist omits is validated and then silently dropped.+ const created = await createCharacter(id, { name: 'Wren Calloway', evolution: LENS });+ expect(created.evolution.outcome).toBe('full-change');+ expect(created.evolution.stages).toHaveLength(2);++ const [reloaded] = await listCharacters(id);+ expect(reloaded.evolution).toEqual(created.evolution);+ // Stages persist in canonical sequence order regardless of authoring order.+ expect(reloaded.evolution.stages.map((s) => s.stageId))+ .toEqual(['control-strategy-failing', 'final-proof']);+ expect(reloaded.evolution.stages[0].evidence).toMatchObject({+ segmentId: 'seg-001', anchorQuote: 'balanced the books',+ });++ const updated = await updateCharacter(id, created.id, {+ evolution: { ...LENS, outcome: 'partial-open' },+ });+ expect(updated.evolution.outcome).toBe('partial-open');+ });++ it('treats an omitted key as "leave it alone" and an explicit null as a clear', async () => {+ const id = await newWork();+ const created = await createCharacter(id, { name: 'Wren Calloway', evolution: LENS });++ // Absent → preserved (an unrelated edit must not delete authored planning).+ const renamed = await updateCharacter(id, created.id, { role: 'protagonist' });+ expect(renamed.evolution).toEqual(created.evolution);++ // Present-but-empty → a real clear, back to absent rather than an empty husk.+ const cleared = await updateCharacter(id, created.id, { evolution: null });+ expect(cleared).not.toHaveProperty('evolution');+ });++ it('leaves a character with no lens byte-identical to a pre-#6445 record', async () => {+ const id = await newWork();+ const created = await createCharacter(id, { name: 'Wren Calloway', lie: 'I only matter while I am useful.' });+ expect(created).not.toHaveProperty('evolution');+ const [reloaded] = await listCharacters(id);+ expect(reloaded).not.toHaveProperty('evolution');+ });++ it('rejects an unknown stage id and an unknown outcome instead of coercing them', async () => {+ const id = await newWork();+ const created = await createCharacter(id, {+ name: 'Wren Calloway',+ evolution: {+ outcome: 'triumphant',+ stages: [+ { stageId: 'not-a-stage', testedBelief: 'invented' },+ { stageId: 'cost-tested', characterChoice: 'She pays it.' },+ ],+ },+ });+ expect(created.evolution.outcome).toBeNull();+ expect(created.evolution.stages.map((s) => s.stageId)).toEqual(['cost-tested']);+ });++ it('drops a junk segment pointer but keeps a well-shaped one that no longer exists', async () => {+ const id = await newWork();+ const created = await createCharacter(id, {+ name: 'Wren Calloway',+ evolution: {+ outcome: 'full-change',+ stages: [+ { stageId: 'cost-tested', characterChoice: 'a', evidence: { segmentId: '../../etc/passwd' } },+ { stageId: 'final-proof', characterChoice: 'b', evidence: { segmentId: 'seg-999', anchorQuote: 'gone' } },+ ],+ },+ });+ const [costTested, finalProof] = created.evolution.stages;+ expect(costTested.evidence).toBeNull();+ // A well-shaped pointer at a deleted segment is PRESERVED so the review can+ // report it stale and the writer can re-anchor it.+ expect(finalProof.evidence).toMatchObject({ segmentId: 'seg-999', anchorQuote: 'gone' });+ });+});++describe('writers room — route schema and store allowlist agree', () => {+ it('accepts nothing on the wire the store would silently drop', async () => {+ const { writersRoomCharacterUpdateSchema } = await import('../../lib/pipelineValidation.js');+ // `name` is a primaryField, handled ahead of the allowlist; everything else+ // the schema accepts has to be writable, or the PATCH 200s and does nothing.+ const wireFields = Object.keys(writersRoomCharacterUpdateSchema.shape).filter((f) => f !== 'name');+ const writable = new Set(characters.CHARACTER_EDITABLE_FIELDS);+ expect(wireFields.filter((f) => !writable.has(f))).toEqual([]);+ // Regression pin for the field this slice added on both sides at once.+ expect(wireFields).toContain('evolution');+ });+});diff --git a/server/services/writersRoom/evaluator.evolutionLens.test.js b/server/services/writersRoom/evaluator.evolutionLens.test.jsnew file mode 100644index 0000000000..77358f1d4e--- /dev/null+++ b/server/services/writersRoom/evaluator.evolutionLens.test.js@@ -0,0 +1,275 @@+/**+ * The Writers Room `evaluate` pass reads the OPTIONAL five-stage evolution lens+ * (#6445, epic #6418) against the manuscript it is already reviewing — WITHOUT+ * promoting the work to a Pipeline series.+ *+ * The behavior this file exists to pin, in order of how badly it fails:+ * 1. A segment anchor that no longer names the passage it was written for is+ * STALE. `segmentIndex` is rebuilt on every draft save, so "the id still+ * exists" is not proof; get this wrong and every save silently verifies a+ * lens against the wrong chapter.+ * 2. A work with no lens produces the same analysis it did before the feature.+ * 3. No Series / Issue / universe record is created at any point.+ *+ * Synthetic manuscripts only — never a real instance record.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync, readdirSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';++let tempRoot;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makePathsProxy(actual, { dataRoot: () => tempRoot });+});+vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: vi.fn() }));+vi.mock('../bibleExtractor.js', () => ({ extractBible: vi.fn() }));+vi.mock('../sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));+vi.mock('../mediaCollections.js', () => ({ addItem: vi.fn(), ERR_DUPLICATE: 'DUP' }));++const { runStagedLLM } = await import('../stageRunner.js');+const { runAnalysis } = await import('./evaluator.js');+const { createWork, saveDraftBody } = await import('./local.js');+const { createCharacter, updateCharacter } = await import('./characters.js');++const EVALUATE_JSON = JSON.stringify({+ logline: 'A salvager stops keeping score.',+ summary: 'She works the harbor.',+ themes: [], strengths: [], issues: [], suggestions: [],+});++// `# Ledger` is seg-001, `# Harbor` is seg-002.+const MANUSCRIPT = [+ '# Ledger',+ '',+ 'She balanced the books before she balanced anything else.',+ '',+ '# Harbor',+ '',+ 'She let the boat go without counting what it cost her.',+ '',+].join('\n');++const stage = (stageId, evidence, extra = {}) => ({+ stageId,+ characterChoice: 'She lets the boat go.',+ evidence,+ ...extra,+});++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-evolution-lens-'));+ vi.mocked(runStagedLLM).mockReset();+ vi.mocked(runStagedLLM).mockResolvedValue({ content: EVALUATE_JSON, model: 'test-model', providerId: 'test-provider' });+});+afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+});++async function seedWork(body = MANUSCRIPT) {+ const work = await createWork({ title: 'Example Work', kind: 'short-story' });+ await saveDraftBody(work.id, body);+ return work.id;+}++const lastVariables = () => vi.mocked(runStagedLLM).mock.calls.at(-1)[1];++describe('writers room evaluate — five-stage evolution lens (#6445)', () => {+ it('renders an authored lens beside the framework block, anchored to this draft', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Wren Calloway',+ lie: 'I only matter while the ledger balances.',+ evolution: {+ outcome: 'full-change',+ outcomeNote: 'She stops keeping score.',+ stages: [stage('final-proof', { segmentId: 'seg-002', anchorQuote: 'let the boat go' })],+ },+ });++ await runAnalysis(workId, { kind: 'evaluate' });++ const variables = lastVariables();+ expect(variables.characterEvolution).toContain('- Wren Calloway');+ expect(variables.characterEvolution).toContain('declared outcome: full-change');+ expect(variables.characterEvolution).toContain('[anchored]');+ // The framework block is unchanged and still rendered alongside it.+ expect(JSON.parse(variables.castFrameworkJson)[0].lie)+ .toBe('I only matter while the ledger balances.');+ });++ it('omits the variable entirely when nobody has authored a lens', async () => {+ const workId = await seedWork();+ await createCharacter(workId, { name: 'Wren Calloway', lie: 'I only matter while the ledger balances.' });++ const analysis = await runAnalysis(workId, { kind: 'evaluate' });++ const variables = lastVariables();+ expect(variables).not.toHaveProperty('characterEvolution');+ // …and the snapshot the writer sees is exactly the pre-#6445 shape.+ expect(analysis.status).toBe('succeeded');+ expect(analysis.result).toEqual(JSON.parse(EVALUATE_JSON));+ });++ it('marks a stage stale — keeping its prose — once the draft edit deletes its segment', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Wren Calloway',+ evolution: {+ outcome: 'full-change',+ stages: [stage('final-proof', { segmentId: 'seg-002', anchorQuote: 'let the boat go' })],+ },+ });++ await runAnalysis(workId, { kind: 'evaluate' });+ expect(lastVariables().characterEvolution).toContain('[anchored]');++ // The writer cuts the closing chapter. `seg-002` no longer exists.+ await saveDraftBody(workId, '# Ledger\n\nShe balanced the books before she balanced anything else.\n');+ await runAnalysis(workId, { kind: 'evaluate' });++ const block = lastVariables().characterEvolution;+ expect(block).toContain('[stale]');+ expect(block).not.toContain('[anchored]');+ expect(block).toContain('choice: She lets the boat go.');+ });++ it('marks a stage stale when a new chapter renumbers its segment onto other prose', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Wren Calloway',+ evolution: {+ outcome: 'full-change',+ stages: [stage('final-proof', { segmentId: 'seg-002', anchorQuote: 'let the boat go' })],+ },+ });++ // A prologue pushes every heading down one. `seg-002` still RESOLVES — it+ // now covers the old first chapter — so only the quote catches the drift.+ await saveDraftBody(workId, `# Prologue\n\nThe harbor master kept his own ledger.\n\n${MANUSCRIPT}`);+ await runAnalysis(workId, { kind: 'evaluate' });++ expect(lastVariables().characterEvolution).toContain('[stale]');+ expect(lastVariables().characterEvolution).not.toContain('[anchored]');+ });++ it('carries a declared tragic-refusal / flat-testing ending through as a declaration', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Dov Marchetti',+ evolution: {+ outcome: 'tragic-refusal',+ outcomeNote: 'He balances the ledger one last time.',+ stages: [stage('cost-tested', { segmentId: 'seg-001', anchorQuote: 'balanced the books' })],+ },+ });+ await createCharacter(workId, {+ name: 'Ilsa Renn',+ evolution: {+ outcome: 'flat-testing',+ stages: [stage('final-proof', { segmentId: 'seg-002', anchorQuote: 'let the boat go' })],+ },+ });++ await runAnalysis(workId, { kind: 'evaluate' });++ const block = lastVariables().characterEvolution;+ expect(block).toContain('declared outcome: tragic-refusal — He balances the ledger one last time.');+ expect(block).toContain('declared outcome: flat-testing');+ });++ it('keeps analysis snapshots pinned to the draft contentHash across a lens edit', async () => {+ const workId = await seedWork();+ const character = await createCharacter(workId, {+ name: 'Wren Calloway',+ evolution: { outcome: 'partial-open', stages: [stage('cost-tested', { segmentId: 'seg-001' })] },+ });+ const first = await runAnalysis(workId, { kind: 'evaluate' });++ // Editing the lens does not touch the draft, so a re-run pins the same hash.+ await updateCharacter(workId, character.id, {+ evolution: { outcome: 'full-change', stages: [stage('final-proof', { segmentId: 'seg-002' })] },+ });+ const second = await runAnalysis(workId, { kind: 'evaluate' });++ expect(second.sourceContentHash).toBe(first.sourceContentHash);+ expect(second.draftVersionId).toBe(first.draftVersionId);+ expect(second.id).toBe('evaluate');+ });++ it('never promotes the work — no series, issue or universe record is created', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Wren Calloway',+ evolution: {+ outcome: 'full-change',+ stages: [stage('final-proof', { segmentId: 'seg-002', anchorQuote: 'let the boat go' })],+ },+ });++ await runAnalysis(workId, { kind: 'evaluate' });++ // The lens is reviewed AS A WRITERS ROOM WORK: the only thing this pass may+ // write is the work's own tree.+ expect(readdirSync(tempRoot).sort()).toEqual(['writers-room']);+ });+});++/**+ * The five validation scenarios in #6418 are editorial JUDGEMENTS — no+ * deterministic test can decide whether a model flagged a tragic refusal as a+ * flat arc. What IS deterministic, and what actually decides those verdicts, is+ * whether the shipped template carries the ruling for each one. This pins the+ * rulings; the prompt-migration tests pin that installs receive them.+ */+describe('shipped writers-room-evaluate template — lens rulings', () => {+ const body = readFileSync(+ join(dirname(fileURLToPath(import.meta.url)), '../../../data.reference/prompts/stages/writers-room-evaluate.md'),+ 'utf-8',+ );++ it('gates the whole block on an authored lens, so a work without one is unchanged', () => {+ expect(body).toContain('{{#characterEvolution}}');+ expect(body).toContain('{{/characterEvolution}}');+ expect(body).toContain('{{characterEvolution}}');+ });++ it('rules each declared outcome, including the two that are intended endings', () => {+ // 1. earned full transformation — behavioral proof, not an external win.+ expect(body).toMatch(/`full-change`[\s\S]{0,400}behavioral proof/);+ // 2. tragic refusal — not a flat/failed arc.+ expect(body).toMatch(/`tragic-refusal`[\s\S]{0,400}Do not flag it as a flat or failed arc/);+ // 3. deliberate flat/testing — constancy is the point.+ expect(body).toMatch(/`flat-testing`[\s\S]{0,400}do not flag it as a flat arc/);+ // 4. partial/open — incompleteness is not a finding.+ expect(body).toMatch(/`partial-open`[\s\S]{0,400}Incompleteness itself is NOT an issue/);+ // 5. external victory with no behavioral proof IS a finding.+ expect(body).toContain('defeating an external obstacle');+ // An undeclared lens is provisional planning, not a declared flat arc.+ expect(body).toMatch(/`undeclared`[\s\S]{0,200}provisional planning/);+ });++ it('refuses to read a stale or unverified anchor as proof', () => {+ expect(body).toContain('[stale]');+ expect(body).toContain('[unverified]');+ expect(body).toContain('NOT PROVEN');+ });++ it('keeps the two failure modes separate, with different repairs', () => {+ expect(body).toContain('No authored intent:');+ expect(body).toContain('Authored intent not delivered:');+ expect(body).toContain('never merge them into one issue');+ });++ it('states the non-negotiables that keep the lens from becoming a gate', () => {+ expect(body).toContain('OPTIONAL');+ expect(body).toContain('NOT a page count, a chapter count, or a percentage layout');+ expect(body).toContain('Not every character transforms');+ expect(body).toContain('a character with no lens is judged exactly as they were before');+ });+});diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex 4dcc436375..5cf1c7a485 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -15,7 +15,9 @@ import { extractScenes, SOURCE_KIND } from '../sceneExtractor.js';import { BIBLE_KIND } from '../../lib/storyBible.js';import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { CUT_TYPES } from '../../lib/editorial/cutApplier.js';-import { getWorkWithBody, ensureWorkMediaCollection } from './local.js';+import {+ getWorkWithBody, ensureWorkMediaCollection, buildSegmentIndex, renderWorkCharacterEvolutions,+} from './local.js';import { addItem as addCollectionItem, ERR_DUPLICATE } from '../mediaCollections.js';import { pickCastFramework } from '../../lib/characterFramework.js';import { listCharacters, mergeExtractedCharacters } from './characters.js';@@ -438,8 +440,22 @@ export async function runAnalysis(workId, { kind } = {}) {// is a local file read, not an LLM call: nothing here fires until the user// asks for an analysis.if (kind === 'evaluate') {- const cast = pickCastFramework(await listCharacters(workId));+ const characters = await listCharacters(workId);+ const cast = pickCastFramework(characters);if (cast.length) variables.castFrameworkJson = JSON.stringify(cast, null, 2);+ // Retrospective five-stage lens (#6445). Rendered alongside the framework+ // block above, anchored to THIS draft's segment index — so a stage whose+ // `segmentId` no longer resolves, or whose `anchorQuote` has drifted off+ // the passage it names, reaches the model annotated `[stale]` instead of+ // as proof. `null` when nobody authored a lens, which leaves `variables`+ // (and therefore the prompt and the snapshot) exactly as they were before+ // this feature existed. Still a local read: no promotion to Pipeline, and+ // no extra provider call.+ const evolution = renderWorkCharacterEvolutions(characters, {+ segmentIndex: draft?.segmentIndex || buildSegmentIndex(body),+ text: body,+ });+ if (evolution) variables.characterEvolution = evolution;}const { content, model: usedModel, providerId: usedProvider } = await runStagedLLM(stage, variables, {source: `writers-room-${kind}`,diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsindex 671ad96e75..a87c591aae 100644--- a/server/services/writersRoom/local.js+++ b/server/services/writersRoom/local.js@@ -19,6 +19,7 @@ import { readFile } from 'fs/promises';import { atomicWrite, ensureDir, rmGuarded } from '../../lib/fileUtils.js';import { countWords } from '../../lib/textUtils.js';import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';+import { renderCharacterEvolutionListForPrompt } from '../../lib/characterEvolution.js';import { sanitizeVoiceExemplars, renderVoiceExemplars } from '../../lib/styleGuide.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { nowIso, badRequest, notFound, wrWorkDir, wrDraftPath } from './_shared.js';@@ -92,6 +93,61 @@ export function buildSegmentIndex(text) {return segments;}+// ---------- retrospective evolution-lens anchors (#6445) ----------++/**+ * The reference set a Writers Room evolution-lens anchor resolves against: a+ * Map of `segmentId` -> that segment's prose, ready for+ * `evolutionEvidenceStatus` / `renderCharacterEvolutionForPrompt`.+ *+ * A Map rather than a Set of ids because a `seg-NNN` is POSITIONAL. The index+ * is rebuilt from scratch by every `saveDraftBody`, so inserting one chapter+ * heading renumbers every segment after it: the id `seg-003` survives the edit+ * while naming a different chapter. Resolving the id alone would therefore+ * report a lens stage as proven against prose it was never written for — the+ * exact "silently verified" failure epic #6418 forbids. Handing the passage+ * text in lets the shared leaf check the stage's `anchorQuote` and report+ * `stale` when the anchor has drifted.+ *+ * A stage with no quote gets the weaker existence check the other hosts get;+ * the editor asks for a quote, and the prompt block reports the resulting+ * status verbatim, so an unquoted anchor is never presented as more than it is.+ */+export function segmentEvidenceRefs(segmentIndex, text) {+ const body = typeof text === 'string' ? text : '';+ const segments = (Array.isArray(segmentIndex) ? segmentIndex : [])+ .filter((segment) => segment && typeof segment.id === 'string');+ // Sentinel, not an empty container: OMITTING the key means "not checked+ // here", which the shared leaf reports as `unverified`. An empty Map would+ // mean "checked, and nothing exists" and would condemn every authored anchor+ // as stale the moment a caller forgot to pass the index.+ if (!segments.length) return {};+ return {+ segmentIds: new Map(segments.map((segment) => [segment.id, body.slice(segment.start, segment.end)])),+ };+}++/**+ * Every authored evolution lens across a work's cast, as one compact prompt+ * block — or `null` when nobody has authored one, which is what keeps a work+ * with no lens byte-identical to its pre-#6445 analysis.+ *+ * The Writers Room companion to `renderCharacterEvolutionsForPrompt`+ * (`seriesCharacterArc.js`): same shared renderer, same stage vocabulary, same+ * `[stale]` / `[unverified]` annotations — only the reference set differs,+ * because this host anchors to manuscript segments instead of authored beats.+ * Nothing here promotes the work to a Pipeline series; it is a read over the+ * per-work cast bible and the draft body.+ */+export function renderWorkCharacterEvolutions(characters, { segmentIndex, text } = {}) {+ const refs = segmentEvidenceRefs(segmentIndex, text);+ return renderCharacterEvolutionListForPrompt(+ (Array.isArray(characters) ? characters : [])+ .map((character) => ({ characterName: character?.name, evolution: character?.evolution })),+ refs,+ );+}+// ---------- folder CRUD ----------export async function listFolders() {diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.jsindex 050a1e8f03..4de9939d0a 100644--- a/server/services/writersRoom/local.test.js+++ b/server/services/writersRoom/local.test.js@@ -20,6 +20,7 @@ const {listExercises, createExercise, finishExercise, discardExercise, promoteExercise,resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,renderWorkVoiceGuide,+ segmentEvidenceRefs, renderWorkCharacterEvolutions,} = local;beforeEach(() => {@@ -517,3 +518,136 @@ describe('live mode (Phase 5)', () => {expect(r3.renderUsage).toEqual({ date: '2026-06-04', count: 1 });});});++// ---------------------------------------------------------------------------+// Retrospective five-stage evolution lens anchored to manuscript segments+// (#6445, epic #6418). Synthetic manuscripts only — never a real instance+// record.+// ---------------------------------------------------------------------------++// A short two-chapter manuscript. `# Ledger` is seg-001, `# Harbor` is seg-002.+const MANUSCRIPT = [+ '# Ledger',+ '',+ 'She balanced the books before she balanced anything else.',+ '',+ '# Harbor',+ '',+ 'She let the boat go without counting what it cost her.',+ '',+].join('\n');++const lensCharacter = (name, outcome, evidence, extra = {}) => ({+ name,+ evolution: {+ outcome,+ stages: [{+ stageId: 'final-proof',+ characterChoice: 'She lets the boat go.',+ evidence,+ ...extra,+ }],+ },+});++describe('retrospective evolution-lens anchors (#6445)', () => {+ const segments = () => buildSegmentIndex(MANUSCRIPT);++ it('maps every segment id to the prose it currently covers', () => {+ const { segmentIds } = segmentEvidenceRefs(segments(), MANUSCRIPT);+ expect([...segmentIds.keys()]).toEqual(['seg-001', 'seg-002']);+ expect(segmentIds.get('seg-002')).toContain('let the boat go');+ expect(segmentIds.get('seg-001')).not.toContain('let the boat go');+ });++ it('renders nothing at all when no character carries a lens', () => {+ const cast = [{ name: 'Wren Calloway', lie: 'I only matter while I am useful.' }];+ expect(renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT })).toBeNull();+ expect(renderWorkCharacterEvolutions([], { segmentIndex: segments(), text: MANUSCRIPT })).toBeNull();+ });++ it('annotates a resolving, quote-matched anchor as anchored', () => {+ const cast = [lensCharacter('Wren Calloway', 'full-change', {+ segmentId: 'seg-002', anchorQuote: 'let the boat go',+ })];+ const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });+ expect(block).toContain('declared outcome: full-change');+ expect(block).toContain('segment seg-002');+ expect(block).toContain('[anchored]');+ });++ it('marks an anchor stale — keeping the authored prose — once its segment is gone', () => {+ const shortened = '# Ledger\n\nShe balanced the books before she balanced anything else.\n';+ const cast = [lensCharacter('Wren Calloway', 'full-change', {+ segmentId: 'seg-002', anchorQuote: 'let the boat go',+ })];+ const block = renderWorkCharacterEvolutions(cast, {+ segmentIndex: buildSegmentIndex(shortened), text: shortened,+ });+ expect(block).toContain('[stale]');+ expect(block).not.toContain('[anchored]');+ // Preserved, never silently dropped: the prose and the re-anchoring quote+ // both survive so the writer can re-point the stage.+ expect(block).toContain('choice: She lets the boat go.');+ expect(block).toContain('let the boat go');+ });++ it('marks an anchor stale when renumbering leaves the id on a different passage', () => {+ // A new opening chapter renumbers everything below it: the old `seg-002`+ // still EXISTS, and now covers prose the stage was never written for. The+ // quote is what catches it — an existence check alone would read "anchored".+ const expanded = `# Prologue\n\nThe harbor master kept his own ledger.\n\n${MANUSCRIPT}`;+ const cast = [lensCharacter('Wren Calloway', 'full-change', {+ segmentId: 'seg-002', anchorQuote: 'let the boat go',+ })];+ const block = renderWorkCharacterEvolutions(cast, {+ segmentIndex: buildSegmentIndex(expanded), text: expanded,+ });+ expect(block).toContain('[stale]');+ expect(block).not.toContain('[anchored]');+ });++ it('reports an unquoted anchor as resolved but never invents a quote check', () => {+ const cast = [lensCharacter('Wren Calloway', 'partial-open', { segmentId: 'seg-001' })];+ const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });+ expect(block).toContain('[anchored]');+ expect(block).not.toContain('quote');+ });++ it('reports a quote with no segment as unverified rather than proven', () => {+ const cast = [lensCharacter('Wren Calloway', 'full-change', { anchorQuote: 'let the boat go' })];+ const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });+ expect(block).toContain('[unverified]');+ expect(block).not.toContain('[anchored]');+ });++ it('carries all four declared outcomes verbatim, including the two that are endings', () => {+ const cast = [+ lensCharacter('Wren Calloway', 'full-change', { segmentId: 'seg-002', anchorQuote: 'let the boat go' }),+ lensCharacter('Dov Marchetti', 'tragic-refusal', { segmentId: 'seg-001', anchorQuote: 'balanced the books' }),+ lensCharacter('Ilsa Renn', 'flat-testing', { segmentId: 'seg-001', anchorQuote: 'balanced the books' }),+ lensCharacter('Peto Vane', 'partial-open', { segmentId: 'seg-002', anchorQuote: 'let the boat go' }),+ ];+ const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });+ for (const outcome of ['full-change', 'tragic-refusal', 'flat-testing', 'partial-open']) {+ expect(block).toContain(`declared outcome: ${outcome}`);+ }+ // One block per character, each nested under its own name.+ for (const name of ['Wren Calloway', 'Dov Marchetti', 'Ilsa Renn', 'Peto Vane']) {+ expect(block).toContain(`- ${name}`);+ }+ });++ it('renders an undeclared lens as undeclared rather than assuming an outcome', () => {+ const cast = [lensCharacter('Wren Calloway', null, { segmentId: 'seg-002', anchorQuote: 'let the boat go' })];+ const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });+ expect(block).toContain('declared outcome: undeclared');+ });++ it('tolerates a work with no draft body at all', () => {+ const cast = [lensCharacter('Wren Calloway', 'full-change', { segmentId: 'seg-001' })];+ const block = renderWorkCharacterEvolutions(cast, {});+ // Nothing to resolve against — unverified, never anchored.+ expect(block).toContain('[unverified]');+ });+});