Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: hold the FableLoom editor to per-character cast-integrity depth, not one uniform standard (#6415)
[._.]/ Adam Eivyec1d477cb1de
diff --git a/data.reference/prompts/stages/fableloom-editorial-remediate.md b/data.reference/prompts/stages/fableloom-editorial-remediate.mdindex d6b480ebe1..6d7c7b8157 100644--- a/data.reference/prompts/stages/fableloom-editorial-remediate.md+++ b/data.reference/prompts/stages/fableloom-editorial-remediate.md@@ -10,6 +10,29 @@ You are the single senior story editor responsible for evaluating and safely rem{{canonDigest}}+## Cast integrity — deterministic depth rulings++{{castIntegrity}}++The block above is a model-free pass over the same cast the world canon+describes, and its **depth ruling per character is binding on your `character`+findings**:++- `explained` — the author has ruled the interior out (unknown / not-applicable)+ and said why. That is a finished assessment, not a gap. Do not report it as one+ and do not ask for more.+- `light` — a declared minor role or a flat arc. Judge only the conscious+ pursuit (motivations, want). Never demand a Ghost, a wound, a trauma, or a+ redemption from one of these.+- `full` — the whole framework is fair to expect.++A filled field is not integrity: a `full`-depth character whose stated control+belief does not predict its own described behavior, whose survival, connection+and status drives are one sentiment restated three times, or whose Lie is simply+its theory of control reworded, is a `character` finding even though nothing is+blank. Conversely, never manufacture damage to fill a slot — an absence the+author explained is not a deficiency.+## Series plan and episode outlines{{seriesPlanJson}}@@ -40,6 +63,7 @@ You are the single senior story editor responsible for evaluating and safely rem- A scene with multiple incoming paths may set `visualCanon.continuitySourceNodeId` only to one of that scene's direct incoming predecessor scene ids. Use `null` only when intentionally removing an existing override.- A non-ending teleplay cut must retain exactly one outgoing transition. A decision scene must retain two or more. An ending must retain none.- Keep the canonical protagonist, wardrobe, participation mode, and world canon intact. Helper-mode audience conversations keep the protagonist off-screen; visible scenes keep the protagonist present.+- Character records are not yours to patch. Report a cast-integrity gap as a `character` finding that names the character and the field, and leave the record itself to the Universe Bible. Never paper over a thin character by rewriting scene prose to imply an interior the canon does not state.- Preserve strong material. Fix only concrete structural, continuity, coherence, agency, pacing, or payoff problems supported by the supplied evidence.- `findings` describes the evaluated state before this patch. `changes` names edits actually represented in the patch.- Omit unchanged keys. Never copy instructional labels or sample identifiers into story fields.diff --git a/scripts/migrations/365-fableloom-editorial-cast-integrity.js b/scripts/migrations/365-fableloom-editorial-cast-integrity.jsnew file mode 100644index 0000000000..48e75d9dc1--- /dev/null+++ b/scripts/migrations/365-fableloom-editorial-cast-integrity.js@@ -0,0 +1,38 @@+/**+ * Teach the FableLoom whole-series editor the deterministic cast-integrity+ * block (#6415).+ *+ * The editor judged an interactive series against the full canon digest with no+ * statement of what each character actually owes the story, so a declared minor+ * role and a character whose interior the author explicitly ruled out both read+ * as thin leads — and nothing told it that a profile with every field filled can+ * still fail to hold together. The new `{{castIntegrity}}` section carries a+ * model-free depth ruling per character and makes it binding on the `character`+ * findings, plus the two rules the canon digest cannot express: a filled field+ * is not integrity, and an absence the author explained is not a deficiency.+ * It also states the boundary this surface needs — the editor patches the story,+ * never the character records. Hash replacement preserves customized prompts.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'fableloom-editorial-remediate.md': ['d73329e2341e7bea9935a96043ed045f'],+};++export const NEW_SHIPPED_MD5 = {+ 'fableloom-editorial-remediate.md': 'c0cce5cfe63ec4e94047415bbe83881b',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'FableLoom editorial cast integrity',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and adopt the {{castIntegrity}} section\n` ++ ' with its binding explained/light/full depth rulings.',+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/365-fableloom-editorial-cast-integrity.test.js b/scripts/migrations/365-fableloom-editorial-cast-integrity.test.jsnew file mode 100644index 0000000000..adf99ce144--- /dev/null+++ b/scripts/migrations/365-fableloom-editorial-cast-integrity.test.js@@ -0,0 +1,42 @@+import { readFileSync } from 'fs';+import { describe, expect, it } from 'vitest';++import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';+import migration, {+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ applyMigration,+} from './365-fableloom-editorial-cast-integrity.js';++describe('migration 365 — FableLoom editorial cast integrity', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-365-fableloom-editorial-cast-integrity-',+ });++ it('makes the depth rulings binding and keeps the editor off the character records', () => {+ const editor = readFileSync(+ `${repoRoot}/data.reference/prompts/stages/fableloom-editorial-remediate.md`,+ 'utf8',+ );+ // The variable editorial.js now supplies — without it the section renders as+ // literal mustache and the rulings say nothing.+ expect(editor).toContain('{{castIntegrity}}');+ expect(editor).toContain('binding on your `character`');+ // Each depth has to be named, or the editor cannot act on a ruling it is+ // told to obey.+ for (const depth of ['explained', 'light', 'full']) {+ expect(editor).toContain(`\`${depth}\``);+ }+ // Both halves of the issue's contract.+ expect(editor).toContain('A filled field is not integrity');+ expect(editor).toContain('manufacture damage to fill a slot');+ // The boundary this surface adds: FableLoom patches the story, never canon.+ // Without it the editor's cheapest way to close a cast gap is to invent the+ // missing interior in scene prose, which is exactly what must not happen.+ expect(editor).toContain('Character records are not yours to patch');+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 7aa206e445..4846ddb4b7 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -57,6 +57,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f', 'e44b6c50d741bbd21fc86f481684c410'],'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],+ 'fableloom-editorial-remediate.md': ['d73329e2341e7bea9935a96043ed045f'],'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8', '18a442e39b973e4074a0d595928a665d', 'e0f8d864caa8746912b56cd567f1c09d', 'b4d363db94fd8a9928fa977745c76ff9'],'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba', '6279b1c9912c300363a727245d22fe84', 'c14e2b9c435e43a8c3b134a62cd66d08'],'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],@@ -103,6 +104,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25','pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e','pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',+ 'fableloom-editorial-remediate.md': 'c0cce5cfe63ec4e94047415bbe83881b','fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e','fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',diff --git a/server/lib/README.md b/server/lib/README.mdindex fc8986ba2a..01775badbb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -112,6 +112,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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). || `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. || `bibleLimits.js` | `BIBLE_LIMITS` — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of `storyBible.js` (which pulls `crypto` + `fileUtils`) so `catalogTypes.js` and the browser bundle can read the numbers alone. || `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. || `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |diff --git a/server/lib/castIntegrityPrompt.js b/server/lib/castIntegrityPrompt.jsnew file mode 100644index 0000000000..290270b0ee--- /dev/null+++ b/server/lib/castIntegrityPrompt.js@@ -0,0 +1,82 @@+/**+ * Render a deterministic cast-integrity report into a prompt block (#6415).+ *+ * The report itself comes from `characterIntegrity.js` and makes zero provider+ * calls. This module is only the prompt-facing projection of it, and it lives+ * in `lib/` because more than one reviewing surface needs the SAME block:+ * the Series foundation judge (`pipeline/foundationJudgeContext.js`) and the+ * FableLoom whole-series editor (`fableLoom/editorial.js`) both hand a model a+ * cast and a depth ruling, and a second copy of this renderer would let the two+ * drift into disagreeing about what a `light` character owes the story.+ *+ * PURE: no I/O, no provider calls, no record reads.+ */++/**+ * Why a character is held to a lighter standard, in the reviewer's own terms.+ * The issue is explicit that these are EXPLAINED requirements, not silent+ * excuses: a depth the prompt cannot justify reads as inconsistent scoring.+ */+export const INTEGRITY_DEPTH_NOTES = Object.freeze({+ explained: 'interior declared unknown/not-applicable with an author note — a finished assessment, ask nothing further',+ light: 'declared minor role or flat arc — conscious pursuit only, no origin-damage chain',+ full: 'full framework expected',+});++const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);+const pluralLines = (count) => (count === 1 ? 'line' : 'lines');++/**+ * Render the deterministic report as a prompt block, bounded by `maxChars`.+ *+ * Rows carrying gaps are emitted first so a tight budget drops the clean ones —+ * a dropped clean line costs the reviewer nothing, where a dropped gap line+ * would hide the very thing the character dimension is scored on. The header+ * always survives, so a truncated block can never read as a full pass.+ *+ * `castLabel` names how the cast was scoped ("series-linked", "story-linked");+ * `budgetLabel` names the budget in the omission note, so each surface explains+ * the truncation in the terms its own prompt uses.+ */+export function renderCastIntegrity(report, {+ maxChars = Infinity,+ castLabel = 'series-linked',+ budgetLabel = 'judging budget',+} = {}) {+ const coverage = Array.isArray(report?.coverage) ? report.coverage : [];+ if (coverage.length === 0) return `(no ${castLabel} cast to measure)`;+ const byCharacter = new Map();+ for (const finding of (Array.isArray(report?.findings) ? report.findings : [])) {+ const own = byCharacter.get(finding.characterId) || [];+ own.push(`${finding.field} (${finding.kind})`);+ byCharacter.set(finding.characterId, own);+ }+ const withGaps = coverage.filter((row) => row.findingCount > 0).length;+ const head = [+ `Deterministic pass (no model call) over ${coverage.length} ${castLabel} characters — ${withGaps} carry gaps.`,+ `Depth rulings are BINDING: ${Object.entries(INTEGRITY_DEPTH_NOTES).map(([depth, note]) => `${depth} = ${note}`).join('; ')}.`,+ ];+ const rows = coverage+ .map((row) => {+ const gaps = byCharacter.get(row.characterId) || [];+ const detail = gaps.length+ ? `${gaps.length} gap${gaps.length === 1 ? '' : 's'}: ${gaps.join('; ')}`+ : `no gaps (${INTEGRITY_DEPTH_NOTES[row.depth] || INTEGRITY_DEPTH_NOTES.full})`;+ return { hasGaps: gaps.length > 0, line: `- **${row.characterName || 'Unnamed'}** [${row.depth}] — ${detail}` };+ })+ .sort((a, b) => Number(b.hasGaps) - Number(a.hasGaps));+ let remaining = maxChars - joinedLength(head);+ const kept = [];+ let index = 0;+ // Stop at the first row that does not fit rather than skipping ahead to a+ // shorter one: the sort put the gaps first, and a greedy fill would happily+ // drop a long gap line to keep a short clean one.+ while (index < rows.length && rows[index].line.length + 1 <= remaining) {+ kept.push(rows[index].line);+ remaining -= rows[index].line.length + 1;+ index += 1;+ }+ const omitted = rows.length - index;+ if (omitted > 0) kept.push(` [${omitted} clean cast-integrity ${pluralLines(omitted)} omitted to fit the ${budgetLabel}]`);+ return [...head, ...kept].join('\n');+}diff --git a/server/lib/index.js b/server/lib/index.jsindex bcc3adf14b..43b59348d8 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -118,6 +118,7 @@ export * from './bibleLimits.js';// the namespaced storyBible below.export * from './characterFramework.js';export * from './characterIntegrity.js';+export * from './castIntegrityPrompt.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';diff --git a/server/services/fableLoom/editorial.js b/server/services/fableLoom/editorial.jsindex 593f286588..59d82970fa 100644--- a/server/services/fableLoom/editorial.js+++ b/server/services/fableLoom/editorial.js@@ -25,6 +25,8 @@ import {} from '../../lib/fableLoomPlaytest.js';import { computeTopologicalNodeOrder } from '../../lib/fableLoomProduction.js';import { CHARS_PER_TOKEN, usableInputTokens } from '../../lib/contextBudget.js';+import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';+import { renderCastIntegrity } from '../../lib/castIntegrityPrompt.js';import {isFableLoomPlaybackMode,FABLELOOM_PROTAGONIST_PRESENCE,@@ -50,6 +52,12 @@ const REVIEW_CATEGORIES = new Set([const AUTOPILOT_QUALITY_THRESHOLD = 8;const EDITORIAL_PROMPT_HARD_MAX_CHARS = 1_000_000;const EDITORIAL_OUTPUT_RESERVE_TOKENS = 8_000;+// The cast-integrity block is CARVED OUT of the editorial prompt budget, never+// added beside it (#6415): whatever it uses is subtracted from what the+// playthrough digest is offered, so the total rendered prompt is bounded+// exactly as it was before. One short line per cast member is all it needs.+const EDITORIAL_CAST_INTEGRITY_BUDGET_SHARE = 0.02;+const EDITORIAL_CAST_INTEGRITY_MIN_CHARS = 400;const INSTRUCTION_PLACEHOLDER_VALUES = new Set(['concise whole-series editorial assessment','episode_id_from_input',@@ -324,6 +332,65 @@ const resolveEditorialPromptBudgetChars = async (stage, route, source) => {return editorialPromptBudgetChars(contextWindow);};+// ---------- cast integrity (#6415) ----------++/**+ * The characters this story actually stages: the canonical protagonist, every+ * scene visual binding, and every interaction-window speaker.+ *+ * Scoping matters because the integrity block is BINDING on the editor. A+ * universe holds every character its author ever wrote; measuring all of them+ * would hand the editor rulings about people this loom never puts on screen,+ * and spend the block's budget saying so.+ */+const loomCastCharacterIds = (loom) => {+ const ids = new Set();+ if (hasText(loom?.protagonistCharacterId)) ids.add(loom.protagonistCharacterId);+ for (const episode of asArray(loom?.episodes)) {+ for (const node of asArray(episode.nodes)) {+ for (const appearance of asArray(node.visualCanon?.characterAppearances)) {+ if (hasText(appearance?.characterId)) ids.add(appearance.characterId);+ }+ if (hasText(node.interactionWindow?.protagonistCharacterId)) {+ ids.add(node.interactionWindow.protagonistCharacterId);+ }+ }+ }+ return ids;+};++/**+ * The deterministic cast-integrity report for this loom. ZERO provider calls —+ * it runs wherever the other deterministic diagnostics do.+ *+ * A loom with no visual bindings yet stages nobody, and reporting "(no cast)"+ * there would silently exempt exactly the early stories that most need the+ * ruling. So an unbound loom falls back to the linked universe's cast: it is+ * the only cast the story can be about, and the editor already receives that+ * same canon in full.+ */+const loomCastIntegrityReport = (loom, universe) => {+ const cast = asArray(universe?.characters);+ const staged = loomCastCharacterIds(loom);+ const scoped = cast.filter((character) => staged.has(character?.id));+ return buildCastIntegrityReport(scoped.length ? scoped : cast);+};++const castIntegrityBudgetChars = (maxPromptChars) => Math.min(+ maxPromptChars,+ Math.max(+ EDITORIAL_CAST_INTEGRITY_MIN_CHARS,+ Math.floor(maxPromptChars * EDITORIAL_CAST_INTEGRITY_BUDGET_SHARE),+ ),+);++/** The prompt block, in the editor's own budget terms. */+const renderLoomCastIntegrity = (report, maxPromptChars) => renderCastIntegrity(report, {+ maxChars: castIntegrityBudgetChars(maxPromptChars),+ castLabel: 'story-linked',+ budgetLabel: 'editorial prompt budget',+});+/** Assemble every deterministic series-level authoring/playthrough signal. */export async function collectFableLoomEditorialDiagnostics(loom,@@ -364,6 +431,10 @@ export async function collectFableLoomEditorialDiagnostics(const playthroughErrors = episodes.reduce((total, episode) => (total + (episode.playtest?.stats.errorCount || 0)), 0);+ // Deterministic, zero-provider, and measured off the SAME universe snapshot+ // 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);const stats = {outlineErrors: outline.stats.errorCount,outlineWarnings: outline.stats.warningCount,@@ -377,6 +448,8 @@ export async function collectFableLoomEditorialDiagnostics(endingVariationCount: playthrough.stats.endingVariationCount,visitedTransitionCount: playthrough.stats.visitedTransitionCount,transitionCount: playthrough.stats.transitionCount,+ castCharacterCount: castIntegrity.castCount,+ castIntegrityFindings: castIntegrity.findings.length,};return {passed: outline.stats.ready@@ -387,6 +460,10 @@ export async function collectFableLoomEditorialDiagnostics(outline,playthrough,episodes,+ // Reported, never gating: a thin spear-carrier must not block a FableLoom+ // autopilot run the way a broken graph does. The editor is told about it;+ // the pass/fail contract is unchanged.+ castIntegrity,stats,};}@@ -956,13 +1033,18 @@ export async function evaluateAndRemediateFableLoom(loomId, {{ providerId, model, effort },'fableloom-editorial-remediate',);+ const castIntegrity = renderLoomCastIntegrity(diagnostics.castIntegrity, maxPromptChars);const variables = withCompletePlaythroughDigest({loom,report: diagnostics.playthrough,- maxPromptChars,+ // Carved out, not added beside: the playthrough digest is offered what the+ // integrity block did not spend, so the editorial prompt total is bounded+ // exactly as it was before this block existed.+ maxPromptChars: Math.max(0, maxPromptChars - castIntegrity.length),variables: {storyContext: storyContext(loom),canonDigest: dependencies.canonDigest || '(none)',+ castIntegrity,seriesPlanJson: seriesPlanDigest(loom),teleplayDigest: teleplayDigest(loom),deterministicDigest: diagnosticLines(diagnostics),@@ -1138,6 +1220,7 @@ export const __testing = {assertEditorialDependenciesUnchanged,assertEditorialPromptBudget,assertEditorialSnapshotUnchanged,+ castIntegrityBudgetChars,compactEditorialDiagnostics,diagnosticLines,editorialDependencyFingerprint,@@ -1147,7 +1230,10 @@ export const __testing = {exactGraphIdContract,finalizeEditorialOperation,loadEditorialDependencies,+ loomCastCharacterIds,+ loomCastIntegrityReport,renderEditorialPrompt,+ renderLoomCastIntegrity,sanitizeEvaluation,sanitizePlaythroughReview,seriesPlanDigest,diff --git a/server/services/fableLoom/editorial.test.js b/server/services/fableLoom/editorial.test.jsindex 8974098bb0..666380d03a 100644--- a/server/services/fableLoom/editorial.test.js+++ b/server/services/fableLoom/editorial.test.js@@ -779,3 +779,150 @@ it('still shows the editorial reviewer a reveal-gated character in full (#6426)'.toThrow(/single-editor limit/i);});});++describe('FableLoom editorial cast integrity (#6415)', () => {+ // Obviously-fake placeholder canon.+ const lead = {+ id: 'character-lead',+ name: 'Mara',+ role: 'protagonist',+ ghost: 'Lost the harbour crew on the deep line.',+ wound: 'Nobody came back for her.',+ lie: 'Asking for help is how couriers get killed.',+ want: 'Run the deep line alone and clear the debt.',+ need: 'Let the harbour crew carry half the run.',+ motivations: 'Clear the debt before the season closes.',+ };+ const spearCarrier = {+ id: 'character-dockhand',+ name: 'Dockhand',+ role: 'minor background dockhand',+ motivations: 'Finish the shift.',+ want: 'A quiet night.',+ };+ const explained = {+ id: 'character-auditor',+ name: 'The Auditor',+ role: 'antagonist',+ psychology: {+ assessment: 'unknown',+ assessmentNote: 'The story is told from outside this one. Its interior stays closed on purpose.',+ },+ };+ const offstage = { id: 'character-offstage', name: 'Never Seen', role: 'protagonist' };+ const universe = { characters: [lead, spearCarrier, explained, offstage] };++ const stagedLoom = () => {+ const loom = makeLoom();+ return {+ ...loom,+ universeId: 'universe-example',+ protagonistCharacterId: lead.id,+ episodes: loom.episodes.map((episode, index) => (index > 0 ? episode : {+ ...episode,+ nodes: episode.nodes.map((node, nodeIndex) => {+ if (nodeIndex === 1) {+ return {+ ...node,+ visualCanon: { mode: 'locked', characterAppearances: [{ characterId: spearCarrier.id }] },+ };+ }+ if (nodeIndex === 2) {+ return {+ ...node,+ interactionWindow: { enabled: true, protagonistCharacterId: explained.id },+ };+ }+ return node;+ }),+ })),+ };+ };++ it('measures only the cast the story actually stages', () => {+ // The universe holds every character its author ever wrote. Handing the+ // editor binding depth rulings about people this loom never puts on screen+ // spends the block's budget saying nothing and invites findings against+ // scenes that do not exist.+ expect([...__testing.loomCastCharacterIds(stagedLoom())].sort())+ .toEqual([explained.id, spearCarrier.id, lead.id].sort());++ const report = __testing.loomCastIntegrityReport(stagedLoom(), universe);+ expect(report.coverage.map((row) => row.characterId).sort())+ .toEqual([explained.id, spearCarrier.id, lead.id].sort());+ expect(report.findings.some((finding) => finding.characterId === offstage.id)).toBe(false);+ });++ it('falls back to the linked cast when a loom has staged nobody yet', () => {+ // A loom with no protagonist and no visual bindings stages nobody, and an+ // empty block would silently exempt exactly the early stories that most+ // need the ruling.+ const unbound = { ...makeLoom(), universeId: 'universe-example', protagonistCharacterId: null };+ expect(__testing.loomCastIntegrityReport(unbound, universe).castCount)+ .toBe(universe.characters.length);+ });++ it('holds a spear-carrier and an explained unknown to lighter requirements', () => {+ const report = __testing.loomCastIntegrityReport(stagedLoom(), universe);+ const depths = Object.fromEntries(report.coverage.map((row) => [row.characterId, row.depth]));+ expect(depths[lead.id]).toBe('full');+ expect(depths[spearCarrier.id]).toBe('light');+ expect(depths[explained.id]).toBe('explained');+ // No manufactured trauma: the ONLY thing this block may report about a+ // declared minor role or an author-closed interior is nothing at all.+ const ownFields = (characterId) => report.findings+ .filter((finding) => finding.characterId === characterId)+ .map((finding) => finding.field);+ expect(ownFields(spearCarrier.id)).toEqual([]);+ expect(ownFields(explained.id)).toEqual([]);+ // And the lead's unwritten interior IS reported — the psychology profile is+ // the one thing no blank count or canon digest reaches.+ expect(ownFields(lead.id)).toContain('psychology');+ });++ it('renders the depth rulings as binding, in this surface\'s own terms', () => {+ const block = __testing.renderLoomCastIntegrity(+ __testing.loomCastIntegrityReport(stagedLoom(), universe),+ 100_000,+ );+ expect(block).toContain('story-linked characters');+ expect(block).toContain('Depth rulings are BINDING');+ expect(block).toContain('**Dockhand** [light]');+ expect(block).toContain('**The Auditor** [explained]');+ expect(block).toContain('**Mara** [full]');+ });++ it('is carved out of the editorial budget, never added beside it', () => {+ // The whole "no budget growth" claim rests on this: the block can never+ // cost more than the budget it is subtracted from, so the digest that+ // receives the remainder is always offered a non-negative share.+ const report = __testing.loomCastIntegrityReport(stagedLoom(), universe);+ for (const budget of [200, 1_000, 500_000]) {+ expect(__testing.castIntegrityBudgetChars(budget)).toBeLessThanOrEqual(budget);+ }+ // Rows are dropped to fit; the header is the one line that always survives,+ // so a truncated block can never read to the editor as a clean cast.+ const tight = __testing.renderLoomCastIntegrity(report, 2_000);+ expect(tight.length).toBeLessThanOrEqual(2_000);+ expect(__testing.renderLoomCastIntegrity(report, 1)).toContain(+ "Depth rulings are BINDING",+ );+ });++ it('reports the cast integrity count without gating the autopilot on it', async () => {+ // A thin spear-carrier must not block a FableLoom run the way a broken+ // graph does — the editor is TOLD about it, the pass/fail contract is not.+ const withCast = await collectFableLoomEditorialDiagnostics(+ stagedLoom(),+ { universe, voiceProfiles: [], canonDigest: '' },+ );+ const withoutCast = await collectFableLoomEditorialDiagnostics(+ stagedLoom(),+ { universe: { characters: [] }, voiceProfiles: [], canonDigest: '' },+ );+ expect(withCast.stats.castCharacterCount).toBe(3);+ expect(withCast.stats.castIntegrityFindings).toBeGreaterThan(0);+ expect(withoutCast.stats.castIntegrityFindings).toBe(0);+ expect(withCast.passed).toBe(withoutCast.passed);+ });+});diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.jsindex 4157a2a82c..2fc0513c68 100644--- a/server/services/pipeline/foundationJudgeContext.js+++ b/server/services/pipeline/foundationJudgeContext.js@@ -12,6 +12,7 @@ import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';import { PSYCHOLOGY_DRIVE_AXES } from '../../lib/storyBible.js';import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';+import { renderCastIntegrity } from '../../lib/castIntegrityPrompt.js';// The character-framework subset the character dimension scores (Ghost → Wound →// Lie → Want → Need chain + secrets + arc fields). Shared by the hash projection@@ -202,61 +203,10 @@ export function countSeriesCastIntegrityFindings(characters, series, issues = []).findings.length;}-// Why a character is held to a lighter standard, in the judge's own terms. The-// issue is explicit that these are EXPLAINED requirements, not silent excuses:-// a depth the prompt cannot justify reads as inconsistent scoring.-const DEPTH_NOTE = Object.freeze({- explained: 'interior declared unknown/not-applicable with an author note — a finished assessment, ask nothing further',- light: 'declared minor role or flat arc — conscious pursuit only, no origin-damage chain',- full: 'full framework expected',-});--/**- * Render the deterministic report for the judge prompt, bounded by `maxChars`.- *- * Rows carrying gaps are emitted first so a tight budget drops the clean ones —- * a dropped clean line costs the judge nothing, where a dropped gap line would- * hide the very thing the character dimension is scored on. The header always- * survives, so the judge can never read a truncated block as a full pass.- */-export function renderCastIntegrity(report, { maxChars = Infinity } = {}) {- const coverage = Array.isArray(report?.coverage) ? report.coverage : [];- if (coverage.length === 0) return '(no series-linked cast to measure)';- const byCharacter = new Map();- for (const finding of (Array.isArray(report?.findings) ? report.findings : [])) {- const own = byCharacter.get(finding.characterId) || [];- own.push(`${finding.field} (${finding.kind})`);- byCharacter.set(finding.characterId, own);- }- const withGaps = coverage.filter((row) => row.findingCount > 0).length;- const head = [- `Deterministic pass (no model call) over ${coverage.length} series-linked characters — ${withGaps} carry gaps.`,- `Depth rulings are BINDING: ${Object.entries(DEPTH_NOTE).map(([depth, note]) => `${depth} = ${note}`).join('; ')}.`,- ];- const rows = coverage- .map((row) => {- const gaps = byCharacter.get(row.characterId) || [];- const detail = gaps.length- ? `${gaps.length} gap${gaps.length === 1 ? '' : 's'}: ${gaps.join('; ')}`- : `no gaps (${DEPTH_NOTE[row.depth] || DEPTH_NOTE.full})`;- return { hasGaps: gaps.length > 0, line: `- **${row.characterName || 'Unnamed'}** [${row.depth}] — ${detail}` };- })- .sort((a, b) => Number(b.hasGaps) - Number(a.hasGaps));- let remaining = maxChars - joinedLength(head);- const kept = [];- let index = 0;- // Stop at the first row that does not fit rather than skipping ahead to a- // shorter one: the sort put the gaps first, and a greedy fill would happily- // drop a long gap line to keep a short clean one.- while (index < rows.length && rows[index].line.length + 1 <= remaining) {- kept.push(rows[index].line);- remaining -= rows[index].line.length + 1;- index += 1;- }- const omitted = rows.length - index;- if (omitted > 0) kept.push(` [${omitted} clean cast-integrity ${pluralLines(omitted)} omitted to fit the judging budget]`);- return [...head, ...kept].join('\n');-}+// The prompt-facing render of the report above lives in lib/castIntegrityPrompt.js+// so the FableLoom editor renders the SAME block from the SAME depth notes.+// Re-exported here because the judge context is where its callers look for it.+export { renderCastIntegrity };// ---------- input hashing (fast-pass / staleness) ----------