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

detect a character-evolution stage inherited at a reconvergence it was never earned on (#6444)

[._.]/ Adam Eivy6549cfbaf681
diff --git a/server/lib/README.md b/server/lib/README.md
index 4b18477c57..698a6d40f3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -111,6 +111,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. |
| `storyBible.js` | Canonical Character / Place / Object shapes; re-exports `BIBLE_LIMITS` from `bibleLimits.js`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |
| `characterEvolution.js` | The OPTIONAL five-stage character evolution lens (#6440): `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `CHARACTER_EVOLUTION_LIMITS`, `sanitizeCharacterEvolution` + `sanitizeCharacterEvolutionList` (null when unauthored, unknown stage/outcome rejected not coerced), `evolutionEvidenceStatus` (derived on read — only `anchored` counts as verified, a pointer to a deleted beat reports `stale`), `isDeclaredEvolution`, `renderCharacterEvolutionForPrompt`, and the per-character story-list primitives both hosts share (`isCanonCharacterId`, `isStoryBeatId`, `characterIdentityKey`, `optIssueNumber`, `EVOLUTION_EVIDENCE_FIELDS`). A pure leaf over `bibleLimits.js` + `textUtils.js` so `client/src/lib/characterEvolution.js` mirrors it into the browser bundle. |
+| `characterEvolutionCoverage.js` | Branch coverage for the evolution lens (#6444): `analyzeCharacterEvolutionCoverage` walks every bounded playthrough and flags `EVOLUTION_UNEARNED_INHERITANCE` — a stage proved on one incoming branch of a reconvergence and not another, so a viewer inherits a change they never watched be earned — plus unproven declared endings, out-of-sequence stage anchors and dead evidence pointers (`EVOLUTION_COVERAGE_CODES`). Introduces `unreviewed` (`EVOLUTION_COVERAGE_STATUSES`): a bounded-out enumeration, a cycle or an unresolvable anchor is explicitly NOT `verified` and NOT a defect. Deterministic and provider-free; returns `null` when no lens is authored, so a loom that never opted in is byte-identical. |
| `characterEvolutionValidation.js` | Zod schemas for the evolution lens — `characterEvolutionSchema` (one lens), `characterEvolutionStageSchema`, `characterEvolutionEvidenceSchema` and `characterEvolutionListSchema` (the FableLoom plan's per-character list). Its own module rather than a `sharedSchemas.js` fragment so `validation.js` (which nearly every suite reaches) doesn't grow an eager edge for a shape only two hosts validate. |
| `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). |
diff --git a/server/lib/characterEvolutionCoverage.js b/server/lib/characterEvolutionCoverage.js
new file mode 100644
index 0000000000..e97018422d
--- /dev/null
+++ b/server/lib/characterEvolutionCoverage.js
@@ -0,0 +1,544 @@
+/**
+ * Branch coverage for the five-stage character evolution lens (#6444, epic #6418).
+ *
+ * `characterEvolution.js` models what a story DECLARES about a character's
+ * transformation. This module asks the branching question that declaration
+ * cannot answer on its own: *on the path the viewer actually played*, was the
+ * change earned?
+ *
+ * In a branching story transformation is not one timeline. If the commitment
+ * stage is proved only on branch A, and A and B reconverge at a shared scene,
+ * then a viewer who played B arrives at that scene inheriting a change they
+ * never watched the character earn. That is the sharpest requirement in #6418
+ * and nothing else in the codebase detects it.
+ *
+ * DETERMINISTIC AND PROVIDER-FREE. It is graph analysis over authored data:
+ * no LLM call, no boot-time work, no background schedule. It runs from the
+ * existing user-triggered review entry point
+ * (`collectFableLoomEditorialDiagnostics`).
+ *
+ * Three rules this module deliberately does NOT break:
+ * - **The lens is optional and never a gate.** A loom with no authored lens
+ * returns `null` — no report, no findings, no stats — so its diagnostics
+ * are byte-identical to a pre-#6444 install's. Findings it does emit are
+ * reported, never folded into any pass/fail contract.
+ * - **A declared flat or tragic arc is not a defect.** `tragic-refusal` and
+ * `flat-testing` are checked for whether the refusal/constancy was TESTED
+ * on each path, never for the absence of a transformation.
+ * - **Partial coverage never reads as a pass.** Bounded-out enumeration, a
+ * cycle, or an anchor that does not resolve produces `unreviewed`, which
+ * is explicitly neither `verified` nor a defect finding.
+ *
+ * Reuse, not re-implementation: paths come from
+ * `enumerateEpisodePlaythroughs` (already bounded by
+ * `FABLELOOM_PLAYTEST_LIMITS`), and reconvergence comes from
+ * `computeTopologicalNodeOrder`'s `convergenceNodeIds`. The editorial
+ * collector hands its existing playthrough report straight in, so the review
+ * path pays for exactly one enumeration, not two.
+ *
+ * `analyzeStoryOutline` is intentionally NOT consulted: the outline/teleplay
+ * sync contract makes an expanded scene key identical to its node id, so the
+ * node graph is the only playable surface, and an episode that has an outline
+ * but no expanded scenes has nothing to walk — it reports `unreviewed` rather
+ * than being judged against a second, non-playable graph.
+ */
+
+import { EVOLUTION_STAGES, EVOLUTION_STAGE_LABELS, isDeclaredEvolution } from './characterEvolution.js';
+import { computeTopologicalNodeOrder } from './fableLoomProduction.js';
+import { enumerateEpisodePlaythroughs } from './fableLoomPlaytest.js';
+
+const asArray = (value) => (Array.isArray(value) ? value : []);
+const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
+
+/**
+ * Per-lens and whole-report coverage. Mirrors `CHARACTER_REVIEW_STATUSES` in
+ * `characterIntegrity.js` on purpose — the two answer the same shaped question
+ * about a cast, and a second vocabulary for "we did not actually look" is how
+ * one of them quietly starts meaning "clean".
+ * - `verified` — every stage resolved, every reachable path enumerated,
+ * nothing found.
+ * - `findings` — fully enumerated, and at least one finding.
+ * - `unreviewed` — coverage could not be established. NOT a pass, and NOT a
+ * defect. Wins over `findings` when both apply, because a
+ * partial review that reported two findings must not read
+ * as "those two and no more".
+ */
+export const EVOLUTION_COVERAGE_STATUSES = Object.freeze(['verified', 'findings', 'unreviewed']);
+
+/** Why an episode's paths could not be reasoned about. `null` = they could. */
+export const EVOLUTION_UNREVIEWED_REASONS = Object.freeze([
+ 'no-scenes', // the episode is still an outline; there is no playable graph
+ 'no-paths', // nothing walks from the opening scene (a broken/absent start)
+ 'variation-limit', // FABLELOOM_PLAYTEST_LIMITS truncated the enumeration
+ 'cycle', // a path repeats without terminating; prefixes are unreliable
+ 'step-limit', // a path hit the per-path scene ceiling
+]);
+
+/**
+ * How far one stage's evidence anchor got. Narrower than
+ * `EVOLUTION_EVIDENCE_STATUSES` because coverage needs a NODE, not just a
+ * resolvable pointer: an anchor naming a live episode but no scene resolves
+ * for the prompt renderer and still cannot be placed on a path.
+ * - `unanchored` — nothing authored.
+ * - `unverified` — authored, but it cannot be placed on a scene in a
+ * playable graph (episode-only anchor, an ambiguous scene
+ * key with no episode, or a beat the teleplay never
+ * expanded).
+ * - `stale` — authored and DEAD: it names an episode or a scene that
+ * does not exist. Preserved and reported, never satisfied.
+ * - `resolved` — placed on a concrete node in a concrete episode.
+ */
+export const EVOLUTION_ANCHOR_RESOLUTIONS = Object.freeze([
+ 'unanchored', 'unverified', 'stale', 'resolved',
+]);
+
+export const EVOLUTION_COVERAGE_CODES = Object.freeze({
+ EVIDENCE_STALE: 'EVOLUTION_EVIDENCE_STALE',
+ STAGE_OUT_OF_ORDER: 'EVOLUTION_STAGE_OUT_OF_ORDER',
+ ENDING_UNPROVEN: 'EVOLUTION_ENDING_UNPROVEN',
+ UNEARNED_INHERITANCE: 'EVOLUTION_UNEARNED_INHERITANCE',
+});
+
+// Findings are a bounded diagnostic block, not a list of every path. The
+// editorial compactor caps the WHOLE series at 80, so an unbounded lens block
+// would push the graph and continuity findings it is appended after out of the
+// report entirely.
+export const EVOLUTION_COVERAGE_FINDINGS_MAX = 40;
+
+const STAGE_INDEX = new Map(EVOLUTION_STAGES.map((stageId, index) => [stageId, index]));
+const stageLabel = (stageId) => EVOLUTION_STAGE_LABELS[stageId] || stageId;
+const nodeLabel = (node, nodeId) => (hasText(node?.title) ? node.title : nodeId);
+
+/**
+ * The scenes each episode can anchor evidence to, and the nodes that are
+ * actually playable.
+ *
+ * `sceneKeys` is the union of expanded node ids and authored outline keys:
+ * after expansion the sync contract makes them the same string, and before it
+ * only the outline exists — so a lens authored at either stage of the pipeline
+ * resolves, and only a pointer at something genuinely deleted reads stale.
+ */
+const buildSceneIndex = (loom) => new Map(asArray(loom?.episodes).map((episode) => {
+ const nodeIds = new Set(asArray(episode?.nodes).map((node) => node?.id).filter(hasText));
+ const sceneKeys = new Set(nodeIds);
+ for (const scene of asArray(episode?.storyOutline?.scenes)) {
+ if (hasText(scene?.key)) sceneKeys.add(scene.key);
+ }
+ return [episode.id, { episode, nodeIds, sceneKeys }];
+}));
+
+/**
+ * Place one stage's evidence on a concrete node, or say why it could not be.
+ *
+ * Resolution is EPISODE-SCOPED, which `evolutionEvidenceStatus` cannot be: it
+ * checks a loom-wide scene-key set, so an anchor naming episode 1 and a scene
+ * that only exists in episode 3 resolves there and is dead here. This resolver
+ * is therefore never more permissive than that one — only ever stricter, which
+ * is the direction the "never silently verified" rule allows.
+ */
+const resolveStageAnchor = (evidence, sceneIndex) => {
+ const episodeId = hasText(evidence?.episodeId) ? evidence.episodeId : '';
+ const sceneKey = hasText(evidence?.sceneKey) ? evidence.sceneKey : '';
+ if (!episodeId && !sceneKey) return { resolution: 'unanchored', episodeId: null, nodeId: null };
+ if (episodeId && !sceneIndex.has(episodeId)) {
+ return {
+ resolution: 'stale', episodeId, nodeId: null, dead: `episode ${episodeId}`,
+ };
+ }
+ if (!sceneKey) {
+ // A live episode with no scene named. Real authored intent, but there is
+ // no position on a path to test it at.
+ return { resolution: 'unverified', episodeId, nodeId: null };
+ }
+ let owner = episodeId ? sceneIndex.get(episodeId) : null;
+ if (!owner) {
+ // No episode authored: accept the scene key only when exactly one episode
+ // owns it. Two owners is genuinely ambiguous, and guessing an episode is
+ // how a stage gets credited to a branch it was never written for.
+ const owners = [...sceneIndex.values()].filter((entry) => entry.sceneKeys.has(sceneKey));
+ if (owners.length !== 1) {
+ return owners.length === 0
+ ? { resolution: 'stale', episodeId: null, nodeId: null, dead: `scene "${sceneKey}"` }
+ : { resolution: 'unverified', episodeId: null, nodeId: null };
+ }
+ [owner] = owners;
+ }
+ if (!owner.sceneKeys.has(sceneKey)) {
+ return {
+ resolution: 'stale',
+ episodeId: owner.episode.id,
+ nodeId: null,
+ dead: `scene "${sceneKey}" in episode ${owner.episode.id}`,
+ };
+ }
+ // Known to the outline but never expanded into a playable scene. The
+ // outline/teleplay sync check already reports that drift; here it just means
+ // the stage cannot be placed on a path.
+ if (!owner.nodeIds.has(sceneKey)) {
+ return { resolution: 'unverified', episodeId: owner.episode.id, nodeId: null };
+ }
+ return { resolution: 'resolved', episodeId: owner.episode.id, nodeId: sceneKey };
+};
+
+/**
+ * The paths for one episode, or the reason there are none to reason about.
+ * `paths: null` is the sentinel for "not enumerated"; `[]` never occurs
+ * alongside `enumerated: true` because an episode that produced no path at all
+ * is itself a reason.
+ */
+const episodePaths = (episode, playtest) => {
+ const unreviewed = (reason) => ({ enumerated: false, reason, paths: null });
+ if (!asArray(episode?.nodes).length) return unreviewed('no-scenes');
+ if (playtest.stats.enumerationComplete === false) return unreviewed('variation-limit');
+ const paths = asArray(playtest.paths);
+ if (!paths.length) return unreviewed('no-paths');
+ // A cycle or a step-limit stop means the walk was CUT SHORT, so a stage that
+ // is missing from a prefix may simply be past the cut. Reasoning about
+ // inheritance on a truncated prefix is exactly the false defect the epic
+ // forbids, so the whole episode reads unreviewed instead.
+ const bounded = paths.find((path) => path.termination === 'cycle' || path.termination === 'step-limit');
+ if (bounded) return unreviewed(bounded.termination === 'cycle' ? 'cycle' : 'step-limit');
+ return { enumerated: true, reason: null, paths };
+};
+
+/** First visit index per node on one path (a node may repeat under the visit cap). */
+const firstVisitIndex = (nodeIds) => {
+ const index = new Map();
+ nodeIds.forEach((nodeId, position) => {
+ if (!index.has(nodeId)) index.set(nodeId, position);
+ });
+ return index;
+};
+
+/**
+ * For ONE anchor node, how every reachable convergence scene sees it.
+ *
+ * Keyed by node rather than by (character, stage) on purpose: two characters
+ * anchoring the same scene ask the identical graph question, and the record
+ * caps (60 lenses x 5 stages against 200 scenes and 96 variations) make the
+ * per-stage form the one shape of this analysis that could get expensive.
+ */
+const convergenceViewOfAnchor = (anchorNodeId, paths, convergenceOnPath) => {
+ const provedBefore = new Set();
+ const unprovedBefore = new Set();
+ const anchoredAtOrAfter = new Set();
+ const example = new Map();
+ paths.forEach((path, pathIndex) => {
+ const anchorIndex = path.firstIndex.get(anchorNodeId);
+ for (const { nodeId, index } of convergenceOnPath[pathIndex]) {
+ if (anchorIndex !== undefined && anchorIndex < index) {
+ provedBefore.add(nodeId);
+ continue;
+ }
+ if (anchorIndex !== undefined) anchoredAtOrAfter.add(nodeId);
+ unprovedBefore.add(nodeId);
+ if (!example.has(nodeId)) {
+ example.set(nodeId, { pathId: path.id, viaNodeId: path.nodeIds[index - 1] || null });
+ }
+ }
+ });
+ return { provedBefore, unprovedBefore, anchoredAtOrAfter, example };
+};
+
+/**
+ * Which of a character's stages this path actually proves, IN STAGE ORDER.
+ *
+ * Order is load-bearing: a path that plays the commitment scene before the
+ * scene where the old strategy fails did not show the arc, it showed two
+ * scenes. The out-of-order stage is reported separately and, on this path,
+ * counts as unproven rather than being silently credited.
+ */
+const provedStagesOnPath = (stages, firstIndex) => {
+ const proved = new Set();
+ const outOfOrder = [];
+ let lastIndex = -1;
+ let lastStageId = null;
+ for (const stage of stages) {
+ const index = firstIndex.get(stage.nodeId);
+ if (index === undefined) continue;
+ if (index < lastIndex) {
+ outOfOrder.push({ stageId: stage.stageId, afterStageId: lastStageId });
+ continue;
+ }
+ lastIndex = index;
+ lastStageId = stage.stageId;
+ proved.add(stage.stageId);
+ }
+ return { proved, outOfOrder };
+};
+
+/**
+ * What one declared outcome needs a path to have shown by its ending.
+ *
+ * `full-change` is the only outcome that asks for the LAST authored stage: the
+ * declaration is that the change endures, so an ending reached without the
+ * closing proof is an ending where the viewer never saw it endure. Every other
+ * outcome — including the two that deliberately end in no transformation —
+ * asks only that SOME authored stage was played, i.e. that the belief was put
+ * under test on this branch. That is the difference between checking a refusal
+ * was earned and demanding a transformation the author never declared.
+ *
+ * The requirement is drawn from the stages anchored in THIS episode, so a lens
+ * whose closing proof lands in a later episode is not charged for it here.
+ */
+const requiredStageForEnding = (outcome, stages) => (
+ outcome === 'full-change' ? stages[stages.length - 1]?.stageId || null : null
+);
+
+/**
+ * Deterministic branch coverage for a loom's authored evolution lenses.
+ *
+ * Returns `null` when the plan has no lens at all — the caller adds nothing to
+ * its report, so an install that never opted in is byte-identical.
+ *
+ * @param {object} loom sanitized loom record
+ * @param {object} [options]
+ * @param {object} [options.playthroughReport] an `analyzeLoomPlaythroughs`
+ * result to reuse. Omit and each episode is enumerated here instead.
+ */
+export function analyzeCharacterEvolutionCoverage(loom, { playthroughReport = null } = {}) {
+ const lenses = asArray(loom?.seriesPlan?.characterEvolutions);
+ if (!lenses.length) return null;
+
+ const sceneIndex = buildSceneIndex(loom);
+ const findings = [];
+ // Counted even when the cap drops the finding itself, so a lens whose only
+ // findings fell off the end can never roll up as `verified`.
+ let lensFindingCount = 0;
+ const pushFinding = (finding) => {
+ lensFindingCount += 1;
+ if (findings.length < EVOLUTION_COVERAGE_FINDINGS_MAX) findings.push(finding);
+ };
+
+ // ---- per-episode path context (one enumeration, shared by every lens) ----
+ const episodes = [];
+ const contextById = new Map();
+ for (const episode of asArray(loom?.episodes)) {
+ // Reuse the caller's report when it covers this episode; an episode it
+ // does not carry is enumerated here rather than being reported unreviewed
+ // for a bookkeeping reason that has nothing to do with the graph.
+ const playtest = asArray(playthroughReport?.episodes)
+ .find((item) => item.episodeId === episode.id)
+ || enumerateEpisodePlaythroughs(episode);
+ const { enumerated, reason, paths } = episodePaths(episode, playtest);
+ const { convergenceNodeIds } = computeTopologicalNodeOrder(episode);
+ const nodeById = new Map(asArray(episode.nodes).map((node) => [node.id, node]));
+ const walked = enumerated
+ ? paths.map((path) => ({ ...path, firstIndex: firstVisitIndex(path.nodeIds) }))
+ : [];
+ const convergenceOnPath = walked.map((path) => path.nodeIds
+ .map((nodeId, index) => ({ nodeId, index }))
+ .filter(({ nodeId, index }) => convergenceNodeIds.has(nodeId)
+ && path.firstIndex.get(nodeId) === index));
+ contextById.set(episode.id, {
+ episode, enumerated, nodeById, paths: walked, convergenceOnPath, anchorViews: new Map(),
+ });
+ episodes.push({
+ episodeId: episode.id,
+ enumerated,
+ reason,
+ // Sentinel, not truthiness: `0` cannot occur here (an episode with no
+ // path is `no-paths`), so `null` unambiguously means "not enumerated".
+ pathCount: enumerated ? paths.length : null,
+ convergenceCount: convergenceNodeIds.size,
+ });
+ }
+ const anchorView = (context, anchorNodeId) => {
+ if (!context.anchorViews.has(anchorNodeId)) {
+ context.anchorViews.set(anchorNodeId, convergenceViewOfAnchor(
+ anchorNodeId, context.paths, context.convergenceOnPath,
+ ));
+ }
+ return context.anchorViews.get(anchorNodeId);
+ };
+
+ // ---- per-character coverage ----
+ const characters = [];
+ for (const lens of lenses) {
+ const { characterId, characterName, evolution } = lens;
+ lensFindingCount = 0;
+ const who = characterName || characterId || 'This character';
+ const declared = isDeclaredEvolution(evolution);
+ const outcome = declared ? evolution.outcome : null;
+ const stages = [];
+ const resolvedByEpisode = new Map();
+ let unreviewed = false;
+
+ for (const stage of asArray(evolution?.stages)) {
+ // `sanitizeEvolutionStage` rejects an unknown stage id rather than
+ // coercing it, so this only fires on an unsanitized caller — and a beat
+ // that cannot be placed in the sequence cannot be reasoned about, which
+ // is unreviewed, never verified.
+ if (!STAGE_INDEX.has(stage?.stageId)) {
+ unreviewed = true;
+ continue;
+ }
+ const anchor = resolveStageAnchor(stage.evidence, sceneIndex);
+ const context = anchor.nodeId ? contextById.get(anchor.episodeId) : null;
+ const enumerated = Boolean(context?.enumerated);
+ if (anchor.resolution !== 'resolved' || !enumerated) unreviewed = true;
+ if (anchor.resolution === 'stale') {
+ pushFinding({
+ code: EVOLUTION_COVERAGE_CODES.EVIDENCE_STALE,
+ severity: 'error',
+ message: `${who}'s "${stageLabel(stage.stageId)}" stage points at ${anchor.dead}, which no longer exists, so the stage can never be proved on any path.`,
+ remediation: 'Re-anchor the stage to a scene that still exists, or clear the evidence pointer.',
+ ...(characterId ? { characterId } : {}),
+ ...(anchor.episodeId ? { episodeId: anchor.episodeId } : {}),
+ stageId: stage.stageId,
+ });
+ }
+ const record = {
+ stageId: stage.stageId,
+ resolution: anchor.resolution,
+ episodeId: anchor.episodeId,
+ nodeId: anchor.nodeId,
+ // `null` = not computed (unresolved anchor, or an episode whose paths
+ // were bounded out); `0` = computed and proved on no path at all.
+ provenPathCount: null,
+ pathCount: enumerated ? context.paths.length : null,
+ };
+ stages.push(record);
+ if (anchor.resolution === 'resolved' && enumerated) {
+ const bucket = resolvedByEpisode.get(anchor.episodeId) || [];
+ bucket.push(record);
+ resolvedByEpisode.set(anchor.episodeId, bucket);
+ }
+ }
+ // A lens with no stages at all is a declaration with nothing behind it.
+ if (!stages.length) unreviewed = true;
+
+ for (const [episodeId, anchored] of resolvedByEpisode) {
+ const context = contextById.get(episodeId);
+ anchored.sort((a, b) => STAGE_INDEX.get(a.stageId) - STAGE_INDEX.get(b.stageId));
+ const requiredStageId = requiredStageForEnding(outcome, anchored);
+ const provenCounts = new Map(anchored.map((stage) => [stage.stageId, 0]));
+ const reportedOutOfOrder = new Set();
+ const uncoveredEndings = new Map();
+
+ for (const path of context.paths) {
+ const { proved, outOfOrder } = provedStagesOnPath(anchored, path.firstIndex);
+ for (const stageId of proved) provenCounts.set(stageId, provenCounts.get(stageId) + 1);
+ for (const { stageId, afterStageId } of outOfOrder) {
+ if (reportedOutOfOrder.has(stageId)) continue;
+ reportedOutOfOrder.add(stageId);
+ pushFinding({
+ code: EVOLUTION_COVERAGE_CODES.STAGE_OUT_OF_ORDER,
+ severity: 'warning',
+ message: `${who}'s "${stageLabel(stageId)}" stage is anchored to a scene the viewer reaches before "${stageLabel(afterStageId)}", so this path plays the arc out of sequence.`,
+ remediation: `Re-anchor "${stageLabel(stageId)}" to a scene later than "${stageLabel(afterStageId)}", or re-order the stages to match the story.`,
+ ...(characterId ? { characterId } : {}),
+ episodeId,
+ stageId,
+ pathId: path.id,
+ });
+ }
+ // Only a DECLARED outcome states what an ending owes the viewer. An
+ // undeclared lens is unfinished planning, and charging it for an
+ // outcome the author never made would invent the declaration.
+ if (!declared || path.termination !== 'ending') continue;
+ const covered = requiredStageId ? proved.has(requiredStageId) : proved.size > 0;
+ if (covered) continue;
+ const key = path.endingNodeId || 'unlabeled-ending';
+ const seen = uncoveredEndings.get(key);
+ if (seen) seen.count += 1;
+ else {
+ uncoveredEndings.set(key, {
+ count: 1,
+ pathId: path.id,
+ endingNodeId: path.endingNodeId,
+ endingLabel: path.endingLabel,
+ });
+ }
+ }
+ for (const stage of anchored) stage.provenPathCount = provenCounts.get(stage.stageId);
+
+ for (const ending of uncoveredEndings.values()) {
+ const label = ending.endingLabel
+ || nodeLabel(context.nodeById.get(ending.endingNodeId), ending.endingNodeId);
+ const what = requiredStageId
+ ? `never reaches the "${stageLabel(requiredStageId)}" stage`
+ : 'never puts the tested belief on screen';
+ pushFinding({
+ code: EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN,
+ severity: 'warning',
+ message: `${ending.count} playthrough(s) reach the ending "${label}" on a branch that ${what} for ${who}, so the declared "${outcome}" outcome is unproven there.`,
+ remediation: `Anchor an evolution stage to a scene on the branches that reach "${label}", or route those branches through the scene that already proves it.`,
+ ...(characterId ? { characterId } : {}),
+ episodeId,
+ ...(ending.endingNodeId ? { nodeId: ending.endingNodeId } : {}),
+ pathId: ending.pathId,
+ });
+ }
+
+ // ---- unearned inheritance at a reconvergence ----
+ for (const stage of anchored) {
+ const view = anchorView(context, stage.nodeId);
+ for (const convergenceNodeId of view.provedBefore) {
+ if (!view.unprovedBefore.has(convergenceNodeId)) continue; // a shared prerequisite
+ const laterAnchored = anchored.some((other) => (
+ STAGE_INDEX.get(other.stageId) > STAGE_INDEX.get(stage.stageId)
+ && anchorView(context, other.nodeId).anchoredAtOrAfter.has(convergenceNodeId)
+ ));
+ const { pathId, viaNodeId } = view.example.get(convergenceNodeId) || {};
+ const where = nodeLabel(context.nodeById.get(convergenceNodeId), convergenceNodeId);
+ const via = viaNodeId
+ ? ` (for example the branch arriving from "${nodeLabel(context.nodeById.get(viaNodeId), viaNodeId)}")`
+ : '';
+ pushFinding({
+ code: EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE,
+ // An arc the author declared CONTINUES past this scene is the case
+ // where the inheritance actually corrupts later content; a
+ // convergence with nothing anchored after it is a gap, not a lie.
+ severity: laterAnchored ? 'error' : 'warning',
+ message: `Branches reconverge at "${where}" with ${who}'s "${stageLabel(stage.stageId)}" stage proved on some incoming branches and not others${via}, so a viewer can arrive having never watched that change be earned.`,
+ remediation: `Prove "${stageLabel(stage.stageId)}" on every branch that reaches "${where}" (or before they split), or write a variant of "${where}" for the branches that have not earned it.`,
+ ...(characterId ? { characterId } : {}),
+ episodeId,
+ nodeId: convergenceNodeId,
+ stageId: stage.stageId,
+ ...(pathId ? { pathId } : {}),
+ });
+ }
+ }
+ }
+
+ characters.push({
+ characterId: characterId || '',
+ characterName: characterName || '',
+ outcome,
+ // `unreviewed` outranks `findings`: a lens with one dead anchor and one
+ // real finding has not been fully looked at, and saying `findings` there
+ // would present that one finding as the complete answer.
+ status: unreviewed ? 'unreviewed' : (lensFindingCount ? 'findings' : 'verified'),
+ stages,
+ });
+ }
+
+ const unreviewedCharacterCount = characters.filter((c) => c.status === 'unreviewed').length;
+ return {
+ status: unreviewedCharacterCount
+ ? 'unreviewed'
+ : (findings.length ? 'findings' : 'verified'),
+ findings,
+ characters,
+ episodes,
+ stats: {
+ lensCount: characters.length,
+ declaredLensCount: characters.filter((c) => c.outcome).length,
+ unreviewedLensCount: unreviewedCharacterCount,
+ unreviewedEpisodeCount: episodes.filter((e) => !e.enumerated).length,
+ findingCount: findings.length,
+ unearnedInheritanceCount: findings.filter((f) => (
+ f.code === EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE
+ )).length,
+ unprovenEndingCount: findings.filter((f) => (
+ f.code === EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN
+ )).length,
+ staleAnchorCount: findings.filter((f) => (
+ f.code === EVOLUTION_COVERAGE_CODES.EVIDENCE_STALE
+ )).length,
+ },
+ };
+}
+
diff --git a/server/lib/characterEvolutionCoverage.test.js b/server/lib/characterEvolutionCoverage.test.js
new file mode 100644
index 0000000000..02b90ccb51
--- /dev/null
+++ b/server/lib/characterEvolutionCoverage.test.js
@@ -0,0 +1,377 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ analyzeCharacterEvolutionCoverage,
+ EVOLUTION_COVERAGE_CODES,
+} from './characterEvolutionCoverage.js';
+import { analyzeLoomPlaythroughs, FABLELOOM_PLAYTEST_LIMITS } from './fableLoomPlaytest.js';
+
+const EPISODE_ID = 'ep-00000000-0000-4000-8000-000000000001';
+
+const scene = (id, title, targets, extra = {}) => ({
+ id,
+ title,
+ playbackMode: targets.length > 1 ? 'decision' : 'cut',
+ audienceConnection: 'connected',
+ isEnding: false,
+ transitions: targets.map((targetNodeId) => ({
+ id: `${id}-to-${targetNodeId}`,
+ targetNodeId,
+ intent: `Go to ${targetNodeId}`,
+ })),
+ ...extra,
+});
+
+const ending = (id, title, endingLabel) => ({
+ id,
+ title,
+ playbackMode: 'cut',
+ audienceConnection: 'connected',
+ isEnding: true,
+ endingLabel,
+ transitions: [],
+});
+
+/**
+ * Two branches that reconverge — the exact graph the epic's sharpest
+ * requirement is about. `opening` splits into `left` / `right`, both rejoin at
+ * `merge`, and `merge` runs to the single ending.
+ */
+const reconvergingEpisode = (id = EPISODE_ID) => ({
+ id,
+ number: 1,
+ title: 'The Divided Signal',
+ startNodeId: 'opening',
+ nodes: [
+ scene('opening', 'The Split', ['left', 'right']),
+ scene('left', 'Glass Bridge', ['merge']),
+ scene('right', 'Buried Wire', ['merge']),
+ scene('merge', 'The Junction', ['finale']),
+ ending('finale', 'The Beacon', 'Signal found'),
+ ],
+});
+
+/** Two branches that never rejoin, ending separately. */
+const forkingEpisode = () => ({
+ id: EPISODE_ID,
+ number: 1,
+ title: 'Two Roads',
+ startNodeId: 'opening',
+ nodes: [
+ scene('opening', 'The Split', ['left', 'right']),
+ scene('left', 'Glass Bridge', ['ending-a']),
+ scene('right', 'Buried Wire', ['ending-b']),
+ ending('ending-a', 'The Beacon', 'Signal found'),
+ ending('ending-b', 'The Silence', 'Signal lost'),
+ ],
+});
+
+// The sanitized shape `sanitizeCharacterEvolutionList` persists, built by hand
+// so this stays a pure-lib test with no record store behind it.
+const stage = (stageId, sceneKey, episodeId = EPISODE_ID) => ({
+ stageId,
+ testedBelief: 'Control is safety.',
+ externalPressure: '',
+ characterChoice: '',
+ causalConsequence: '',
+ evidence: sceneKey === null && episodeId === null
+ ? null
+ : {
+ atIssue: null,
+ atSceneAnchor: '',
+ transitionId: '',
+ episodeId: episodeId || '',
+ sceneKey: sceneKey || '',
+ },
+});
+
+const loomWith = (episodes, stages, outcome = 'full-change') => ({
+ id: 'loom-example',
+ name: 'Example Story',
+ participationMode: 'protagonist',
+ episodes,
+ seriesPlan: {
+ storyArc: '',
+ plotPoints: [],
+ sideQuests: [],
+ characterEvolutions: [{
+ characterId: 'chr-00000000-0000-4000-8000-0000000000aa',
+ characterName: 'Mara',
+ evolution: { outcome, outcomeNote: '', stages },
+ }],
+ },
+});
+
+const codes = (report) => report.findings.map((finding) => finding.code);
+const findingFor = (report, code) => report.findings.find((finding) => finding.code === code);
+
+describe('analyzeCharacterEvolutionCoverage', () => {
+ it('returns null for a loom that never opted into the lens', () => {
+ // The optional-lens non-negotiable: an install with no lens must add
+ // nothing at all to its diagnostics, not an empty report object.
+ const plain = loomWith([reconvergingEpisode()], []);
+ delete plain.seriesPlan.characterEvolutions;
+
+ expect(analyzeCharacterEvolutionCoverage(plain)).toBeNull();
+ expect(analyzeCharacterEvolutionCoverage({ ...plain, seriesPlan: {} })).toBeNull();
+ });
+
+ it('flags a stage proved on only one incoming branch of a reconvergence', () => {
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('commitment-to-change', 'left'), stage('final-proof', 'finale')],
+ ));
+
+ const finding = findingFor(report, EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE);
+ expect(finding).toBeDefined();
+ // The convergence scene is named by its stable node id, never by an
+ // ephemeral `path-N`, and the message points at the branch that did not
+ // earn it so the repair is actionable without re-deriving the graph.
+ expect(finding.nodeId).toBe('merge');
+ expect(finding.episodeId).toBe(EPISODE_ID);
+ expect(finding.stageId).toBe('commitment-to-change');
+ expect(finding.message).toContain('Buried Wire');
+ expect(finding.remediation).toContain('The Junction');
+ // `final-proof` is anchored downstream of the junction, so the story
+ // declares that content after it depends on the inherited change.
+ expect(finding.severity).toBe('error');
+ expect(report.stats.unearnedInheritanceCount).toBe(1);
+ });
+
+ it('accepts a stage proved before the branch point as a shared prerequisite', () => {
+ // The regression most likely to reappear: an over-eager convergence check
+ // that flags every reconvergence, including the legitimate case where the
+ // stage was earned before the branches ever split.
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('commitment-to-change', 'opening'), stage('final-proof', 'finale')],
+ ));
+
+ expect(codes(report)).not.toContain(EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE);
+ expect(report.stats.unearnedInheritanceCount).toBe(0);
+ });
+
+ it('accepts a stage proved at the convergence itself', () => {
+ // Every incoming branch plays that scene, so nothing is inherited — the
+ // second shape of the shared-prerequisite case.
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('commitment-to-change', 'merge')],
+ ));
+
+ expect(codes(report)).not.toContain(EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE);
+ });
+
+ it('downgrades an inherited stage with nothing anchored after the convergence', () => {
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('commitment-to-change', 'left')],
+ ));
+
+ expect(findingFor(report, EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE).severity)
+ .toBe('warning');
+ });
+
+ it('names the ending a declared full-change never proves', () => {
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [forkingEpisode()],
+ [stage('final-proof', 'left')],
+ ));
+
+ const finding = findingFor(report, EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN);
+ expect(finding.nodeId).toBe('ending-b');
+ expect(finding.message).toContain('Signal lost');
+ expect(finding.message).not.toContain('Signal found');
+ expect(report.stats.unprovenEndingCount).toBe(1);
+ });
+
+ it('never asks a tragic refusal or a flat arc to transform, only to be tested', () => {
+ const stages = [stage('control-strategy-failing', 'left'), stage('cost-tested', 'right')];
+ for (const outcome of ['tragic-refusal', 'flat-testing']) {
+ // Each branch plays one stage, so the belief IS put under test on both —
+ // a declared refusal or constancy must produce no finding here.
+ const tested = analyzeCharacterEvolutionCoverage(
+ loomWith([forkingEpisode()], stages, outcome),
+ );
+ expect(tested.findings).toEqual([]);
+ expect(tested.status).toBe('verified');
+
+ // ...and one branch that never stages the belief at all is still
+ // reported, because a refusal the viewer never watched is not earned.
+ const untested = analyzeCharacterEvolutionCoverage(loomWith(
+ [forkingEpisode()],
+ [stage('control-strategy-failing', 'left')],
+ outcome,
+ ));
+ expect(codes(untested)).toEqual([EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN]);
+ expect(findingFor(untested, EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN).message)
+ .toContain('Signal lost');
+ }
+ });
+
+ it('reports a cyclic graph as unreviewed rather than as a defect', () => {
+ const cyclic = {
+ id: EPISODE_ID,
+ number: 1,
+ title: 'The Loop',
+ startNodeId: 'opening',
+ nodes: [
+ scene('opening', 'The Split', ['loop', 'finale']),
+ scene('loop', 'The Return', ['opening']),
+ ending('finale', 'The Beacon', 'Signal found'),
+ ],
+ };
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [cyclic],
+ [stage('final-proof', 'loop')],
+ ));
+
+ expect(report.status).toBe('unreviewed');
+ expect(report.findings).toEqual([]);
+ expect(report.episodes[0]).toMatchObject({ enumerated: false, reason: 'cycle', pathCount: null });
+ expect(report.characters[0].stages[0].provenPathCount).toBeNull();
+ });
+
+ it('reports a bounded-out enumeration as unreviewed and reuses the caller report', () => {
+ const wide = {
+ id: EPISODE_ID,
+ number: 1,
+ title: 'Wide',
+ startNodeId: 'opening',
+ nodes: [
+ scene('opening', 'The Split', ['left', 'right']),
+ scene('left', 'Glass Bridge', ['finale']),
+ scene('right', 'Buried Wire', ['finale']),
+ ending('finale', 'The Beacon', 'Signal found'),
+ ],
+ };
+ const loom = loomWith([wide], [stage('final-proof', 'left')]);
+ const truncated = analyzeLoomPlaythroughs(loom, { maxPaths: 1 });
+ expect(truncated.complete).toBe(false);
+
+ const report = analyzeCharacterEvolutionCoverage(loom, { playthroughReport: truncated });
+
+ expect(report.status).toBe('unreviewed');
+ expect(report.episodes[0].reason).toBe('variation-limit');
+ // Truncated coverage must not manufacture the ending finding a complete
+ // enumeration would have produced from the same partial evidence.
+ expect(report.findings).toEqual([]);
+ expect(analyzeCharacterEvolutionCoverage(loom).status).toBe('findings');
+ });
+
+ it('keeps a dead evidence pointer reportable and never satisfied', () => {
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('final-proof', 'a-deleted-scene')],
+ ));
+
+ const finding = findingFor(report, EVOLUTION_COVERAGE_CODES.EVIDENCE_STALE);
+ expect(finding.message).toContain('a-deleted-scene');
+ expect(report.characters[0].stages[0]).toMatchObject({
+ resolution: 'stale', nodeId: null, provenPathCount: null,
+ });
+ expect(report.characters[0].status).toBe('unreviewed');
+ expect(report.status).toBe('unreviewed');
+
+ // A pointer at an episode that no longer exists is the same class of dead.
+ const goneEpisode = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('final-proof', 'left', 'ep-00000000-0000-4000-8000-00000000ffff')],
+ ));
+ expect(goneEpisode.characters[0].status).toBe('unreviewed');
+ expect(codes(goneEpisode)).toContain(EVOLUTION_COVERAGE_CODES.EVIDENCE_STALE);
+ });
+
+ it('separates "proved on no path" from "never computed"', () => {
+ // The sentinel rule: an unreachable-but-live scene is a real zero, and a
+ // `null` next to it must mean the analyzer never looked. Collapsing the two
+ // is how a partial review starts reading as a clean one.
+ const withOrphan = reconvergingEpisode();
+ withOrphan.nodes.push(scene('orphan', 'The Cut Scene', ['finale']));
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [withOrphan],
+ [stage('final-proof', 'orphan')],
+ ));
+
+ expect(report.characters[0].stages[0]).toMatchObject({
+ resolution: 'resolved', provenPathCount: 0,
+ });
+ expect(report.characters[0].stages[0].pathCount).toBeGreaterThan(0);
+ });
+
+ it('reports an out-of-sequence anchor instead of silently crediting it', () => {
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ // The commitment is anchored to the opening, before the scene where the
+ // control strategy is shown failing: the path plays the arc backwards.
+ [stage('control-strategy-failing', 'merge'), stage('commitment-to-change', 'opening')],
+ ));
+
+ const finding = findingFor(report, EVOLUTION_COVERAGE_CODES.STAGE_OUT_OF_ORDER);
+ expect(finding.stageId).toBe('commitment-to-change');
+ expect(finding.message).toContain('control strategy failing');
+ // One finding per stage, not one per enumerated path.
+ expect(codes(report).filter((code) => code === finding.code)).toHaveLength(1);
+ });
+
+ it('leaves an undeclared lens uncharged for an outcome its author never made', () => {
+ const undeclared = analyzeCharacterEvolutionCoverage(loomWith(
+ [forkingEpisode()],
+ [stage('final-proof', 'left')],
+ null,
+ ));
+
+ expect(codes(undeclared)).not.toContain(EVOLUTION_COVERAGE_CODES.ENDING_UNPROVEN);
+ expect(undeclared.characters[0].outcome).toBeNull();
+ // Structural inheritance is still checked — it is a defect regardless of
+ // what the author eventually declares.
+ const converging = analyzeCharacterEvolutionCoverage(loomWith(
+ [reconvergingEpisode()],
+ [stage('commitment-to-change', 'left')],
+ null,
+ ));
+ expect(codes(converging)).toContain(EVOLUTION_COVERAGE_CODES.UNEARNED_INHERITANCE);
+ });
+
+ it('reports an episode with no expanded scenes as unreviewed', () => {
+ const outlineOnly = {
+ id: EPISODE_ID,
+ number: 1,
+ title: 'Planned only',
+ startNodeId: null,
+ nodes: [],
+ storyOutline: { version: 1, startKey: 'beat-1', scenes: [{ key: 'beat-1' }] },
+ };
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [outlineOnly],
+ [stage('final-proof', 'beat-1')],
+ ));
+
+ expect(report.status).toBe('unreviewed');
+ expect(report.episodes[0].reason).toBe('no-scenes');
+ expect(report.findings).toEqual([]);
+ });
+
+ it('stays inside the playthrough limits on a branch-heavy graph', () => {
+ // Ten binary decisions is 1024 paths; the analyzer must inherit the
+ // harness's bound rather than walking them all.
+ const nodes = [];
+ for (let level = 0; level < 10; level += 1) {
+ nodes.push(scene(`d${level}`, `Decision ${level}`, [`l${level}`, `r${level}`]));
+ for (const side of ['l', 'r']) {
+ nodes.push(scene(`${side}${level}`, `${side}${level}`, [level === 9 ? 'finale' : `d${level + 1}`]));
+ }
+ }
+ nodes.push(ending('finale', 'The Beacon', 'Signal found'));
+ const report = analyzeCharacterEvolutionCoverage(loomWith(
+ [{
+ id: EPISODE_ID, number: 1, title: 'Wide', startNodeId: 'd0', nodes,
+ }],
+ [stage('final-proof', 'l0')],
+ ));
+
+ expect(report.episodes[0]).toMatchObject({ enumerated: false, reason: 'variation-limit' });
+ expect(report.status).toBe('unreviewed');
+ expect(FABLELOOM_PLAYTEST_LIMITS.DEFAULT_MAX_PATHS).toBeLessThan(1024);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index a54155635b..a8f96e691d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -116,6 +116,7 @@ export * from './taskDataInputCatalog.js';
export * from './bibleLimits.js';
// The optional five-stage character evolution lens, as a pure leaf.
export * from './characterEvolution.js';
+export * from './characterEvolutionCoverage.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/services/fableLoom/editorial.js b/server/services/fableLoom/editorial.js
index 59d82970fa..d21e77a9eb 100644
--- a/server/services/fableLoom/editorial.js
+++ b/server/services/fableLoom/editorial.js
@@ -26,6 +26,7 @@ import {
import { computeTopologicalNodeOrder } from '../../lib/fableLoomProduction.js';
import { CHARS_PER_TOKEN, usableInputTokens } from '../../lib/contextBudget.js';
import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';
+import { analyzeCharacterEvolutionCoverage } from '../../lib/characterEvolutionCoverage.js';
import { renderCastIntegrity } from '../../lib/castIntegrityPrompt.js';
import {
isFableLoomPlaybackMode,
@@ -435,6 +436,14 @@ export async function collectFableLoomEditorialDiagnostics(
// the continuity pass reads — so a depth ruling the editor is told is binding
// always names a character the canon digest actually describes.
const castIntegrity = loomCastIntegrityReport(loom, universe);
+ // Branch coverage for the OPTIONAL evolution lens (#6444). `null` when the
+ // plan never opted in, and every key it contributes is then omitted — so a
+ // loom without a lens produces byte-identical diagnostics to a pre-#6444
+ // install, and the lens never becomes a gate on a legacy story. Reuses the
+ // playthrough report already computed above; it adds no enumeration.
+ const evolutionCoverage = analyzeCharacterEvolutionCoverage(loom, {
+ playthroughReport: playthrough,
+ });
const stats = {
outlineErrors: outline.stats.errorCount,
outlineWarnings: outline.stats.warningCount,
@@ -450,6 +459,11 @@ export async function collectFableLoomEditorialDiagnostics(
transitionCount: playthrough.stats.transitionCount,
castCharacterCount: castIntegrity.castCount,
castIntegrityFindings: castIntegrity.findings.length,
+ ...(evolutionCoverage ? {
+ evolutionCoverageStatus: evolutionCoverage.status,
+ evolutionCoverageFindings: evolutionCoverage.stats.findingCount,
+ unreviewedEvolutionLenses: evolutionCoverage.stats.unreviewedLensCount,
+ } : {}),
};
return {
passed: outline.stats.ready
@@ -464,6 +478,10 @@ export async function collectFableLoomEditorialDiagnostics(
// autopilot run the way a broken graph does. The editor is told about it;
// the pass/fail contract is unchanged.
castIntegrity,
+ // Reported, never gating — for the same reason cast integrity is not: an
+ // unproven branch is a craft note, not a broken graph, and `passed` stays
+ // exactly the contract it was before the lens existed.
+ ...(evolutionCoverage ? { evolutionCoverage } : {}),
stats,
};
}
@@ -489,6 +507,13 @@ const diagnosticLines = (diagnostics) => {
lines.push(`- [playthrough/${issue.severity}] episode=${episode.episodeId} path=${issue.pathId || '-'} node=${issue.nodeId || '-'} code=${issue.code}: ${issue.message}`);
});
});
+ if (diagnostics.evolutionCoverage) {
+ const coverage = diagnostics.evolutionCoverage;
+ lines.push(`Character evolution coverage: ${coverage.status}; ${coverage.stats.declaredLensCount}/${coverage.stats.lensCount} lens(es) declared, ${coverage.stats.unreviewedLensCount} unreviewed.`);
+ coverage.findings.forEach((finding) => {
+ lines.push(`- [evolution/${finding.severity}] episode=${finding.episodeId || '-'} node=${finding.nodeId || '-'} stage=${finding.stageId || '-'} code=${finding.code}: ${finding.message} Fix: ${finding.remediation}`);
+ });
+ }
return lines.join('\n');
};
@@ -528,6 +553,18 @@ const compactEditorialDiagnostics = (diagnostics) => {
problem: finding.message,
suggestion: finding.remediation || 'Repair the continuity break.',
}))),
+ // Branch coverage for the evolution lens lands in the shared shape as
+ // `character`, so the editor reads it beside every other finding. Absent
+ // entirely when no lens is authored.
+ ...asArray(diagnostics.evolutionCoverage?.findings).map((finding) => ({
+ severity: finding.severity === 'error' ? 'high' : 'medium',
+ category: 'character',
+ episodeId: finding.episodeId || null,
+ nodeId: finding.nodeId || null,
+ pathId: finding.pathId || null,
+ problem: finding.message,
+ suggestion: finding.remediation,
+ })),
];
return {
passed: diagnostics.passed,
diff --git a/server/services/fableLoom/editorial.test.js b/server/services/fableLoom/editorial.test.js
index 666380d03a..0ba2a7c0fd 100644
--- a/server/services/fableLoom/editorial.test.js
+++ b/server/services/fableLoom/editorial.test.js
@@ -926,3 +926,79 @@ describe('FableLoom editorial cast integrity (#6415)', () => {
expect(withCast.passed).toBe(withoutCast.passed);
});
});
+
+describe('character evolution branch coverage in the editorial diagnostics (#6444)', () => {
+ const dependencies = { universe: null, voiceProfiles: [], canonDigest: '' };
+
+ const evolutionStage = (stageId, sceneKey) => ({
+ stageId,
+ characterChoice: 'She stops negotiating and walks onto the bridge.',
+ evidence: { episodeId: 'episode-example', sceneKey },
+ });
+
+ const lensedLoom = (stages, outcome = 'full-change') => {
+ const base = makeLoom();
+ return sanitizeLoom({
+ ...base,
+ seriesPlan: {
+ ...base.seriesPlan,
+ characterEvolutions: [{
+ characterId: 'chr-mara',
+ characterName: 'Mara',
+ evolution: { outcome, stages },
+ }],
+ },
+ });
+ };
+
+ it('adds nothing at all to a loom that never opted into the lens', async () => {
+ // The optional-lens non-negotiable, asserted as a literal baseline: a
+ // pre-#6444 install's diagnostics must be byte-identical, so the coverage
+ // block and every stat it contributes are omitted rather than nulled.
+ const diagnostics = await collectFableLoomEditorialDiagnostics(makeLoom(), dependencies);
+
+ expect(Object.hasOwn(diagnostics, 'evolutionCoverage')).toBe(false);
+ expect(Object.keys(diagnostics.stats).filter((key) => /evolution/i.test(key))).toEqual([]);
+ expect(__testing.diagnosticLines(diagnostics)).not.toMatch(/evolution/i);
+ expect(__testing.compactEditorialDiagnostics(diagnostics).findings
+ .some((finding) => finding.category === 'character')).toBe(false);
+ });
+
+ it('reports an unearned inheritance as a character finding without gating the run', async () => {
+ // `left` and `right` rejoin at the ending scene, and only `left` proves the
+ // commitment — a viewer who took `right` arrives having never watched it.
+ const lensed = lensedLoom([evolutionStage('commitment-to-change', 'left')]);
+ const plain = await collectFableLoomEditorialDiagnostics(makeLoom(), dependencies);
+ const diagnostics = await collectFableLoomEditorialDiagnostics(lensed, dependencies);
+
+ expect(diagnostics.evolutionCoverage.stats.unearnedInheritanceCount).toBe(1);
+ expect(diagnostics.stats.evolutionCoverageStatus).toBe('findings');
+ const characterFindings = __testing.compactEditorialDiagnostics(diagnostics).findings
+ .filter((item) => item.category === 'character');
+ // The rejoin scene is also this graph's only ending, so it is both the
+ // inherited convergence and the ending the declared change never reaches.
+ const inherited = characterFindings.find((item) => item.problem.includes('Buried Wire'));
+ expect(inherited).toMatchObject({
+ severity: 'medium', episodeId: 'episode-example', nodeId: 'ending',
+ });
+ expect(inherited.suggestion).toBeTruthy();
+ expect(characterFindings.some((item) => item.problem.includes('Signal found'))).toBe(true);
+ expect(characterFindings.every((item) => item.pathId)).toBe(true);
+ // Reported, never gating — and the graph the editor is handed is untouched.
+ expect(diagnostics.passed).toBe(plain.passed);
+ expect(__testing.exactGraphIdContract(lensed.episodes[0]))
+ .toBe(__testing.exactGraphIdContract(makeLoom().episodes[0]));
+ expect(__testing.teleplayDigest(lensed)).toBe(__testing.teleplayDigest(makeLoom()));
+ });
+
+ it('carries an unreviewed lens through to the editor instead of a silent pass', async () => {
+ const diagnostics = await collectFableLoomEditorialDiagnostics(
+ lensedLoom([evolutionStage('final-proof', 'a-deleted-scene')]),
+ dependencies,
+ );
+
+ expect(diagnostics.stats.evolutionCoverageStatus).toBe('unreviewed');
+ expect(diagnostics.stats.unreviewedEvolutionLenses).toBe(1);
+ expect(__testing.diagnosticLines(diagnostics)).toContain('Character evolution coverage: unreviewed');
+ });
+});
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index a46197e587..e2ea3a8d5c 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -282,7 +282,11 @@ function sanitizeSeriesPlan(raw, episodes) {
/**
* Reference sets a FableLoom evolution lens's evidence anchors resolve
- * against — every episode id, and every outline scene key across the loom.
+ * against — every episode id, and every scene an anchor can name across the
+ * loom: expanded teleplay node ids AND authored outline keys. The sync
+ * contract makes those the same string once an outline is expanded, so the
+ * union only widens for a graph-first episode whose outline was never written
+ * — where a live scene must not read as a deleted one.
* Hand it to `evolutionEvidenceStatus` so a stage pointing at a deleted
* episode or a renamed scene reports `stale` rather than passing as proof.
*/
@@ -290,6 +294,9 @@ export function fableLoomEvolutionEvidenceRefs(loom) {
const episodes = Array.isArray(loom?.episodes) ? loom.episodes : [];
const sceneKeys = new Set();
for (const episode of episodes) {
+ for (const node of episode?.nodes || []) {
+ if (node?.id) sceneKeys.add(node.id);
+ }
for (const scene of episode?.storyOutline?.scenes || []) {
if (scene?.key) sceneKeys.add(scene.key);
}
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index a73bf721b6..10168597d2 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -1315,6 +1315,22 @@ describe('per-character evolution lens on the series plan (#6440)', () => {
)).toBe('stale');
});
+ it('resolves an anchor at an expanded scene that has no outline beat', async () => {
+ // A graph-first episode has node ids and no outline; before #6444 the ref
+ // set was built from outline scene keys alone, so a live scene read as a
+ // deleted one and the stage could never be verified.
+ let loom = await makeLoom({ name: 'A graph-first loom' });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ const episodeId = loom.episodes[0].id;
+ loom = await addNode(loom.id, episodeId, { title: 'The Split' });
+ const { id: nodeId } = loom.episodes[0].nodes[0];
+ expect(loom.episodes[0].storyOutline).toBeFalsy();
+
+ const refs = fableLoomEvolutionEvidenceRefs(loom);
+ expect(evolutionEvidenceStatus({ episodeId, sceneKey: nodeId }, refs)).toBe('anchored');
+ expect(evolutionEvidenceStatus({ episodeId, sceneKey: 'node-deleted' }, refs)).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;