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: model an optional five-stage character evolution lens on series and FableLoom plans (#6440)

[._.]/ Adam Eivy376824431458
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 86c3b79032..e885931e2d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -51,6 +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). |
| `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
new file mode 100644
index 0000000000..1bb926a42b
--- /dev/null
+++ b/client/src/lib/characterEvolution.js
@@ -0,0 +1,83 @@
+/**
+ * The five-stage character evolution lens as the editors consume it (#6440).
+ *
+ * Re-exports the vocabularies from the pure server leaf
+ * `server/lib/characterEvolution.js` — imported rather than copied so the two
+ * runtimes cannot drift — and adds the editor-only descriptors (label,
+ * placeholder, per-field cap) the arc and FableLoom plan editors render.
+ * Exactly how `client/src/lib/characterFramework.js` mirrors
+ * `server/lib/characterFramework.js`; a guard in
+ * `server/lib/characterEvolution.test.js` fails if this file ever restates a
+ * vocabulary instead of re-exporting it.
+ *
+ * The lens is OPTIONAL everywhere it appears: an editor renders it unset by
+ * default, and clearing every field is a real clear that sanitizes the whole
+ * lens back to absent.
+ */
+import {
+ CHARACTER_EVOLUTION_LIMITS,
+ EVOLUTION_EVIDENCE_FIELDS,
+ EVOLUTION_EVIDENCE_STATUSES,
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_STAGES,
+ EVOLUTION_STAGE_LABELS,
+ EVOLUTION_STAGE_TEXT_FIELDS,
+ evolutionEvidenceStatus,
+ isDeclaredEvolution,
+} from '../../../server/lib/characterEvolution.js';
+
+export {
+ CHARACTER_EVOLUTION_LIMITS,
+ // Which anchor fields each host offers — the series arc points at an issue,
+ // a scene anchor or an authored transition beat; a FableLoom lens at an
+ // episode and an outline scene key.
+ EVOLUTION_EVIDENCE_FIELDS,
+ EVOLUTION_EVIDENCE_STATUSES,
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_STAGES,
+ EVOLUTION_STAGE_LABELS,
+ EVOLUTION_STAGE_TEXT_FIELDS,
+ // Derived on read, never persisted — only `anchored` means verified.
+ evolutionEvidenceStatus,
+ isDeclaredEvolution,
+};
+
+// The four prose fields of one stage, in authoring order, with the copy an
+// editor renders. Kept beside the field list rather than inside a component so
+// the series arc editor and the FableLoom plan editor ask the same questions.
+export const EVOLUTION_STAGE_EDITOR_FIELDS = Object.freeze([
+ {
+ name: 'testedBelief',
+ label: 'Belief under test',
+ placeholder: 'the operating rule this stage puts pressure on — it need not be the literal opposite of what they end up believing',
+ max: CHARACTER_EVOLUTION_LIMITS.testedBelief,
+ },
+ {
+ name: 'externalPressure',
+ label: 'External pressure',
+ placeholder: 'what the story does TO them here — the event, not the feeling',
+ max: CHARACTER_EVOLUTION_LIMITS.externalPressure,
+ },
+ {
+ name: 'characterChoice',
+ label: 'Character choice',
+ placeholder: 'what they actively decide in response — behavior, not realization alone',
+ max: CHARACTER_EVOLUTION_LIMITS.characterChoice,
+ },
+ {
+ name: 'causalConsequence',
+ label: 'Causal consequence',
+ placeholder: 'what that choice causes — the link the next stage builds on',
+ max: CHARACTER_EVOLUTION_LIMITS.causalConsequence,
+ },
+]);
+
+// What each declared outcome means, so a writer picks the honest one instead of
+// defaulting to full change. All four are first-class endings, and declaring
+// one is what stops a review reading a deliberate flat arc as a gap.
+export const EVOLUTION_OUTCOME_HINTS = Object.freeze({
+ 'full-change': 'the changed behavior endures past the final cost',
+ 'tragic-refusal': 'they double down on the control belief and pay for it',
+ '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',
+});
diff --git a/client/src/lib/characterEvolution.test.js b/client/src/lib/characterEvolution.test.js
new file mode 100644
index 0000000000..e72c1182b5
--- /dev/null
+++ b/client/src/lib/characterEvolution.test.js
@@ -0,0 +1,37 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CHARACTER_EVOLUTION_LIMITS,
+ EVOLUTION_EVIDENCE_FIELDS,
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_OUTCOME_HINTS,
+ EVOLUTION_STAGES,
+ EVOLUTION_STAGE_EDITOR_FIELDS,
+ EVOLUTION_STAGE_LABELS,
+ EVOLUTION_STAGE_TEXT_FIELDS,
+} from './characterEvolution.js';
+
+// The editor copy is hand-written here while the vocabularies are re-exported
+// from the server leaf, so these assert the half that CAN drift: a descriptor
+// naming a field, stage or outcome the server does not have would render an
+// input whose value the sanitizer silently drops. (The re-exports themselves
+// are guarded on the server side, where a source check can tell a re-export
+// from a hand-copied literal.)
+describe('editor descriptors track the shared vocabularies', () => {
+ it('gives every stage a label and every outcome a hint', () => {
+ expect(Object.keys(EVOLUTION_STAGE_LABELS).sort()).toEqual([...EVOLUTION_STAGES].sort());
+ expect(Object.keys(EVOLUTION_OUTCOME_HINTS).sort()).toEqual([...EVOLUTION_OUTCOMES].sort());
+ });
+
+ it('describes exactly the four authored stage fields, at the server caps', () => {
+ expect(EVOLUTION_STAGE_EDITOR_FIELDS.map((f) => f.name)).toEqual([...EVOLUTION_STAGE_TEXT_FIELDS]);
+ for (const field of EVOLUTION_STAGE_EDITOR_FIELDS) {
+ expect(field.max, field.name).toBe(CHARACTER_EVOLUTION_LIMITS[field.name]);
+ expect(field.label && field.placeholder, field.name).toBeTruthy();
+ }
+ });
+
+ it('splits the anchor vocabulary by host without overlap', () => {
+ const { pipelineSeries, fableLoom } = EVOLUTION_EVIDENCE_FIELDS;
+ expect(pipelineSeries.some((name) => fableLoom.includes(name))).toBe(false);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 782550d8b2..2e4e5be16a 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -25,6 +25,7 @@ export * from './autopilotMilestones.js';
export * from './beatColors.js';
export * from './beatGrid.js';
export * from './bibleLimits.js';
+export * from './characterEvolution.js';
export * from './characterFramework.js';
export * from './characterIntegrity.js';
export * from './catalogTypes.js';
diff --git a/server/lib/README.md b/server/lib/README.md
index 3fa1b4198b..5db04310fe 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -110,6 +110,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. |
| `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. |
| `storyBible.js` | Canonical Character / Place / Object shapes; re-exports `BIBLE_LIMITS` from `bibleLimits.js`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |
+| `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. |
+| `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). |
| `characterIntegrity.js` | The shared cast-integrity contract (#6415): `INTEGRITY_FINDING_KINDS` (`missing` / `underspecified` / `contradictory`), the five `INTEGRITY_DIMENSIONS`, `CHARACTER_REVIEW_STATUSES` (`passed` vs `not-reviewed` / `truncated` / `stale` — incomplete coverage can never read as clean), `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` / `staleReportCharacterIds` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
| `castIntegrityPrompt.js` | The prompt-facing render of a `characterIntegrity.js` report (#6415): `renderCastIntegrity` (gap rows first, header always kept, so a budget-truncated block can never read as a clean cast) and `INTEGRITY_DEPTH_NOTES` (the `explained` / `light` / `full` rulings in the reviewer's own words). Shared by the Series foundation judge and the FableLoom whole-series editor so the two cannot drift on what a `light` character owes. |
@@ -443,7 +445,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
-| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`); `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (a guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — the escape half is mirrored on the client at `client/src/lib/textUtils.js`, which the browser imports since it cannot reach `server/lib`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels); `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
+| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`); `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (a guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — the escape half is mirrored on the client at `client/src/lib/textUtils.js`, which the browser imports since it cannot reach `server/lib`); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels); `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
| `postAppliedNumeracy.js` | Pure seeded Applied Numeracy pack — everyday percentage, ratio, unit, rate, and estimation scenarios plus server-authoritative numeric/fraction/unit scoring with explicit tolerance handling. |
diff --git a/server/lib/bibleLimits.js b/server/lib/bibleLimits.js
index 15ca6ec613..ffb979cd38 100644
--- a/server/lib/bibleLimits.js
+++ b/server/lib/bibleLimits.js
@@ -71,6 +71,37 @@ export const BIBLE_LIMITS = Object.freeze({
PSYCHOLOGY_NOTE_MAX: 800,
// Per-drive desire + fear.
PSYCHOLOGY_DRIVE_FIELD_MAX: 400,
+ // Five-stage character evolution lens (#6440) — the OPTIONAL, story-scoped
+ // craft lens layered over the universe-level psychology profile above. It
+ // records, per stage, the belief under test, the pressure applied, the
+ // choice made, and what that choice caused. The lens lives on a series arc
+ // (or a FableLoom plan), never on the universe character: a story's realized
+ // change must not overwrite world-level identity. Absent on every record
+ // that has not authored one.
+ EVOLUTION_TESTED_BELIEF_MAX: 600,
+ EVOLUTION_EXTERNAL_PRESSURE_MAX: 800,
+ EVOLUTION_CHARACTER_CHOICE_MAX: 800,
+ EVOLUTION_CAUSAL_CONSEQUENCE_MAX: 800,
+ // Why this outcome was DECLARED. Same job as PSYCHOLOGY_NOTE_MAX: a
+ // deliberate flat or tragic-refusal arc has to read as an authored decision,
+ // not as an unfilled transformation.
+ EVOLUTION_OUTCOME_NOTE_MAX: 800,
+ // Evidence anchors reuse each host's existing vocabulary rather than a new
+ // one: a free-text scene anchor (as `characterArcs[].transitions[]` uses),
+ // and opaque record pointers (`trn-` transition, `ep-` episode, an outline
+ // scene key). The pointer cap comfortably fits a prefixed uuid and an
+ // 80-char outline key.
+ EVOLUTION_EVIDENCE_ANCHOR_MAX: 300,
+ EVOLUTION_EVIDENCE_REF_MAX: 120,
+ // Lenses per FableLoom plan — one per character, matching
+ // CHARACTER_ARC_LIMITS.ARCS_PER_SERIES_MAX (the pipeline host nests its
+ // lenses inside that already-capped arc list instead).
+ EVOLUTIONS_PER_PLAN_MAX: 60,
+ // Upper bound for an issue number a story beat anchors to. Read by BOTH
+ // `seriesCharacterArc.js` (CHARACTER_ARC_LIMITS.ISSUE_MAX) and the evolution
+ // lens, so the two anchor vocabularies cannot drift apart. Generous enough
+ // for any real series while still rejecting a hallucinated integer.
+ STORY_ISSUE_NUMBER_MAX: 9999,
// Secrets the character keeps (≥2 encouraged in the prompt). Short prose
// items, capped per-item and per-character like other string lists.
SECRET_MAX: 600,
diff --git a/server/lib/characterEvolution.js b/server/lib/characterEvolution.js
new file mode 100644
index 0000000000..6bfb38a960
--- /dev/null
+++ b/server/lib/characterEvolution.js
@@ -0,0 +1,416 @@
+/**
+ * The OPTIONAL five-stage character evolution lens (#6440, epic #6418).
+ *
+ * A story-scoped craft lens layered over the universe-level psychology profile
+ * in `characterFramework.js` (Ghost → Wound → Lie → Want → Need, theory of
+ * control, drives). That profile is the character's baseline IDENTITY and is
+ * owned by the universe; this module models what ONE story does to it — the
+ * belief it puts under test, the pressure it applies, the choice the character
+ * makes, and what that choice causes. A series/work/branch's realized change
+ * must never be written back over world-level identity, which is why the lens
+ * hangs off the story record (`series.characterArcs[].evolution`,
+ * `loom.seriesPlan.characterEvolutions[]`) and links to the cast by character
+ * id alone.
+ *
+ * Deliberate non-rules, carried from #6418:
+ * - The lens is OPTIONAL. Every arc, beat structure and authored transition
+ * kind stays valid with it unset; nothing here becomes a gate.
+ * - The five stages are a craft lens over authored beats, NOT a page count,
+ * a chapter count, or a percentage layout.
+ * - The changed belief need not be the literal negation of the tested one.
+ * - Not every character transforms. `tragic-refusal`, `flat-testing` and
+ * `partial-open` are DECLARED outcomes, not defects — declaring one is what
+ * stops a downstream review reading a deliberate flat arc as a gap.
+ * - Stages are SPARSE: a lens with only stages 1 and 3 authored is valid.
+ *
+ * A PURE LEAF (imports only `bibleLimits.js` + the dependency-free trim
+ * helpers in `textUtils.js`), matching `characterFramework.js`, so
+ * `client/src/lib/characterEvolution.js` can re-export the vocabularies into
+ * the browser bundle without dragging `crypto` / `fileUtils` along. That
+ * purity is why a stage has no minted uuid: `stageId` is the identity (one
+ * 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.
+ */
+
+import { BIBLE_LIMITS } from './bibleLimits.js';
+import { trimTo, trimToClause } from './textUtils.js';
+
+// Storr's sequence as #6418 restates it, in order: the control strategy is
+// visibly failing; an event forces exploration of another way; the character
+// commits to a changed strategy; consequences test whether they can bear its
+// cost; a final choice and its aftermath demonstrate enduring change (or
+// refusal). An unknown stage id is REJECTED rather than coerced — a beat that
+// cannot be placed in the sequence cannot be reasoned about, and silently
+// snapping it to a neighbouring stage would fabricate authored intent.
+export const EVOLUTION_STAGES = Object.freeze([
+ 'control-strategy-failing',
+ 'pressure-forces-exploration',
+ 'commitment-to-change',
+ 'cost-tested',
+ 'final-proof',
+]);
+
+// The four DECLARED outcome kinds. `full-change` = the change endures;
+// `tragic-refusal` = the character doubles down on the control belief;
+// `flat-testing` = the belief is tested and deliberately holds (the character
+// changes the world instead of themselves); `partial-open` = only some of the
+// change is earned, or the ending leaves it genuinely open. All four are
+// first-class authored endings — none is a finding.
+export const EVOLUTION_OUTCOMES = Object.freeze([
+ 'full-change',
+ 'tragic-refusal',
+ 'flat-testing',
+ 'partial-open',
+]);
+
+// The prose half of one stage, in authoring order.
+export const EVOLUTION_STAGE_TEXT_FIELDS = Object.freeze([
+ 'testedBelief', 'externalPressure', 'characterChoice', 'causalConsequence',
+]);
+
+// Per-field caps keyed by field name (mirrors CHARACTER_PSYCHOLOGY_LIMITS) so a
+// Zod schema or an editor sizes every input from one map instead of
+// re-deriving the `<FIELD>_MAX` naming convention.
+export const CHARACTER_EVOLUTION_LIMITS = Object.freeze({
+ testedBelief: BIBLE_LIMITS.EVOLUTION_TESTED_BELIEF_MAX,
+ externalPressure: BIBLE_LIMITS.EVOLUTION_EXTERNAL_PRESSURE_MAX,
+ characterChoice: BIBLE_LIMITS.EVOLUTION_CHARACTER_CHOICE_MAX,
+ causalConsequence: BIBLE_LIMITS.EVOLUTION_CAUSAL_CONSEQUENCE_MAX,
+ outcomeNote: BIBLE_LIMITS.EVOLUTION_OUTCOME_NOTE_MAX,
+ characterName: BIBLE_LIMITS.NAME_MAX,
+ atSceneAnchor: 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,
+ LENSES_PER_PLAN_MAX: BIBLE_LIMITS.EVOLUTIONS_PER_PLAN_MAX,
+});
+
+// How much a stage's evidence anchor actually PROVES. Only `anchored` counts
+// as verified — the epic's non-negotiable is that a missing or stale anchor can
+// never read as verified, so every other value must fail an "is this proven?"
+// test:
+// `unanchored` — nothing authored. Not a defect on its own (the lens is a
+// plan; evidence arrives when the beat does), just unproven.
+// `unverified` — a pointer is authored but the caller supplied no reference
+// set to check it against. Unknown, therefore not verified.
+// `anchored` — every authored pointer resolves against the host record.
+// `stale` — at least one authored pointer names something that no
+// longer exists. PRESERVED, never silently dropped, following
+// the `sanitizeStoryOutline` precedent that keeps an unknown
+// `targetKey` so `DANGLING_TRANSITION` can report it.
+export const EVOLUTION_EVIDENCE_STATUSES = Object.freeze([
+ 'unanchored', 'unverified', 'anchored', 'stale',
+]);
+
+// Shared per-character story-list primitives. They live in this leaf — the
+// lowest module both per-character story lists reach — rather than beside
+// either host, because a rule that lives in two places drifts: widen the canon
+// id shape on the arc path alone and the same id silently blanks on the lens
+// path, or refine the identity key on one side and two records that collapse
+// on the pipeline host stay split on the FableLoom host.
+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-]+$/;
+
+const isStr = (v) => typeof v === 'string';
+
+/** True for a canon cast pointer (`chr-<uuid>`). */
+export const isCanonCharacterId = (raw) => isStr(raw) && CHARACTER_ID_RE.test(raw);
+
+/** True for an authored transition-beat id (`trn-<uuid>`). */
+export const isStoryBeatId = (raw) => isStr(raw) && TRANSITION_ID_RE.test(raw);
+
+/**
+ * Dedupe key for a per-character story list: the canon pointer wins, and a
+ * case-folded name is the fallback so a name-only entry still de-dupes against
+ * itself. Read by `sanitizeCharacterArcList` and `sanitizeCharacterEvolutionList`.
+ */
+export const characterIdentityKey = (characterId, characterName) => (
+ characterId || `name:${String(characterName).trim().toLowerCase()}`
+);
+
+/**
+ * Optional non-negative issue number. Absent / non-finite → null so a caller
+ * can tell "no issue pinned" from issue 0. Shared with the arc's transition
+ * anchors, which cap against the same `STORY_ISSUE_NUMBER_MAX`.
+ */
+export const optIssueNumber = (raw, max) => (
+ Number.isFinite(raw) ? Math.max(0, Math.min(max, Math.floor(raw))) : null
+);
+
+// A pointer is kept only when it matches its host's id shape; anything else
+// collapses to '' so a junk value can't masquerade as evidence. A well-shaped
+// pointer to a DELETED record is a different case entirely — it survives here
+// and `evolutionEvidenceStatus` reports it stale.
+const shapedRef = (raw, re) => {
+ if (!isStr(raw)) return '';
+ const value = raw.trim();
+ return re.test(value) ? value.slice(0, CHARACTER_EVOLUTION_LIMITS.evidenceRef) : '';
+};
+
+const asSet = (value) => {
+ if (value instanceof Set) return value;
+ if (Array.isArray(value)) return new Set(value);
+ return null;
+};
+
+// The anchor fields each host owns, and the ref set each resolves against.
+// ONE table so the sanitizer, the status check, the renderer, the Zod schema
+// and the client editor never enumerate the vocabulary five different ways.
+export const EVOLUTION_EVIDENCE_FIELDS = Object.freeze({
+ pipelineSeries: Object.freeze(['atIssue', 'atSceneAnchor', 'transitionId']),
+ fableLoom: Object.freeze(['episodeId', 'sceneKey']),
+});
+
+// Pointer fields that resolve against a host reference set, paired with the
+// `refs` key that carries it. `atIssue` / `atSceneAnchor` are deliberately
+// absent: they are authored locators with nothing to resolve against.
+const RESOLVABLE_ANCHORS = Object.freeze([
+ ['transitionId', 'transitionIds'],
+ ['episodeId', 'episodeIds'],
+ ['sceneKey', 'sceneKeys'],
+]);
+
+/**
+ * Sanitize one stage's evidence anchor. Returns `null` when nothing is
+ * authored so an evidence-free stage carries no empty husk.
+ *
+ * Both hosts' vocabularies live in one block on purpose — the lens shape is
+ * shared, and each host resolves only the pointers it owns:
+ * - Pipeline series: `atIssue` / `atSceneAnchor` (the same optional pair
+ * `sanitizeTransition` accepts) plus `transitionId`, naming the authored
+ * `trn-` beat that proves the stage.
+ * - FableLoom: `episodeId` (`ep-<uuid>`) plus `sceneKey` (a
+ * `storyOutline.scenes[].key`).
+ * A field the host does not use simply stays empty.
+ */
+export function sanitizeEvolutionEvidence(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const evidence = {
+ atIssue: optIssueNumber(raw.atIssue, CHARACTER_EVOLUTION_LIMITS.atIssue),
+ atSceneAnchor: trimTo(raw.atSceneAnchor, CHARACTER_EVOLUTION_LIMITS.atSceneAnchor),
+ transitionId: shapedRef(raw.transitionId, TRANSITION_ID_RE),
+ episodeId: shapedRef(raw.episodeId, EPISODE_ID_RE),
+ // Outline scene keys are author-chosen slugs with no prefix contract, so
+ // 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),
+ };
+ const authored = evidence.atIssue !== null
+ || evidence.atSceneAnchor
+ || evidence.transitionId
+ || evidence.episodeId
+ || evidence.sceneKey;
+ return authored ? evidence : null;
+}
+
+/**
+ * How much this evidence proves, given what the host record actually contains.
+ * DERIVED on read rather than persisted, so a status can never drift out of
+ * step with the record it describes and a peer can never assert its own
+ * anchors verified. Pass whichever reference sets the host owns:
+ *
+ * { transitionIds, episodeIds, sceneKeys } // Set | Array | omitted
+ *
+ * An omitted set means "not checked here" → `unverified`, never `anchored`.
+ * Returns one of EVOLUTION_EVIDENCE_STATUSES; only `anchored` is verified.
+ */
+export function evolutionEvidenceStatus(evidence, refs = {}) {
+ if (!evidence || typeof evidence !== 'object') return 'unanchored';
+ const authored = RESOLVABLE_ANCHORS.filter(([field]) => Boolean(evidence[field]));
+ // A free-text scene anchor / issue number is an authored locator with nothing
+ // to resolve against — it counts as authored evidence but can never be
+ // 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';
+ }
+ let unchecked = false;
+ for (const [field, refsKey] of authored) {
+ const known = asSet(refs[refsKey]);
+ if (!known) unchecked = true;
+ else if (!known.has(evidence[field])) return 'stale';
+ }
+ return unchecked ? 'unverified' : 'anchored';
+}
+
+/**
+ * Sanitize one stage. Returns `null` when the stage id is unknown (rejected,
+ * never coerced) or when nothing is authored under it, so `cleanStages` drops
+ * it and a sparse lens stays sparse.
+ */
+export function sanitizeEvolutionStage(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!EVOLUTION_STAGES.includes(raw.stageId)) return null;
+ const stage = { stageId: raw.stageId };
+ let authored = false;
+ for (const field of EVOLUTION_STAGE_TEXT_FIELDS) {
+ // Prose, not identifiers: `trimToClause` so an over-cap stage ends on a
+ // sentence (or at worst a whole word) rather than mid-word. A hard clip
+ // hands the next verify round a belief that stops mid-thought, which reads
+ // as an authoring gap — see the same note in `seriesCharacterArc.js`.
+ stage[field] = trimToClause(raw[field], CHARACTER_EVOLUTION_LIMITS[field]);
+ if (stage[field]) authored = true;
+ }
+ stage.evidence = sanitizeEvolutionEvidence(raw.evidence);
+ // A stage id with no prose and no anchor is an empty marker with nothing to
+ // render or reason about (mirrors `sanitizeTransition`'s label/note rule).
+ return authored || stage.evidence ? stage : null;
+}
+
+// Stages are stored in canonical sequence order, deduplicated by `stageId`
+// (last write wins) — the lens is five ORDERED stages, so a round trip that
+// re-sorted arbitrarily would never be byte-stable.
+function cleanStages(rawList) {
+ if (!Array.isArray(rawList)) return [];
+ const byStage = new Map();
+ for (const raw of rawList) {
+ const stage = sanitizeEvolutionStage(raw);
+ if (stage) byStage.set(stage.stageId, stage);
+ }
+ return EVOLUTION_STAGES.map((id) => byStage.get(id)).filter(Boolean);
+}
+
+/**
+ * Sanitize one character's evolution lens. Returns `null` when nothing is
+ * authored, mirroring `sanitizeCharacterArc`'s "no identifying content ⇒ drop"
+ * rule — so a record that never opted into the lens round-trips byte-identical.
+ *
+ * `outcome` is the DECLARATION that keeps a deliberate flat or tragic arc from
+ * reading as a defect downstream, and an unknown value is rejected outright
+ * rather than coerced to a default (which would fabricate a declaration the
+ * author never made). It is nullable rather than mandatory on purpose: an
+ * author fills stages before they know how the story lands, a peer may send a
+ * lens through an older sanitizer, and BOTH host records carry the lens inside
+ * a wholesale-replaced field — so refusing a lens with no declared outcome
+ * would delete authored prose on a partial save and 400 an unrelated edit.
+ * `isDeclaredEvolution` is the gate downstream reviews use instead; an
+ * undeclared lens is incomplete, never a declared flat arc.
+ */
+export function sanitizeCharacterEvolution(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const outcome = EVOLUTION_OUTCOMES.includes(raw.outcome) ? raw.outcome : null;
+ const outcomeNote = trimToClause(raw.outcomeNote, CHARACTER_EVOLUTION_LIMITS.outcomeNote);
+ const stages = cleanStages(raw.stages);
+ if (!outcome && !outcomeNote && stages.length === 0) return null;
+ return { outcome, outcomeNote, stages };
+}
+
+/**
+ * True only when the author has DECLARED how the arc lands. The epic's
+ * non-negotiable — a declared flat or tragic-refusal arc is first-class, not a
+ * finding — applies to declared lenses only; an undeclared one is unfinished
+ * planning and must read as such.
+ */
+export const isDeclaredEvolution = (evolution) => (
+ Boolean(evolution) && EVOLUTION_OUTCOMES.includes(evolution.outcome)
+);
+
+/**
+ * Sanitize a per-character lens LIST (`loom.seriesPlan.characterEvolutions[]`).
+ * Each entry is `{ characterId, characterName, evolution }`; entries with no
+ * identity or no authored lens are dropped, and the list dedupes by character
+ * identity exactly as `sanitizeCharacterArcList` does (canon pointer first,
+ * case-folded name as the fallback) so two lenses for one character collapse
+ * last-write-wins. Returns [] for a non-array so a pre-lens plan migrates
+ * forward without a writer pass.
+ *
+ * The pipeline host needs no equivalent: its lens nests inside the already
+ * per-character, already deduplicated `series.characterArcs[]`.
+ */
+export function sanitizeCharacterEvolutionList(rawList) {
+ if (!Array.isArray(rawList)) return [];
+ const byKey = new Map();
+ const order = [];
+ for (const raw of rawList) {
+ if (!raw || typeof raw !== 'object') continue;
+ const characterId = isCanonCharacterId(raw.characterId) ? raw.characterId : '';
+ const characterName = trimTo(raw.characterName, CHARACTER_EVOLUTION_LIMITS.characterName);
+ if (!characterId && !characterName) continue;
+ // Identity and cap are settled BEFORE the per-entry walk: a peer payload
+ // skips the route's `.max()` and reaches this sanitizer directly, so a
+ // 10k-entry list must not pay five stages of prose trimming per entry only
+ // to be dropped at the cap.
+ const key = characterIdentityKey(characterId, characterName);
+ const known = byKey.has(key);
+ if (!known && byKey.size >= CHARACTER_EVOLUTION_LIMITS.LENSES_PER_PLAN_MAX) continue;
+ const evolution = sanitizeCharacterEvolution(raw.evolution);
+ if (!evolution) continue;
+ if (!known) order.push(key);
+ byKey.set(key, { characterId, characterName, evolution });
+ }
+ return order.map((k) => byKey.get(k));
+}
+
+// Human-readable stage names for a prompt block or an editor heading. Exported
+// (rather than kept private) so `client/src/lib/characterEvolution.js` renders
+// the same words the review prompts do.
+export const EVOLUTION_STAGE_LABELS = Object.freeze({
+ 'control-strategy-failing': 'control strategy failing',
+ 'pressure-forces-exploration': 'pressure forces exploration',
+ 'commitment-to-change': 'commitment to change',
+ 'cost-tested': 'cost tested',
+ 'final-proof': 'final proof',
+});
+
+// How each authored stage field reads in a prompt block.
+const STAGE_FIELD_LABELS = Object.freeze({
+ testedBelief: 'belief under test',
+ externalPressure: 'pressure',
+ characterChoice: 'choice',
+ causalConsequence: 'consequence',
+});
+
+// One-line description of what a stage's anchor points at, for a prompt block.
+// Says nothing about whether it resolves — `evolutionEvidenceStatus` owns that.
+const describeEvidence = (evidence) => {
+ if (!evidence) return 'none';
+ 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']]) {
+ if (evidence[field]) bits.push(`${label} ${evidence[field]}`);
+ }
+ return bits.join(', ') || 'none';
+};
+
+/**
+ * Render one lens as a compact prompt block, or `null` when there is nothing
+ * to render — mirroring `renderCharacterArcsForPrompt` so every later slice of
+ * #6418 shares one renderer instead of writing three.
+ *
+ * `refs` is optional and is forwarded to `evolutionEvidenceStatus`; an anchor
+ * is annotated only when it is stale or when it resolves, so a prompt can
+ * never present an unresolvable pointer as proof.
+ */
+export function renderCharacterEvolutionForPrompt(evolution, refs = {}) {
+ if (!evolution || typeof evolution !== 'object') return null;
+ const outcome = EVOLUTION_OUTCOMES.includes(evolution.outcome) ? evolution.outcome : 'undeclared';
+ const note = isStr(evolution.outcomeNote) && evolution.outcomeNote ? ` — ${evolution.outcomeNote}` : '';
+ // Materialize the ref sets ONCE rather than per stage — a caller that hands
+ // in arrays would otherwise rebuild the same Sets five times per lens.
+ const resolved = Object.fromEntries(RESOLVABLE_ANCHORS
+ .map(([, refsKey]) => [refsKey, asSet(refs[refsKey])])
+ .filter(([, known]) => known));
+ const stageLines = [];
+ for (const stage of Array.isArray(evolution.stages) ? evolution.stages : []) {
+ if (!stage || typeof stage !== 'object') continue;
+ const parts = [];
+ for (const field of EVOLUTION_STAGE_TEXT_FIELDS) {
+ if (stage[field]) parts.push(`${STAGE_FIELD_LABELS[field]}: ${stage[field]}`);
+ }
+ const status = evolutionEvidenceStatus(stage.evidence, resolved);
+ if (status !== 'unanchored') parts.push(`evidence: ${describeEvidence(stage.evidence)} [${status}]`);
+ stageLines.push(` ${EVOLUTION_STAGE_LABELS[stage.stageId] || stage.stageId}: ${parts.join('; ') || '(not yet authored)'}`);
+ }
+ // A lens with a declared outcome but no stages is still worth rendering —
+ // the declaration is the part a review must not mistake for a gap. A lens
+ // with neither is nothing at all (and the sanitizer would have dropped it).
+ if (!stageLines.length && outcome === 'undeclared' && !note) return null;
+ return [`declared outcome: ${outcome}${note}`, ...stageLines].join('\n');
+}
diff --git a/server/lib/characterEvolution.test.js b/server/lib/characterEvolution.test.js
new file mode 100644
index 0000000000..53aa4dab66
--- /dev/null
+++ b/server/lib/characterEvolution.test.js
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import {
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_STAGES,
+ evolutionEvidenceStatus,
+ isDeclaredEvolution,
+ renderCharacterEvolutionForPrompt,
+ sanitizeCharacterEvolution,
+ sanitizeCharacterEvolutionList,
+} from './characterEvolution.js';
+
+const stage = (stageId, extra = {}) => ({ stageId, testedBelief: `belief for ${stageId}`, ...extra });
+
+describe('sanitizeCharacterEvolution', () => {
+ it('drops a lens with nothing authored, so an untouched record keeps no husk', () => {
+ expect(sanitizeCharacterEvolution(null)).toBeNull();
+ expect(sanitizeCharacterEvolution({})).toBeNull();
+ // Every leaf present but blank — the whole lens collapses rather than
+ // persisting five empty stages.
+ expect(sanitizeCharacterEvolution({
+ outcome: '',
+ outcomeNote: ' ',
+ stages: EVOLUTION_STAGES.map((stageId) => ({
+ stageId, testedBelief: '', externalPressure: '', characterChoice: '', causalConsequence: '',
+ })),
+ })).toBeNull();
+ });
+
+ it('keeps a SPARSE lens and stores stages in canonical sequence order', () => {
+ // Authored out of order, stages 1 and 3 only — the documented sparse case.
+ const evolution = sanitizeCharacterEvolution({
+ outcome: 'partial-open',
+ stages: [stage('commitment-to-change'), stage('control-strategy-failing')],
+ });
+ expect(evolution.stages.map((s) => s.stageId))
+ .toEqual(['control-strategy-failing', 'commitment-to-change']);
+ // Idempotent: re-sanitizing the stored shape must not reorder or lose it,
+ // which is what makes a save → load → sync → save round trip byte-stable.
+ expect(sanitizeCharacterEvolution(evolution)).toEqual(evolution);
+ });
+
+ it('rejects an unknown stageId and an unknown outcome rather than coercing them', () => {
+ const evolution = sanitizeCharacterEvolution({
+ outcome: 'mostly-changed',
+ outcomeNote: 'author is still deciding',
+ stages: [stage('act-two-midpoint'), stage('cost-tested')],
+ });
+ // A fabricated declaration would let a downstream review read this arc as a
+ // deliberate flat/tragic ending the author never declared.
+ expect(evolution.outcome).toBeNull();
+ expect(isDeclaredEvolution(evolution)).toBe(false);
+ expect(evolution.stages.map((s) => s.stageId)).toEqual(['cost-tested']);
+ });
+
+ it('treats a present-but-empty stage field as a real clear, not an absent one', () => {
+ const evolution = sanitizeCharacterEvolution({
+ outcome: 'full-change',
+ stages: [{ stageId: 'final-proof', testedBelief: '', characterChoice: 'walks away' }],
+ });
+ expect(evolution.stages[0]).toMatchObject({ testedBelief: '', characterChoice: 'walks away' });
+ });
+
+ it('declares a flat arc as first-class rather than an unfinished one', () => {
+ const flat = sanitizeCharacterEvolution({ outcome: 'flat-testing', outcomeNote: 'she holds' });
+ expect(isDeclaredEvolution(flat)).toBe(true);
+ expect(flat.stages).toEqual([]);
+ for (const outcome of EVOLUTION_OUTCOMES) {
+ expect(isDeclaredEvolution(sanitizeCharacterEvolution({ outcome }))).toBe(true);
+ }
+ });
+});
+
+describe('evidence anchors', () => {
+ const withAnchor = (evidence) => sanitizeCharacterEvolution({
+ outcome: 'full-change',
+ stages: [stage('final-proof', { evidence })],
+ }).stages[0].evidence;
+
+ it('preserves an authored pointer to a deleted record and reports it stale', () => {
+ const evidence = withAnchor({ transitionId: 'trn-deleted', episodeId: 'ep-gone' });
+ // Preserved as authored intent, following the sanitizeStoryOutline
+ // precedent that keeps an unknown targetKey so it can be REPORTED.
+ expect(evidence).toMatchObject({ transitionId: 'trn-deleted', episodeId: 'ep-gone' });
+ expect(evolutionEvidenceStatus(evidence, {
+ transitionIds: ['trn-alive'], episodeIds: ['ep-alive'],
+ })).toBe('stale');
+ });
+
+ it('reports anchored only when every authored pointer resolves', () => {
+ const evidence = withAnchor({ episodeId: 'ep-1', sceneKey: 'opening' });
+ expect(evolutionEvidenceStatus(evidence, { episodeIds: ['ep-1'], sceneKeys: ['opening'] }))
+ .toBe('anchored');
+ // One resolvable, one not — the whole anchor is stale, never verified.
+ expect(evolutionEvidenceStatus(evidence, { episodeIds: ['ep-1'], sceneKeys: ['closing'] }))
+ .toBe('stale');
+ });
+
+ it('never reports anchored for absent evidence or an unchecked pointer', () => {
+ expect(evolutionEvidenceStatus(null, { episodeIds: ['ep-1'] })).toBe('unanchored');
+ // A pointer with no reference set to check it against is unknown, and
+ // unknown must not read as verified.
+ expect(evolutionEvidenceStatus(withAnchor({ episodeId: 'ep-1' }), {})).toBe('unverified');
+ // A free-text scene anchor is authored but has nothing to resolve against.
+ expect(evolutionEvidenceStatus(withAnchor({ atSceneAnchor: 'the pier at dawn' }), {}))
+ .toBe('unverified');
+ });
+
+ it('drops a malformed pointer but keeps a well-shaped one', () => {
+ // 'episode-4' is not an `ep-` id — a junk value must not masquerade as
+ // evidence, which is different from a well-shaped pointer to a deleted one.
+ expect(withAnchor({ episodeId: 'episode-4', atIssue: 3 }))
+ .toMatchObject({ episodeId: '', atIssue: 3 });
+ expect(withAnchor({ transitionId: 'not-a-transition' })).toBeNull();
+ });
+});
+
+describe('sanitizeCharacterEvolutionList', () => {
+ it('dedupes by character identity and drops identity-less or empty entries', () => {
+ const list = sanitizeCharacterEvolutionList([
+ { characterId: 'chr-1', characterName: 'Ada', evolution: { outcome: 'full-change' } },
+ { characterId: 'chr-1', characterName: 'Ada Reyes', evolution: { outcome: 'tragic-refusal' } },
+ { characterName: 'Bo', evolution: { outcome: 'flat-testing' } },
+ { characterName: 'bo', evolution: { outcome: 'partial-open' } },
+ { characterName: 'Cy', evolution: {} },
+ { evolution: { outcome: 'full-change' } },
+ ]);
+ expect(list.map((e) => [e.characterName, e.evolution.outcome])).toEqual([
+ ['Ada Reyes', 'tragic-refusal'],
+ ['bo', 'partial-open'],
+ ]);
+ });
+});
+
+describe('renderCharacterEvolutionForPrompt', () => {
+ it('names the declared outcome and never presents a stale anchor as proof', () => {
+ const evolution = sanitizeCharacterEvolution({
+ outcome: 'tragic-refusal',
+ outcomeNote: 'he keeps the ledger',
+ stages: [stage('final-proof', { characterChoice: 'burns the letter', evidence: { episodeId: 'ep-gone' } })],
+ });
+ const block = renderCharacterEvolutionForPrompt(evolution, { episodeIds: ['ep-live'] });
+ expect(block).toContain('declared outcome: tragic-refusal — he keeps the ledger');
+ expect(block).toContain('[stale]');
+ expect(block).not.toContain('[anchored]');
+ });
+
+ it('returns null when there is nothing to render', () => {
+ expect(renderCharacterEvolutionForPrompt(null)).toBeNull();
+ expect(renderCharacterEvolutionForPrompt({ outcome: null, outcomeNote: '', stages: [] })).toBeNull();
+ });
+});
+
+// The client editors read the stage/outcome vocabularies from this leaf. A
+// hand-copied list there would drift the moment a stage id changed here, and an
+// equality assertion on the client side cannot catch it — it would be comparing
+// re-exported bindings to themselves. So assert the property that actually
+// matters: the mirror IMPORTS, it does not restate.
+describe('client mirror re-exports rather than copies', () => {
+ it('declares no vocabulary of its own', () => {
+ const mirror = readFileSync(
+ join(import.meta.dirname, '../../client/src/lib/characterEvolution.js'),
+ 'utf8',
+ );
+ expect(mirror).toContain("from '../../../server/lib/characterEvolution.js'");
+ for (const name of ['EVOLUTION_STAGES', 'EVOLUTION_OUTCOMES', 'EVOLUTION_STAGE_LABELS', 'CHARACTER_EVOLUTION_LIMITS']) {
+ expect(mirror, `${name} must be re-exported, not redeclared`)
+ .not.toMatch(new RegExp(`(const|let|var)\\s+${name}\\s*=`));
+ }
+ });
+});
diff --git a/server/lib/characterEvolutionValidation.js b/server/lib/characterEvolutionValidation.js
new file mode 100644
index 0000000000..f40b02ce5f
--- /dev/null
+++ b/server/lib/characterEvolutionValidation.js
@@ -0,0 +1,77 @@
+/**
+ * Zod schemas for the OPTIONAL five-stage character evolution lens (#6440).
+ *
+ * Its own module rather than a fragment in `sharedSchemas.js` because that file
+ * is pulled in by `validation.js`, which nearly every server suite reaches —
+ * 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.
+ */
+
+import { z } from 'zod';
+import {
+ CHARACTER_EVOLUTION_LIMITS,
+ EVOLUTION_OUTCOMES,
+ EVOLUTION_STAGES,
+ EVOLUTION_STAGE_TEXT_FIELDS,
+} from './characterEvolution.js';
+
+/**
+ * The OPTIONAL five-stage character evolution lens (#6440), as a route input.
+ *
+ * Shared because two unrelated hosts embed the same lens —
+ * `series.characterArcs[].evolution` (`routes/pipeline/series.js`) and
+ * `loom.seriesPlan.characterEvolutions[]` (`fableLoomValidation.js`) — and a
+ * hand-mirrored second copy would drift the moment a cap or a stage id moved.
+ *
+ * Every field is optional so a partial save and a deliberate clear both
+ * round-trip; `sanitizeCharacterEvolution` stays the authority (it drops empty
+ * stages, rejects an unknown `stageId` / `outcome`, and collapses an entirely
+ * blank lens to null). `outcome` is `.nullable()` rather than required
+ * because both hosts carry the lens inside a WHOLESALE-replaced field: making
+ * it mandatory would 400 an unrelated edit to a neighbouring arc whenever a
+ * lens had not been declared yet. The declaration is enforced semantically by
+ * `isDeclaredEvolution`, which is what keeps an undeclared lens from reading
+ * as a declared flat arc downstream.
+ */
+export const characterEvolutionEvidenceSchema = z.object({
+ atIssue: z.number().int().min(0).max(CHARACTER_EVOLUTION_LIMITS.atIssue).nullable().optional(),
+ atSceneAnchor: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.atSceneAnchor).optional(),
+ 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(),
+});
+
+export const characterEvolutionStageSchema = z.object({
+ stageId: z.enum(EVOLUTION_STAGES),
+ // Derived from the shared field list + cap table rather than re-typed, so a
+ // fifth stage field is one edit, not three, and a cap can never drift from
+ // what the sanitizer enforces.
+ ...Object.fromEntries(EVOLUTION_STAGE_TEXT_FIELDS
+ .map((field) => [field, z.string().trim().max(CHARACTER_EVOLUTION_LIMITS[field]).optional()])),
+ evidence: characterEvolutionEvidenceSchema.nullable().optional(),
+});
+
+export const characterEvolutionSchema = z.object({
+ outcome: z.enum(EVOLUTION_OUTCOMES).nullable().optional(),
+ outcomeNote: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.outcomeNote).optional(),
+ // Sparse by design: a lens with only stages 1 and 3 authored is valid, so the
+ // array is capped at the stage count rather than required to be full.
+ stages: z.array(characterEvolutionStageSchema)
+ .max(CHARACTER_EVOLUTION_LIMITS.STAGES_PER_LENS_MAX).optional(),
+});
+
+/**
+ * A per-character lens LIST, as `loom.seriesPlan.characterEvolutions[]` stores
+ * it. Kept beside the lens itself so the entry shape has exactly one
+ * definition; `sanitizeCharacterEvolutionList` stays the authority (drops
+ * identity-less or empty entries and dedupes by character).
+ */
+export const characterEvolutionListSchema = z.array(z.object({
+ characterId: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.evidenceRef).optional(),
+ characterName: z.string().trim().max(CHARACTER_EVOLUTION_LIMITS.characterName).optional(),
+ evolution: characterEvolutionSchema.nullable().optional(),
+})).max(CHARACTER_EVOLUTION_LIMITS.LENSES_PER_PLAN_MAX);
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index cd7270d970..80f27a2879 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -8,6 +8,7 @@
import { z } from 'zod';
import { isShotSpeakerCue } from './fableLoomShots.js';
import { LOOM_LIMITS } from './fableLoomLimits.js';
+import { characterEvolutionListSchema } from './characterEvolutionValidation.js';
import { LOOM_FORMATS } from './fableLoomFormats.js';
import {
FABLELOOM_AUDIO_TARGETS,
@@ -113,6 +114,12 @@ const seriesPlan = z.object({
title: z.string().max(LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),
transcript: z.string().max(LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
}).nullable().optional(),
+ // The OPTIONAL five-stage character evolution lens per character (#6440).
+ // Optional here so every pre-#6440 client keeps saving a plan unchanged;
+ // omitting it on a PATCH clears the lenses, because the plan rides a
+ // wholesale-`seriesPlan` PATCH (the sync path is where an absent key
+ // preserves — see preserveLegacyCharacterEvolutions).
+ characterEvolutions: characterEvolutionListSchema.optional(),
});
const outlineTransitionSchema = z.object({
diff --git a/server/lib/index.js b/server/lib/index.js
index 16ad27195d..2d435c57ce 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -27,6 +27,7 @@ export * as agentContextValidation from './agentContextValidation.js';
export * as appleHealthValidation from './appleHealthValidation.js';
export * as brainValidation from './brainValidation.js';
export * as catalogValidation from './catalogValidation.js';
+export * as characterEvolutionValidation from './characterEvolutionValidation.js';
export * as cosValidation from './cosValidation.js';
export * from './cosToolContracts.js';
export * as creativeCommissionValidation from './creativeCommissionValidation.js';
@@ -113,6 +114,8 @@ export * from './streamLines.js';
export * from './taskDataInputCatalog.js';
// The canon field caps storyBible.js sanitizes against, as a pure leaf.
export * from './bibleLimits.js';
+// The optional five-stage character evolution lens, as a pure leaf.
+export * from './characterEvolution.js';
// The narrative-character framework field list, as a pure leaf — storyBible.js
// re-exports CHARACTER_ARC_TYPES from here, so keep this flat export ahead of
// the namespaced storyBible below.
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index bf41872f64..4e7f1760bb 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -182,7 +182,17 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// OLDER peer must be rejected outright). Bump makes the older peer reject the
// ahead-version series transfer instead. Per-category gate → only series sync
// pauses with old peers.
- pipelineSeries: 12,
+ // v13 = `series.characterArcs[].evolution` added (#6440) — the optional
+ // five-stage character evolution lens (belief under test → pressure → choice
+ // → consequence, with a declared outcome). Same additive field INSIDE an
+ // already-federated sub-object as voiceExemplars (v11) inside styleGuide: a
+ // ≤v12 peer that re-sanitizes a series through its evolution-unaware
+ // `sanitizeCharacterArc` would silently strip the lens and last-writer-wins
+ // the loss back onto the newer peer (`preserveAbsentAdditiveFields` restores
+ // a wholly-absent `characterArcs`, not a present-but-sub-field-stripped
+ // one). Bump makes the older peer reject the ahead-version series transfer
+ // instead. Per-category gate → only series sync pauses with old peers.
+ pipelineSeries: 13,
// NOT bumped for the manuscript-review sibling doc now bundled on series
// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).
// Unlike `readerMap` (v2), the review is NOT a field inside the series
@@ -386,7 +396,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// effort preferences. A v5 peer would preserve the format but strip these
// additive preferences during an unrelated whole-record update.
// v7 = shot duration and dramatic-scene grouping survive whole-record sync.
- fableLoom: 7,
+ // v8 = `seriesPlan.characterEvolutions[]` — the optional five-stage character
+ // evolution lens per character (#6440). `sanitizeSeriesPlan` omits the key
+ // entirely when no lens is authored, so a ≤v7 peer that re-sanitizes a loom
+ // through its evolution-unaware sanitizer drops every authored lens and
+ // last-writer-wins the loss back onto the newer peer. Bump makes the older
+ // peer reject the ahead-version loom transfer; the receiver additionally
+ // restores local lenses from a <v8 sender that omits the key
+ // (`preserveLegacyCharacterEvolutions`), the same belt-and-braces the
+ // delivery plan got at v4.
+ fableLoom: 8,
// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)
// federated via the per-record peer-sync push pipeline (record kind
// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 432139e783..e1d1b9d7f9 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -30,13 +30,13 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
it('declares pipeline collection layout versions', () => {
// pipelineIssues v3 adds the independently persisted climax arc role.
expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(3);
- // pipelineSeries bumped to 12 when series.exportSettings was added (#2181)
- // (v2 = readerMap, v3 = tickingClock, v4 = styleGuide, v5 = coverImage,
- // v6 = characterArcs, v7 = factCritical + factReference,
+ // pipelineSeries bumped to 13 when characterArcs[].evolution was added
+ // (#6440) (v2 = readerMap, v3 = tickingClock, v4 = styleGuide,
+ // v5 = coverImage, v6 = characterArcs, v7 = factCritical + factReference,
// v8 = editorialCheckConfig, v9 = severityWeights + blockingSeverities,
// v10 = arc.foreshadowing, v11 = styleGuide.voiceExemplars +
- // voiceAntiExemplars).
- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(12);
+ // voiceAntiExemplars, v12 = exportSettings).
+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(13);
});
it('declares mediaCollections layout version', () => {
@@ -44,10 +44,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
});
it('version-gates the persisted FableLoom shot and reference shape', () => {
- // v7 adds timed shots and draft character image anchors.
+ // v7 adds timed shots and draft character image anchors; v8 adds the
+ // optional per-character five-stage evolution lens on the series plan.
// Older peers stay behind the full render contract until they advertise
// support for the additive fields.
- expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(7);
+ expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(8);
});
it('version-gates the additive Creative Commission taste brief shape', () => {
@@ -61,7 +62,7 @@ describe('buildPortosMeta', () => {
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
expect(meta.schemaVersions.universes).toBe(11);
expect(meta.schemaVersions.pipelineIssues).toBe(3);
- expect(meta.schemaVersions.pipelineSeries).toBe(12);
+ expect(meta.schemaVersions.pipelineSeries).toBe(13);
});
it('overrides merge into schemaVersions', async () => {
diff --git a/server/lib/seriesCharacterArc.js b/server/lib/seriesCharacterArc.js
index 87fc0054c1..2737f362b5 100644
--- a/server/lib/seriesCharacterArc.js
+++ b/server/lib/seriesCharacterArc.js
@@ -22,6 +22,7 @@
* startState, // who they are at the opening
* endState, // who they are at the close
* transitions: [{ id, atIssue, atSceneAnchor, label, kind, note }],
+ * evolution, // the optional five-stage lens, absent when unset (#6440)
* status, // 'draft' | 'verified'
* }
*
@@ -32,7 +33,15 @@
*/
import { randomUUID } from 'crypto';
-import { isStr, trimTo, trimToClause } from './storyBible.js';
+import { BIBLE_LIMITS } from './bibleLimits.js';
+import {
+ characterIdentityKey,
+ isCanonCharacterId,
+ isStoryBeatId,
+ optIssueNumber,
+ sanitizeCharacterEvolution,
+} from './characterEvolution.js';
+import { trimTo, trimToClause } from './textUtils.js';
export const CHARACTER_ARC_LIMITS = Object.freeze({
CHARACTER_NAME_MAX: 200,
@@ -44,7 +53,10 @@ export const CHARACTER_ARC_LIMITS = Object.freeze({
TRANSITION_NOTE_MAX: 1000,
TRANSITION_ANCHOR_MAX: 300,
TRANSITIONS_PER_ARC_MAX: 40,
- ISSUE_MAX: 9999,
+ // Shared with the evolution lens's own issue anchor, so the two anchor
+ // vocabularies cannot drift apart (`characterEvolution.js` reads the same
+ // constant).
+ ISSUE_MAX: BIBLE_LIMITS.STORY_ISSUE_NUMBER_MAX,
ARCS_PER_SERIES_MAX: 60,
});
@@ -63,17 +75,14 @@ export const TRANSITION_KINDS = Object.freeze([
'sacrifice',
]);
-const CHARACTER_ID_RE = /^chr-[a-zA-Z0-9-]+$/;
const TRANSITION_ID_PREFIX = 'trn-';
-const TRANSITION_ID_RE = /^trn-[a-zA-Z0-9-]+$/;
+// The canon id shapes, the issue clamp and the identity key are shared with the
+// evolution lens (`characterEvolution.js`, which this module already imports)
+// so the two per-character story lists cannot drift on what counts as a valid
+// pointer or as the same character.
const ensureTransitionId = (raw) =>
- (isStr(raw) && TRANSITION_ID_RE.test(raw) ? raw : `${TRANSITION_ID_PREFIX}${randomUUID()}`);
-
-// Optional non-negative integer (e.g. an issue number). Absent / non-finite →
-// null so the caller can distinguish "no issue pinned" from issue 0.
-const optInt = (raw, max) =>
- (Number.isFinite(raw) ? Math.max(0, Math.min(max, Math.floor(raw))) : null);
+ (isStoryBeatId(raw) ? raw : `${TRANSITION_ID_PREFIX}${randomUUID()}`);
/**
* Sanitize one transition beat. Returns `null` when it carries no identifying
@@ -100,7 +109,7 @@ export function sanitizeTransition(raw) {
id: ensureTransitionId(raw.id),
kind,
label,
- atIssue: optInt(raw.atIssue, CHARACTER_ARC_LIMITS.ISSUE_MAX),
+ atIssue: optIssueNumber(raw.atIssue, CHARACTER_ARC_LIMITS.ISSUE_MAX),
atSceneAnchor: trimTo(raw.atSceneAnchor, CHARACTER_ARC_LIMITS.TRANSITION_ANCHOR_MAX),
note,
};
@@ -127,7 +136,7 @@ function cleanTransitions(rawList) {
*/
export function sanitizeCharacterArc(raw) {
if (!raw || typeof raw !== 'object') return null;
- const characterId = isStr(raw.characterId) && CHARACTER_ID_RE.test(raw.characterId) ? raw.characterId : '';
+ const characterId = isCanonCharacterId(raw.characterId) ? raw.characterId : '';
const characterName = trimTo(raw.characterName, CHARACTER_ARC_LIMITS.CHARACTER_NAME_MAX);
// want/need/startState/endState are LLM-authored prose rendered back into the
// verify + resolve prompts — boundary-aware caps for the same reason as the
@@ -138,13 +147,23 @@ export function sanitizeCharacterArc(raw) {
const startState = trimToClause(raw.startState, CHARACTER_ARC_LIMITS.START_STATE_MAX);
const endState = trimToClause(raw.endState, CHARACTER_ARC_LIMITS.END_STATE_MAX);
const transitions = cleanTransitions(raw.transitions);
+ // The OPTIONAL five-stage evolution lens (#6440). The key is OMITTED (not
+ // stored as null) when nothing is authored, so a pre-#6440 arc round-trips
+ // byte-identical and nothing about the lens becomes a gate on a legacy
+ // story — the same shape rule `sanitizeSeriesPlan` uses for the delivery
+ // plan. Wire-gated (pipelineSeries schema v13).
+ const evolution = sanitizeCharacterEvolution(raw.evolution);
// Without a character pointer/name there's nothing to attach the arc to, and
- // without any authored field or transition there's nothing to render — either
- // way it's indistinguishable from "no arc".
+ // without any authored field, transition or lens there's nothing to render —
+ // either way it's indistinguishable from "no arc".
if (!characterId && !characterName) return null;
- if (!want && !need && !startState && !endState && transitions.length === 0) return null;
+ if (!want && !need && !startState && !endState && transitions.length === 0 && !evolution) return null;
const status = CHARACTER_ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';
- return { characterId, characterName, want, need, startState, endState, transitions, status };
+ return {
+ characterId, characterName, want, need, startState, endState, transitions,
+ ...(evolution ? { evolution } : {}),
+ status,
+ };
}
/**
@@ -161,9 +180,7 @@ export function sanitizeCharacterArcList(rawList) {
for (const raw of rawList) {
const arc = sanitizeCharacterArc(raw);
if (!arc) continue;
- // Identity key: the canon pointer wins; fall back to the case-folded name so
- // a name-only arc still de-dupes against itself.
- const key = arc.characterId || `name:${arc.characterName.trim().toLowerCase()}`;
+ const key = characterIdentityKey(arc.characterId, arc.characterName);
if (!byKey.has(key)) {
if (byKey.size >= CHARACTER_ARC_LIMITS.ARCS_PER_SERIES_MAX) continue;
order.push(key);
@@ -201,3 +218,15 @@ export function renderCharacterArcsForPrompt(arcs) {
}
return lines.length ? lines.join('\n') : null;
}
+
+/**
+ * Reference sets an evolution lens's evidence anchors resolve against on this
+ * host — the arc's own authored transition beats. Hand it to
+ * `evolutionEvidenceStatus` / `renderCharacterEvolutionForPrompt` so a stage
+ * pointing at a since-deleted `trn-` beat reports `stale` instead of passing
+ * as proof. Kept beside the arc because the arc owns the beats.
+ */
+export function characterArcEvidenceRefs(arc) {
+ const transitions = Array.isArray(arc?.transitions) ? arc.transitions : [];
+ return { transitionIds: new Set(transitions.map((t) => t?.id).filter(Boolean)) };
+}
diff --git a/server/lib/seriesCharacterArc.test.js b/server/lib/seriesCharacterArc.test.js
index 205a205c27..5f118e8cc6 100644
--- a/server/lib/seriesCharacterArc.test.js
+++ b/server/lib/seriesCharacterArc.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
+ characterArcEvidenceRefs,
sanitizeTransition,
sanitizeCharacterArc,
sanitizeCharacterArcList,
@@ -7,6 +8,7 @@ import {
CHARACTER_ARC_LIMITS,
TRANSITION_KINDS,
} from './seriesCharacterArc.js';
+import { evolutionEvidenceStatus } from './characterEvolution.js';
describe('sanitizeTransition', () => {
it('keeps a well-formed transition and mints an id', () => {
@@ -183,3 +185,39 @@ describe('renderCharacterArcsForPrompt', () => {
expect(block).toContain('realization (issue 3): sees the cost');
});
});
+
+describe('optional five-stage evolution lens (#6440)', () => {
+ it('leaves an arc that never opted in byte-identical', () => {
+ // The lens must add no key at all to a legacy arc — an `evolution: null`
+ // stamp would rewrite every stored characterArcs entry on its next save.
+ const arc = sanitizeCharacterArc({
+ characterId: 'chr-1', characterName: 'Mara', want: 'revenge', need: 'to forgive',
+ });
+ expect(Object.prototype.hasOwnProperty.call(arc, 'evolution')).toBe(false);
+ expect(JSON.stringify(sanitizeCharacterArc(arc))).toBe(JSON.stringify(arc));
+ });
+
+ it('keeps a lens-only arc and resolves its stages against the arc\'s own beats', () => {
+ const arc = sanitizeCharacterArc({
+ // No want/need/startState — a writer may plan the evolution first, and the
+ // lens alone is enough to keep the arc.
+ characterName: 'Mara',
+ transitions: [{ id: 'trn-live', kind: 'decision', label: 'walks out' }],
+ evolution: {
+ outcome: 'full-change',
+ stages: [
+ { stageId: 'final-proof', characterChoice: 'stays', evidence: { transitionId: 'trn-live' } },
+ { stageId: 'cost-tested', characterChoice: 'pays', evidence: { transitionId: 'trn-deleted' } },
+ ],
+ },
+ });
+ expect(JSON.stringify(sanitizeCharacterArc(arc))).toBe(JSON.stringify(arc));
+ // Only the beat this arc still owns counts as proof; the pointer to the
+ // deleted one survives as authored intent and reads stale.
+ const refs = characterArcEvidenceRefs(arc);
+ expect(Object.fromEntries(arc.evolution.stages
+ .map((st) => [st.stageId, evolutionEvidenceStatus(st.evidence, refs)])))
+ .toEqual({ 'cost-tested': 'stale', 'final-proof': 'anchored' });
+ expect(arc.evolution.stages[0].evidence.transitionId).toBe('trn-deleted');
+ });
+});
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 294c0e625b..5c0637024d 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -14,7 +14,7 @@ import { normalizeSlugline } from './scenePrompt.js';
import { PATHS, resolveImageRef } from './fileUtils.js';
import { isPlainObject } from './objects.js';
import { shortCanonPrimaryField } from './canonPrompt.js';
-import { trimTo } from './textUtils.js';
+import { trimTo, trimToClause } from './textUtils.js';
import { BIBLE_LIMITS } from './bibleLimits.js';
import {
CHARACTER_ARC_TYPES,
@@ -27,7 +27,12 @@ import {
// Re-export so callers (writers-room domain files) can import a single
// canonical normalizer when they need to match places by slugline.
export { normalizeSlugline };
-export { trimTo };
+// `trimTo` and the boundary-aware `trimToClause` both live in the
+// dependency-free `textUtils.js` so the pure story-model leaves the browser
+// bundle shares (`characterFramework.js`, `characterEvolution.js`) can cap
+// prose without importing this module's `crypto` / `fileUtils`. Re-exported
+// here because every existing sanitizer reaches for them through storyBible.
+export { trimTo, trimToClause };
// The canon field caps live in a pure leaf (`bibleLimits.js`) so the browser
// bundle and `catalogTypes.js` can read them without this module's `crypto` /
@@ -197,78 +202,10 @@ const DEFAULT_ID_PREFIX = Object.freeze({
});
// Shared string predicate retained here for the story-bible domain. `trimTo`
-// now lives in dependency-free textUtils and is re-exported above so existing
-// story-bible consumers keep the same public contract.
+// and `trimToClause` now live in dependency-free textUtils and are re-exported
+// above so existing story-bible consumers keep the same public contract.
export const isStr = (v) => typeof v === 'string';
-// Smallest share of the budget a sentence-boundary cut may keep. A cut that
-// lands above this wins over a mid-sentence clip; below it, gutting the record
-// costs more than the ragged edge does.
-//
-// This was 0.6, which rejected a valid sentence break at 53% of a field's budget
-// and fell through to a nearly-at-cap whole-word fragment. The next verification
-// round then flagged the sanitizer-authored incomplete sentence, and every
-// over-cap replacement reproduced it. A single-sentence field (logline, ending
-// hook) is the common case: its first terminator is often its ONLY one, so a
-// floor near the top of the budget rejects the clean cut it was meant to prefer.
-const SENTENCE_CUT_FLOOR = 0.3;
-
-// A sentence terminator that actually ENDS a sentence: `.`/`!`/`?` plus any
-// closing quote or bracket, and then either whitespace or the end of the window.
-// Requiring that lookahead is what keeps "Dr. Vey" and "3.5" from reading as
-// breaks; allowing `$` is what lets a terminator sitting flush against the
-// budget edge count, which `lastIndexOf('. ')` missed because it demanded a
-// trailing space that the slice had already cut off.
-const SENTENCE_END_RE = /[.!?]["'’”)\]]*(?=\s|$)/g;
-const COMMON_ABBREVIATION_RE = /\b(?:dr|etc|jr|mr|mrs|ms|prof|sr|st|vs)\.$/i;
-
-// A clause boundary — the weaker cut used when a short field holds no sentence
-// terminator at all. Short caps (a 200-char transition label) routinely hold one
-// long clause-chained sentence, where the whole-word fallback leaves a dangling
-// half-clause ("...escrows the proceeds with no repayment lien, no") that reads
-// as an authoring gap to the next verify round. Because it is weaker than a
-// sentence break, it has to keep more of the field to be worth taking.
-const CLAUSE_END_RE = /[,;:—–]/g;
-const CLAUSE_CUT_FLOOR = 0.6;
-
-// Boundary-aware cap for PROSE fields (loglines, synopses, ending hooks). A hard
-// `slice(0, max)` clips mid-word ("...tracing the brand and"), which downstream
-// verify passes flag as "truncated mid-sentence" — and because a resolver then
-// regenerates an over-cap value that gets re-clipped the same way, the
-// verify→resolve loop never converges. When the text fits, it's returned
-// untouched. When it must be clipped, back off to the last sentence terminator
-// (. ! ?) within the budget, provided that cut keeps at least
-// SENTENCE_CUT_FLOOR of it; failing that, to the last clause boundary (, ; : —)
-// keeping at least CLAUSE_CUT_FLOOR; and failing that (a single clause running
-// past the cap, or a break so early that honoring it would gut the field) to the
-// last whitespace boundary so the result still ends on a whole word. Never
-// returns more than `max` chars.
-export function trimToClause(v, max) {
- if (!isStr(v)) return '';
- const s = v.trim();
- if (s.length <= max) return s;
- const window = s.slice(0, max);
- // Prefer the last real sentence terminator in the window. `end` is the cut
- // point (exclusive) so trailing quotes/brackets ride along with the period.
- let end = -1;
- SENTENCE_END_RE.lastIndex = 0;
- for (let m = SENTENCE_END_RE.exec(window); m; m = SENTENCE_END_RE.exec(window)) {
- if (m[0][0] === '.' && COMMON_ABBREVIATION_RE.test(window.slice(0, m.index + 1))) continue;
- end = m.index + m[0].length;
- }
- if (end >= Math.floor(max * SENTENCE_CUT_FLOOR)) return window.slice(0, end).trim();
- // No usable sentence break — back off to the last clause boundary instead, so
- // the result ends on a complete clause rather than mid-thought. The mark itself
- // is dropped (cut is exclusive) so the value never ends on a hanging comma.
- let clause = -1;
- CLAUSE_END_RE.lastIndex = 0;
- for (let m = CLAUSE_END_RE.exec(window); m; m = CLAUSE_END_RE.exec(window)) clause = m.index;
- if (clause >= Math.floor(max * CLAUSE_CUT_FLOOR)) return window.slice(0, clause).trim();
- // Not even a usable clause break — clip on the last whole word instead of mid-word.
- const space = window.lastIndexOf(' ');
- return (space > 0 ? window.slice(0, space) : window).trim();
-}
-
// Walk a raw array through a per-item sanitizer, dropping rejected entries
// (falsy return from `sanitizer`) and capping the output at `cap`. Three
// near-identical loops elsewhere in this file (cleanStringArray, the wardrobe
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 3c83610fcb..068e37d897 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -34,7 +34,6 @@ const {
CANON_CONTROL_FIELDS,
SERVER_OWNED_CHARACTER_FIELDS,
trimTo,
- trimToClause,
filterCanonForIssue,
filterCanonListForIssue,
isCanonEntryGatedForIssue,
@@ -1600,89 +1599,6 @@ describe('BIBLE_LIMITS client mirror', () => {
expect(clientMirror.BIBLE_LIMITS).toEqual(BIBLE_LIMITS);
});
});
-
-describe('storyBible — trimToClause (boundary-aware prose cap)', () => {
- it('returns text untouched when it fits', () => {
- expect(trimToClause('A short logline.', 500)).toBe('A short logline.');
- expect(trimToClause(' trimmed ', 500)).toBe('trimmed');
- });
-
- it('is empty for non-strings (matches trimTo)', () => {
- expect(trimToClause(null, 50)).toBe('');
- expect(trimToClause(undefined, 50)).toBe('');
- expect(trimToClause(42, 50)).toBe('');
- });
-
- it('clips at a sentence boundary when it preserves a meaningful share of the budget', () => {
- const text = 'First full sentence about the arc here. And then a second clause runs on well past the budget.';
- const out = trimToClause(text, 50);
- expect(out).toBe('First full sentence about the arc here.');
- expect(out.length).toBeLessThanOrEqual(50);
- });
-
- it('prefers the only complete sentence at 53% over a near-cap fragment', () => {
- const complete = `${'word '.repeat(52)}done.`; // 265 chars
- const tail = ` ${'continuation '.repeat(30)}`;
- const out = trimToClause(complete + tail, 500);
- expect(out).toBe(complete);
- expect(out.endsWith('.')).toBe(true);
- });
-
- it('does not treat abbreviations or decimals as sentence endings', () => {
- const text = `Dr. Example measured 3.5 units before the actual stop. ${'tail '.repeat(20)}`;
- const out = trimToClause(text, 70);
- expect(out).toBe('Dr. Example measured 3.5 units before the actual stop.');
- });
-
- it('keeps closing quotes and brackets attached to the sentence', () => {
- const text = `The operator said, "Stop now." ${'tail '.repeat(20)}`;
- expect(trimToClause(text, 50)).toBe('The operator said, "Stop now."');
- });
-
- it('backs off to a clause boundary when the field holds no sentence break', () => {
- // The shape a saturated 200-char transition label takes: one clause-chained
- // sentence, no terminator anywhere in budget. Cutting on the last whole word
- // leaves "...with no repayment lien, no" — a dangling half-clause the next
- // verification round reports as an incomplete record.
- const label = 'Proves with the validated block that the takeover cannot reach quorum, then closes the short and escrows the proceeds with no repayment lien, no personal withdrawal key, and no veto';
- const out = trimToClause(label, 160);
- expect(out).toBe('Proves with the validated block that the takeover cannot reach quorum, then closes the short and escrows the proceeds with no repayment lien');
- expect(out.length).toBeLessThanOrEqual(160);
- expect(/[,;:—–]$/.test(out)).toBe(false);
- });
-
- it('prefers a usable sentence break over a later clause break', () => {
- const text = 'The vote carries after a long night of argument. The crews ratify, the boosters transfer, and the manifest is certified.';
- expect(trimToClause(text, 70)).toBe('The vote carries after a long night of argument.');
- });
-
- it('ignores a clause break so early that honoring it would gut the field', () => {
- // Comma at ~8% of the budget: keeping only "Yes" is worse than the ragged
- // whole-word edge, so the word fallback still wins.
- const text = `Yes, ${'word '.repeat(40)}`;
- const out = trimToClause(text, 60);
- expect(out.startsWith('Yes, word')).toBe(true);
- expect(out.length).toBeGreaterThan(50);
- });
-
- it('never clips mid-word — falls back to a whole-word boundary on a run-on', () => {
- // No sentence terminator within budget → must still end on a complete word,
- // not "...tracing the brand an".
- const runon = 'JUNO risks her anonymity to be recognized as author while Caroline Marsh starts tracing the brand and the buzz';
- const out = trimToClause(runon, 60);
- expect(out.length).toBeLessThanOrEqual(60);
- expect(out.endsWith(' ')).toBe(false);
- // The last token is a whole word from the source (no partial word).
- const lastWord = out.split(' ').pop();
- expect(runon.split(' ')).toContain(lastWord);
- });
-
- it('never returns more than max characters', () => {
- const long = 'word '.repeat(400); // 2000 chars, no sentence breaks
- expect(trimToClause(long, 100).length).toBeLessThanOrEqual(100);
- });
-});
-
describe('storyBible — reveal-gated canon (#2178)', () => {
describe('sanitizer field round-trip', () => {
it('defaults reveal fields to null/absent on every kind (backward compat)', () => {
diff --git a/server/lib/textUtils.js b/server/lib/textUtils.js
index f0803cf57d..677b2d7eb7 100644
--- a/server/lib/textUtils.js
+++ b/server/lib/textUtils.js
@@ -36,6 +36,82 @@ export const trimTo = (value, max) => (
typeof value === 'string' ? value.trim().slice(0, max) : ''
);
+// Smallest share of the budget a sentence-boundary cut may keep. A cut that
+// lands above this wins over a mid-sentence clip; below it, gutting the record
+// costs more than the ragged edge does.
+//
+// This was 0.6, which rejected a valid sentence break at 53% of a field's budget
+// and fell through to a nearly-at-cap whole-word fragment. The next verification
+// round then flagged the sanitizer-authored incomplete sentence, and every
+// over-cap replacement reproduced it. A single-sentence field (logline, ending
+// hook) is the common case: its first terminator is often its ONLY one, so a
+// floor near the top of the budget rejects the clean cut it was meant to prefer.
+const SENTENCE_CUT_FLOOR = 0.3;
+
+// A sentence terminator that actually ENDS a sentence: `.`/`!`/`?` plus any
+// closing quote or bracket, and then either whitespace or the end of the window.
+// Requiring that lookahead is what keeps "Dr. Vey" and "3.5" from reading as
+// breaks; allowing `$` is what lets a terminator sitting flush against the
+// budget edge count, which `lastIndexOf('. ')` missed because it demanded a
+// trailing space that the slice had already cut off.
+const SENTENCE_END_RE = /[.!?]["'’”)\]]*(?=\s|$)/g;
+const COMMON_ABBREVIATION_RE = /\b(?:dr|etc|jr|mr|mrs|ms|prof|sr|st|vs)\.$/i;
+
+// A clause boundary — the weaker cut used when a short field holds no sentence
+// terminator at all. Short caps (a 200-char transition label) routinely hold one
+// long clause-chained sentence, where the whole-word fallback leaves a dangling
+// half-clause ("...escrows the proceeds with no repayment lien, no") that reads
+// as an authoring gap to the next verify round. Because it is weaker than a
+// sentence break, it has to keep more of the field to be worth taking.
+const CLAUSE_END_RE = /[,;:—–]/g;
+const CLAUSE_CUT_FLOOR = 0.6;
+
+/**
+ * Boundary-aware cap for PROSE fields (loglines, synopses, ending hooks). A hard
+ * `slice(0, max)` clips mid-word ("...tracing the brand and"), which downstream
+ * verify passes flag as "truncated mid-sentence" — and because a resolver then
+ * regenerates an over-cap value that gets re-clipped the same way, the
+ * verify→resolve loop never converges. When the text fits, it's returned
+ * untouched. When it must be clipped, back off to the last sentence terminator
+ * (. ! ?) within the budget, provided that cut keeps at least
+ * SENTENCE_CUT_FLOOR of it; failing that, to the last clause boundary (, ; : —)
+ * keeping at least CLAUSE_CUT_FLOOR; and failing that (a single clause running
+ * past the cap, or a break so early that honoring it would gut the field) to the
+ * last whitespace boundary so the result still ends on a whole word. Never
+ * returns more than `max` chars.
+ *
+ * Lives here rather than in `storyBible.js` (which re-exports it, so every
+ * existing caller is unchanged) because `storyBible.js` pulls `crypto` +
+ * `fileUtils`: the pure story-model leaves the browser bundle shares —
+ * `characterFramework.js`, `characterEvolution.js` — need the boundary-aware
+ * cap without dragging Node built-ins into the client build.
+ */
+export function trimToClause(v, max) {
+ if (typeof v !== 'string') return '';
+ const s = v.trim();
+ if (s.length <= max) return s;
+ const window = s.slice(0, max);
+ // Prefer the last real sentence terminator in the window. `end` is the cut
+ // point (exclusive) so trailing quotes/brackets ride along with the period.
+ let end = -1;
+ SENTENCE_END_RE.lastIndex = 0;
+ for (let m = SENTENCE_END_RE.exec(window); m; m = SENTENCE_END_RE.exec(window)) {
+ if (m[0][0] === '.' && COMMON_ABBREVIATION_RE.test(window.slice(0, m.index + 1))) continue;
+ end = m.index + m[0].length;
+ }
+ if (end >= Math.floor(max * SENTENCE_CUT_FLOOR)) return window.slice(0, end).trim();
+ // No usable sentence break — back off to the last clause boundary instead, so
+ // the result ends on a complete clause rather than mid-thought. The mark itself
+ // is dropped (cut is exclusive) so the value never ends on a hanging comma.
+ let clause = -1;
+ CLAUSE_END_RE.lastIndex = 0;
+ for (let m = CLAUSE_END_RE.exec(window); m; m = CLAUSE_END_RE.exec(window)) clause = m.index;
+ if (clause >= Math.floor(max * CLAUSE_CUT_FLOOR)) return window.slice(0, clause).trim();
+ // Not even a usable clause break — clip on the last whole word instead of mid-word.
+ const space = window.lastIndexOf(' ');
+ return (space > 0 ? window.slice(0, space) : window).trim();
+}
+
/**
* Bound a string to a hard character cap, cutting on a natural boundary.
*
diff --git a/server/lib/textUtils.test.js b/server/lib/textUtils.test.js
index b8a21e9211..1270787654 100644
--- a/server/lib/textUtils.test.js
+++ b/server/lib/textUtils.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { clampToCharLimit, countWords, escapeRegExp, trimTo } from './textUtils.js';
+import { clampToCharLimit, countWords, escapeRegExp, trimTo, trimToClause } from './textUtils.js';
import { collectClientSources, collectServerSources, readClientSource, readServerSource } from './testHelper.js';
describe('countWords', () => {
@@ -161,3 +161,85 @@ describe('no private escapeRegExp', () => {
expect(escapeIdiomCount('const x = 1;')).toBe(0);
});
});
+
+describe('trimToClause (boundary-aware prose cap)', () => {
+ it('returns text untouched when it fits', () => {
+ expect(trimToClause('A short logline.', 500)).toBe('A short logline.');
+ expect(trimToClause(' trimmed ', 500)).toBe('trimmed');
+ });
+
+ it('is empty for non-strings (matches trimTo)', () => {
+ expect(trimToClause(null, 50)).toBe('');
+ expect(trimToClause(undefined, 50)).toBe('');
+ expect(trimToClause(42, 50)).toBe('');
+ });
+
+ it('clips at a sentence boundary when it preserves a meaningful share of the budget', () => {
+ const text = 'First full sentence about the arc here. And then a second clause runs on well past the budget.';
+ const out = trimToClause(text, 50);
+ expect(out).toBe('First full sentence about the arc here.');
+ expect(out.length).toBeLessThanOrEqual(50);
+ });
+
+ it('prefers the only complete sentence at 53% over a near-cap fragment', () => {
+ const complete = `${'word '.repeat(52)}done.`; // 265 chars
+ const tail = ` ${'continuation '.repeat(30)}`;
+ const out = trimToClause(complete + tail, 500);
+ expect(out).toBe(complete);
+ expect(out.endsWith('.')).toBe(true);
+ });
+
+ it('does not treat abbreviations or decimals as sentence endings', () => {
+ const text = `Dr. Example measured 3.5 units before the actual stop. ${'tail '.repeat(20)}`;
+ const out = trimToClause(text, 70);
+ expect(out).toBe('Dr. Example measured 3.5 units before the actual stop.');
+ });
+
+ it('keeps closing quotes and brackets attached to the sentence', () => {
+ const text = `The operator said, "Stop now." ${'tail '.repeat(20)}`;
+ expect(trimToClause(text, 50)).toBe('The operator said, "Stop now."');
+ });
+
+ it('backs off to a clause boundary when the field holds no sentence break', () => {
+ // The shape a saturated 200-char transition label takes: one clause-chained
+ // sentence, no terminator anywhere in budget. Cutting on the last whole word
+ // leaves "...with no repayment lien, no" — a dangling half-clause the next
+ // verification round reports as an incomplete record.
+ const label = 'Proves with the validated block that the takeover cannot reach quorum, then closes the short and escrows the proceeds with no repayment lien, no personal withdrawal key, and no veto';
+ const out = trimToClause(label, 160);
+ expect(out).toBe('Proves with the validated block that the takeover cannot reach quorum, then closes the short and escrows the proceeds with no repayment lien');
+ expect(out.length).toBeLessThanOrEqual(160);
+ expect(/[,;:—–]$/.test(out)).toBe(false);
+ });
+
+ it('prefers a usable sentence break over a later clause break', () => {
+ const text = 'The vote carries after a long night of argument. The crews ratify, the boosters transfer, and the manifest is certified.';
+ expect(trimToClause(text, 70)).toBe('The vote carries after a long night of argument.');
+ });
+
+ it('ignores a clause break so early that honoring it would gut the field', () => {
+ // Comma at ~8% of the budget: keeping only "Yes" is worse than the ragged
+ // whole-word edge, so the word fallback still wins.
+ const text = `Yes, ${'word '.repeat(40)}`;
+ const out = trimToClause(text, 60);
+ expect(out.startsWith('Yes, word')).toBe(true);
+ expect(out.length).toBeGreaterThan(50);
+ });
+
+ it('never clips mid-word — falls back to a whole-word boundary on a run-on', () => {
+ // No sentence terminator within budget → must still end on a complete word,
+ // not "...tracing the brand an".
+ const runon = 'JUNO risks her anonymity to be recognized as author while Caroline Marsh starts tracing the brand and the buzz';
+ const out = trimToClause(runon, 60);
+ expect(out.length).toBeLessThanOrEqual(60);
+ expect(out.endsWith(' ')).toBe(false);
+ // The last token is a whole word from the source (no partial word).
+ const lastWord = out.split(' ').pop();
+ expect(runon.split(' ')).toContain(lastWord);
+ });
+
+ it('never returns more than max characters', () => {
+ const long = 'word '.repeat(400); // 2000 chars, no sentence breaks
+ expect(trimToClause(long, 100).length).toBeLessThanOrEqual(100);
+ });
+});
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index fdb8abec58..4021149a0e 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -11,6 +11,7 @@ import {
validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray,
} from '../../lib/validation.js';
import { recordRenderPinFields } from '../../lib/sharedSchemas.js';
+import { characterEvolutionSchema } from '../../lib/characterEvolutionValidation.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import { TRIM_SIZES, INTERIOR_FONTS } from '../../lib/proseExportSettings.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
@@ -103,6 +104,12 @@ const characterArcSchema = z.object({
endState: z.string().trim().max(CHARACTER_ARC_LIMITS.END_STATE_MAX).optional(),
transitions: z.array(characterArcTransitionSchema)
.max(CHARACTER_ARC_LIMITS.TRANSITIONS_PER_ARC_MAX).optional(),
+ // The OPTIONAL five-stage evolution lens (#6440). `characterArcs` is a
+ // wholesale replace, so a client sends each arc whole — an omitted or null
+ // `evolution` is a real clear here, exactly like an omitted `want`. The
+ // absent-key-preserves rule applies one level up, on the sync-merge path
+ // (`ADDITIVE_SERIES_FIELDS` already lists `characterArcs`).
+ evolution: characterEvolutionSchema.nullable().optional(),
status: z.enum(CHARACTER_ARC_STATUSES).optional(),
});
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index ee000aed70..a46197e587 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -16,6 +16,7 @@ import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeLlmRoutePin } from '../../lib/llmRoutePin.js';
+import { sanitizeCharacterEvolutionList } from '../../lib/characterEvolution.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import {
@@ -236,6 +237,13 @@ function sanitizeSeriesPlan(raw, episodes) {
transcript: trimTo(source.nextSeasonTeaser.transcript, LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
}
: null;
+ // The OPTIONAL five-stage character evolution lens (#6440), one per
+ // character, keyed by the canon `chr-` id. Evidence anchors (episodeId /
+ // sceneKey) are PRESERVED as authored even when they no longer resolve —
+ // `fableLoomEvolutionEvidenceRefs` lets a reader derive `stale` on read,
+ // the same way `sanitizeStoryOutline` keeps an unknown `targetKey` so
+ // DANGLING_TRANSITION can report it. Absent on every pre-#6440 plan.
+ const characterEvolutions = sanitizeCharacterEvolutionList(source.characterEvolutions);
return {
storyArc: trimTo(source.storyArc, LOOM_LIMITS.STORY_ARC_MAX),
plotPoints: (Array.isArray(source.plotPoints) ? source.plotPoints : [])
@@ -264,9 +272,31 @@ function sanitizeSeriesPlan(raw, episodes) {
interEpisodeVoicemails,
nextSeasonTeaser: teaser,
} : {}),
+ // Omitted entirely when no lens is authored, so a pre-#6440 plan is
+ // byte-identical after a round trip (same shape rule the delivery plan
+ // above follows) and `preserveLegacyCharacterEvolutions` can tell "this
+ // sender cannot represent the field" from "the author cleared it".
+ ...(characterEvolutions.length ? { characterEvolutions } : {}),
};
}
+/**
+ * Reference sets a FableLoom evolution lens's evidence anchors resolve
+ * against — every episode id, and every outline scene key across the loom.
+ * Hand it to `evolutionEvidenceStatus` so a stage pointing at a deleted
+ * episode or a renamed scene reports `stale` rather than passing as proof.
+ */
+export function fableLoomEvolutionEvidenceRefs(loom) {
+ const episodes = Array.isArray(loom?.episodes) ? loom.episodes : [];
+ const sceneKeys = new Set();
+ for (const episode of episodes) {
+ for (const scene of episode?.storyOutline?.scenes || []) {
+ if (scene?.key) sceneKeys.add(scene.key);
+ }
+ }
+ return { episodeIds: new Set(episodes.map((episode) => episode.id)), sceneKeys };
+}
+
export function sanitizeLoom(raw) {
if (!raw || typeof raw !== 'object') return null;
if (!isStr(raw.id) || !raw.id) return null;
@@ -684,41 +714,75 @@ const preserveLegacyDeliveryPlan = (remotePlan, localPlan, senderVersion) => (
: {}
);
+// The per-character evolution lens (#6440) arrived with v8. `sanitizeSeriesPlan`
+// omits the key entirely when a plan has none, so a <=v7 sender that omits it
+// means "cannot represent" and the local lenses must survive; a v8+ sender that
+// omits it describes a plan whose lenses were genuinely cleared. Same shape as
+// preserveLegacyDeliveryPlan above — without it, one sync from a not-yet-
+// upgraded peer silently drops every authored lens and LWWs the loss back.
+const preserveLegacyCharacterEvolutions = (remotePlan, localPlan, senderVersion) => (
+ senderVersion < 8
+ && localPlan
+ && Object.prototype.hasOwnProperty.call(localPlan, 'characterEvolutions')
+ && !Object.prototype.hasOwnProperty.call(remotePlan || {}, 'characterEvolutions')
+ ? { characterEvolutions: localPlan.characterEvolutions }
+ : {}
+);
+
+// Everything an older sender cannot represent inside `seriesPlan`, in one
+// place: the v4 delivery plan, the v5 plot-point kinds, and the v8 evolution
+// lenses. Returns `remote` BY REFERENCE when there is nothing to restore, so
+// the common merge allocates no copy.
+const preserveLegacySeriesPlan = (remote, local, senderVersion) => {
+ const evolutions = preserveLegacyCharacterEvolutions(remote, local, senderVersion);
+ if (senderVersion >= 5) {
+ return evolutions.characterEvolutions ? { ...remote, ...evolutions } : remote;
+ }
+ const localPlotPoints = new Map((local?.plotPoints || []).map((item) => [item.id, item]));
+ return {
+ ...remote,
+ ...preserveLegacyDeliveryPlan(remote, local, senderVersion),
+ plotPoints: (remote?.plotPoints || []).map((item) => ({
+ ...item,
+ ...(localPlotPoints.has(item.id) ? { kind: localPlotPoints.get(item.id).kind } : {}),
+ })),
+ // Last, so the key lands where `sanitizeSeriesPlan` puts it — this merge
+ // result is persisted without a re-sanitize.
+ ...evolutions,
+ };
+};
+
// An older peer cannot represent newer scene production fields. When that
// peer wins whole-record LWW after an unrelated edit, retain the local fields
// on nodes that still exist instead of letting its unaware sanitizer clear
// them. A sender at the current schema version's present null remains an
// intentional clear.
const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
- if (!local || senderVersion >= 7) return remote;
+ if (!local || senderVersion >= 8) return remote;
+ const seriesPlan = preserveLegacySeriesPlan(remote.seriesPlan, local.seriesPlan, senderVersion);
+ // A v7 sender's ONLY unrepresentable field is the evolution lens above —
+ // every branch below is gated at <7 or lower. Returning early keeps the
+ // dominant legacy path off the O(episodes x nodes) rebuild it would all skip.
+ if (senderVersion >= 7) {
+ return seriesPlan === remote.seriesPlan ? remote : { ...remote, seriesPlan };
+ }
const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));
- const localPlotPoints = new Map((local.seriesPlan?.plotPoints || []).map((item) => [item.id, item]));
- const legacyRenderSettings = senderVersion < 5
- ? local.renderSettings
- : {
- ...remote.renderSettings,
- ...Object.fromEntries(FABLELOOM_RENDER_PREFERENCE_KEYS
- .filter((key) => Object.prototype.hasOwnProperty.call(local.renderSettings, key))
- .map((key) => [key, local.renderSettings[key]])),
- };
return {
...remote,
...(senderVersion < 6 ? {
// v5 peers understand the aspect-ratio format but would strip the
// provider/model preferences added in v6 during an unrelated update.
- renderSettings: legacyRenderSettings,
+ renderSettings: senderVersion < 5 ? local.renderSettings : {
+ ...remote.renderSettings,
+ ...Object.fromEntries(FABLELOOM_RENDER_PREFERENCE_KEYS
+ .filter((key) => Object.prototype.hasOwnProperty.call(local.renderSettings, key))
+ .map((key) => [key, local.renderSettings[key]])),
+ },
} : {}),
...(senderVersion < 5 ? {
productionStatus: local.productionStatus,
} : {}),
- seriesPlan: senderVersion < 5 ? {
- ...remote.seriesPlan,
- ...preserveLegacyDeliveryPlan(remote.seriesPlan, local.seriesPlan, senderVersion),
- plotPoints: (remote.seriesPlan?.plotPoints || []).map((item) => ({
- ...item,
- ...(localPlotPoints.has(item.id) ? { kind: localPlotPoints.get(item.id).kind } : {}),
- })),
- } : remote.seriesPlan,
+ seriesPlan,
...(senderVersion < 4 ? {
protagonistCharacterId: local.protagonistCharacterId,
protagonistWardrobeId: local.protagonistWardrobeId,
@@ -777,7 +841,7 @@ export async function mergeLoomsFromSync(
remoteLooms,
{
source = { via: 'sync', peerId: null },
- senderSchemaVersions = { fableLoom: 7 },
+ senderSchemaVersions = { fableLoom: 8 },
} = {},
) {
if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index 816e6876c6..a73bf721b6 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -31,6 +31,8 @@ const {
restoreLoom, sanitizeLoom, updateEpisode, updateLoom,
mutateLoom, updateNode, updateNodeTransition,
} = await import('./records.js');
+const { fableLoomEvolutionEvidenceRefs } = await import('./records.js');
+const { evolutionEvidenceStatus } = await import('../../lib/characterEvolution.js');
const { _resetFableLoomBackend } = await import('./store.js');
const conflictJournal = await import('../../lib/conflictJournal.js');
const { registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import('../sharing/recordEvents.js');
@@ -1264,3 +1266,98 @@ describe('attachNodePlaybackAsset and node playback fields', () => {
expect(targetNode.playbackAssets.holdLoopVideoHistoryIds).toEqual(['vid-h1', 'vid-h2']);
});
});
+
+describe('per-character evolution lens on the series plan (#6440)', () => {
+ const lens = (outcome, stages) => ({
+ characterId: 'chr-mara',
+ characterName: 'Mara',
+ evolution: { outcome, stages },
+ });
+
+ const seedLoomWithLens = async () => {
+ let loom = await makeLoom({ name: 'A lensed loom' });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ const episodeId = loom.episodes[0].id;
+ return updateLoom(loom.id, {
+ seriesPlan: {
+ ...loom.seriesPlan,
+ characterEvolutions: [lens('tragic-refusal', [
+ { stageId: 'control-strategy-failing', testedBelief: 'winning is safety' },
+ { stageId: 'final-proof', characterChoice: 'burns the ledger', evidence: { episodeId } },
+ ])],
+ },
+ });
+ };
+
+ it('leaves a plan that never opted in byte-identical', async () => {
+ const loom = await makeLoom({ name: 'A plain loom' });
+ expect(Object.prototype.hasOwnProperty.call(loom.seriesPlan, 'characterEvolutions')).toBe(false);
+ expect(JSON.stringify(sanitizeLoom(loom).seriesPlan)).toBe(JSON.stringify(loom.seriesPlan));
+ });
+
+ it('round-trips an authored lens through save, load and re-sanitize', async () => {
+ const saved = await seedLoomWithLens();
+ const reloaded = await getLoom(saved.id);
+ expect(reloaded.seriesPlan.characterEvolutions).toEqual(saved.seriesPlan.characterEvolutions);
+ expect(JSON.stringify(sanitizeLoom(reloaded).seriesPlan))
+ .toBe(JSON.stringify(reloaded.seriesPlan));
+ // The evidence anchor resolves against the loom's live episodes; a lens
+ // pointing at a deleted one must report stale rather than pass as proof.
+ const refs = fableLoomEvolutionEvidenceRefs(reloaded);
+ const proof = reloaded.seriesPlan.characterEvolutions[0].evolution.stages[1];
+ expect(evolutionEvidenceStatus(proof.evidence, refs)).toBe('anchored');
+ const afterDelete = await deleteEpisode(reloaded.id, reloaded.episodes[0].id);
+ expect(afterDelete.seriesPlan.characterEvolutions[0].evolution.stages[1].evidence.episodeId)
+ .toBe(proof.evidence.episodeId);
+ expect(evolutionEvidenceStatus(
+ afterDelete.seriesPlan.characterEvolutions[0].evolution.stages[1].evidence,
+ fableLoomEvolutionEvidenceRefs(afterDelete),
+ )).toBe('stale');
+ });
+
+ it('preserves the lens when a v7 peer wins an unrelated LWW edit', async () => {
+ const loom = await seedLoomWithLens();
+ const { characterEvolutions: _dropped, ...planWithoutLens } = loom.seriesPlan;
+ const remoteV7 = {
+ ...loom,
+ name: 'Renamed by v7 peer',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ seriesPlan: planWithoutLens,
+ };
+
+ await mergeLoomsFromSync([remoteV7], { senderSchemaVersions: { fableLoom: 7 } });
+
+ const merged = await getLoom(loom.id);
+ expect(merged.name).toBe('Renamed by v7 peer');
+ // A v7 sanitizer cannot represent the lens, so its omission is "cannot
+ // represent", not "the author deleted it".
+ expect(merged.seriesPlan.characterEvolutions).toEqual(loom.seriesPlan.characterEvolutions);
+ });
+
+ it('lets a v8 peer clear the lens it fully understands, and round-trips one it sends', async () => {
+ const loom = await seedLoomWithLens();
+ const { characterEvolutions: _dropped, ...planWithoutLens } = loom.seriesPlan;
+
+ await mergeLoomsFromSync([{
+ ...loom,
+ name: 'Cleared by v8 peer',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ seriesPlan: planWithoutLens,
+ }], { senderSchemaVersions: { fableLoom: 8 } });
+ expect((await getLoom(loom.id)).seriesPlan.characterEvolutions).toBeUndefined();
+
+ await mergeLoomsFromSync([{
+ ...loom,
+ updatedAt: '2099-01-02T00:00:00.000Z',
+ seriesPlan: {
+ ...planWithoutLens,
+ characterEvolutions: [lens('flat-testing', [{ stageId: 'cost-tested', characterChoice: 'holds' }])],
+ },
+ }], { senderSchemaVersions: { fableLoom: 8 } });
+ const restored = await getLoom(loom.id);
+ expect(restored.seriesPlan.characterEvolutions[0].evolution).toMatchObject({
+ outcome: 'flat-testing',
+ stages: [{ stageId: 'cost-tested', characterChoice: 'holds' }],
+ });
+ });
+});
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 050139a568..e7cbe4d9fc 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -743,6 +743,36 @@ describe('pipeline series service', () => {
const cleared = await svc.updateSeries(s.id, { characterArcs: [] });
expect(cleared.characterArcs).toEqual([]);
});
+
+ it('persists an authored five-stage evolution lens, and clears it on its own (#6440)', async () => {
+ const s = await svc.createSeries({ name: 'X' });
+ const authored = await svc.updateSeries(s.id, {
+ characterArcs: [{
+ characterName: 'Mara',
+ want: 'revenge',
+ evolution: {
+ outcome: 'partial-open',
+ outcomeNote: 'she gets most of the way there',
+ stages: [
+ { stageId: 'control-strategy-failing', testedBelief: 'winning is safety' },
+ { stageId: 'commitment-to-change', characterChoice: 'asks for help', evidence: { atIssue: 5 } },
+ ],
+ },
+ }],
+ });
+ const fresh = await svc.getSeries(s.id);
+ expect(fresh.characterArcs[0].evolution).toEqual(authored.characterArcs[0].evolution);
+ expect(fresh.characterArcs[0].evolution.stages.map((st) => st.stageId))
+ .toEqual(['control-strategy-failing', 'commitment-to-change']);
+
+ // Dropping the lens leaves the rest of the arc intact — it is a lens over
+ // the arc, never a gate on it.
+ const cleared = await svc.updateSeries(s.id, {
+ characterArcs: [{ characterName: 'Mara', want: 'revenge' }],
+ });
+ expect(cleared.characterArcs[0].evolution).toBeUndefined();
+ expect(cleared.characterArcs[0].want).toBe('revenge');
+ });
});
// Issue #1361 — a behind/legacy peer pushes a newer series payload that simply
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index b2e8be6024..599793a0bd 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2380,7 +2380,14 @@ describe('sharing round-trip', () => {
const result = await importer.processManifest(bucket.id, exp.filename);
expect(result.skipped).toBe(true);
expect(result.reason).toBe('portos-schema-ahead');
- expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 12 }]);
+ // Receiver version read from the live registry — this test is about the
+ // per-category GATE, not about which number pipelineSeries is on today
+ // (the registry's own test pins that). Imported lazily because the
+ // static-import graph is hoisted above this file's `vi.mock` setup.
+ const { PORTOS_SCHEMA_VERSIONS } = await import('../../lib/schemaVersions.js');
+ expect(result.ahead).toEqual([
+ { category: 'pipelineSeries', senderV: 99, receiverV: PORTOS_SCHEMA_VERSIONS.pipelineSeries },
+ ]);
expect(result.producedByVersion).toBe('99.0.0');
// Series stayed tombstoned (or absent) — apply was refused.
await expect(series.getSeries(s.id)).rejects.toThrow();