Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: map tested belief through cost to behavioral proof in the FableLoom plan review (#6443)
[._.]/ Adam Eivya86c3b48b16f
diff --git a/data.reference/prompts/stages/fableloom-review-series-plan.md b/data.reference/prompts/stages/fableloom-review-series-plan.mdindex bedfea177f..8aff1de22c 100644--- a/data.reference/prompts/stages/fableloom-review-series-plan.md+++ b/data.reference/prompts/stages/fableloom-review-series-plan.md@@ -16,6 +16,84 @@ You are a senior story editor analyzing the complete plan for an interactive braEvaluate the long-form dramatic arc, escalation and payoff of the ordered plot points, pacing across episodes, integration and resolution of side quests, continuity, thematic coherence, and whether the plan leaves each episode a distinct dramatic job. When beat outlines are present in the episode outline, review their scene-by-scene progression as one continuous teleplay series: check that each episode inherits the previous episode's consequences, that the protagonist and world remain consistent, that branch outcomes reconverge honestly, and that the finale's configured voicemail/teaser handoffs are earned. Account for branching storytelling: meaningful paths can vary locally, but the series-level promises and payoffs still need to remain legible.+{{#characterEvolutions}}+## Authored character evolution (five-stage lens)++The author has recorded an OPTIONAL five-stage lens for the characters below. It+states the causal chain this series is meant to run a character through:++**tested control belief → external pressure that forces exploration → the choice+→ the cost paid → the final behavioral proof**++- *control strategy failing* — the belief the character controls their world+ with, and the first sign it no longer works.+- *pressure forces exploration* — the external pressure that makes the old+ strategy unusable and forces them to look for another way.+- *commitment to change* — the choice they actually make.+- *cost tested* — what that choice costs them, and whether they can bear it.+- *final proof* — the closing BEHAVIOR that proves the change (or the refusal).++For each character carrying a lens, walk the plan and say WHERE each stage is+paid off — which plot point, side quest, episode, or beat carries it — and where+the chain breaks. **The final proof is character behavior, not the defeat of an+external obstacle.** A plan whose climax wins the external fight while the+declared change is never demonstrated by what the character DOES is a risk, not+a strength — say so even when the plot resolves cleanly.++The `declared outcome` is authored intent. It changes your verdict; it never+suppresses this pass:++- `full-change` — the change must endure and be proven by behavior. An external+ victory with no behavioral evidence in the plan IS a risk.+- `tragic-refusal` — doubling down on the control belief is the INTENDED+ ending. Do not report it as a flat or failed arc. The risk here is the+ opposite: a refusal the plan never actually tests — no real pressure, no cost+ paid — so the character never had a change to refuse.+- `flat-testing` — the belief is tested and deliberately HOLDS; the character+ changes the world around them instead of themselves. Constancy is the point:+ do not report it as a flat arc or an arc gap.+- `partial-open` — partial change, or an ending left genuinely open, is a+ legitimate ending. Incompleteness itself is NOT a risk; an UNEARNED CLAIM OF+ COMPLETION is — a plan asserting the character is transformed when the stages+ were never paid off.+- `undeclared` — the author has not yet said how the arc lands. Treat the+ stages as provisional planning, not as intent to hold the plan to.++Evidence: a stage annotated `[stale]` points at an episode or scene that no+longer exists and `[unverified]` could not be resolved. Neither is proof.+Missing or unresolved evidence means NOT PROVEN — never read it as passing.++Two failure modes need DIFFERENT repairs — never merge them into one risk:++- **no authored intent** — the plan plainly needs a stage the lens never+ authors. Begin the risk with `No authored intent:` and make its+ recommendation name the stage to author.+- **authored intent not delivered** — a stage IS authored but no plot point,+ side quest or episode delivers it. Begin the risk with+ `Authored intent not delivered:` and make its recommendation name the+ concrete scene or plan repair that would land that stage.++Every `recommendations[]` entry you raise from this pass must name a concrete+scene or plan repair — which episode, which plot point, what happens there — not+a restatement of the gap.++This is a craft lens over the authored beats — NOT a page count, a chapter+count, an episode quota, or a percentage layout. Do not require five episodes,+fixed positions, a stage per episode, or a changed belief that is the literal+opposite of the tested one. A character with no lens is judged exactly as they+were before. In a branching plan a stage may be paid off on some paths only —+name the paths that miss it rather than calling the stage absent.++**When every authored lens is satisfied, this pass contributes nothing.** Report+it as a strength or say nothing at all; do NOT manufacture an evolution risk to+fill the section. An empty `risks` array is the correct answer for a plan with+no problems.++```+{{characterEvolutions}}+```+{{/characterEvolutions}}+Return ONLY valid JSON matching this shape:```jsondiff --git a/scripts/migrations/368-fableloom-plan-review-evolution.js b/scripts/migrations/368-fableloom-plan-review-evolution.jsnew file mode 100644index 0000000000..959e1f84b8--- /dev/null+++ b/scripts/migrations/368-fableloom-plan-review-evolution.js@@ -0,0 +1,47 @@+/**+ * Map tested control belief through cost to behavioral proof in the FableLoom+ * series-plan review (#6443, epic #6418).+ *+ * The shipped template evaluated arc, escalation, pacing, side-quest lifecycle,+ * continuity, thematic coherence and per-episode dramatic job — and said+ * nothing about character transformation being EARNED BY BEHAVIOR. Two+ * consequences at plan time: a climax that wins the external fight read as a+ * clean payoff even with no behavioral proof anywhere in the plan, and a+ * deliberately flat or tragic ending read as an arc gap.+ *+ * The new `{{characterEvolutions}}` section carries the staged causal chain+ * plus the declared outcome, makes the outcome change the verdict rather than+ * suppress the pass, and splits "no authored intent" from "authored intent not+ * delivered" so the two get different repairs. It also states explicitly that a+ * satisfied lens contributes NOTHING — a plan review that always emitted an+ * evolution risk would spin `editorialAutopilot.runPlanning()` to `maxRounds`.+ *+ * The section is mustache-gated and the variable renders '' when no lens is+ * authored, so an install with no lens sends a byte-identical prompt to the+ * pre-migration one. Hash replacement preserves customized prompts.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'fableloom-review-series-plan.md': ['1c1ab552f6f6a4d9d51f1d3bacd89122'],+};++export const NEW_SHIPPED_MD5 = {+ 'fableloom-review-series-plan.md': '588c82fafd733581490f24cb6fb4bfa7',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'FableLoom plan review maps belief → cost → behavioral proof',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and adopt the\n` ++ ' "Authored character evolution (five-stage lens)" section with its\n' ++ ' {{characterEvolutions}} block, declared-outcome rulings, and the\n' ++ ' "no authored intent" / "authored intent not delivered" split.',+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/368-fableloom-plan-review-evolution.test.js b/scripts/migrations/368-fableloom-plan-review-evolution.test.jsnew file mode 100644index 0000000000..d3fa52579a--- /dev/null+++ b/scripts/migrations/368-fableloom-plan-review-evolution.test.js@@ -0,0 +1,91 @@+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 './368-fableloom-plan-review-evolution.js';++// Wrap-insensitive: the template is hard-wrapped at 80 columns, so a phrase+// assertion keyed to today's line breaks would fail on a pure re-wrap that+// changed no guidance at all.+const body = () => readFileSync(+ `${repoRoot}/data.reference/prompts/stages/fableloom-review-series-plan.md`,+ 'utf8',+).replace(/\s+/g, ' ');++describe('migration 368 — FableLoom plan review evolution lens', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-368-fableloom-plan-review-evolution-',+ });++ it('gates the lens behind the variable weave.js supplies', () => {+ // Without the mustache SECTION the block renders even with no lens authored+ // — which breaks the "unchanged review for a plan with no lens" promise.+ // Without the VARIABLE the section renders empty forever.+ const md = body();+ expect(md).toContain('{{#characterEvolutions}}');+ expect(md).toContain('{{characterEvolutions}}');+ expect(md).toContain('{{/characterEvolutions}}');+ });++ it('states the causal chain and rules every declared outcome', () => {+ const md = body();+ // The chain is what the plan digest alone cannot express; shipping the lens+ // data without it leaves the model to guess the mapping.+ for (const stage of [+ 'control strategy failing',+ 'pressure forces exploration',+ 'commitment to change',+ 'cost tested',+ 'final proof',+ ]) {+ expect(md).toContain(stage);+ }+ // An unruled outcome falls back to the pre-lens reading, which is the bug:+ // a tragic refusal or a deliberate flat arc reported as an arc gap.+ for (const outcome of ['full-change', 'tragic-refusal', 'flat-testing', 'partial-open', 'undeclared']) {+ expect(md).toContain(`\`${outcome}\``);+ }+ expect(md).toContain('do not report it as a flat arc');+ expect(md).toContain('UNEARNED CLAIM OF COMPLETION');+ });++ it('makes an external victory with no behavioral proof a risk, not a strength', () => {+ // The single behavior #6418 names as the reason the lens reaches the plan+ // review at all.+ const md = body();+ expect(md).toContain('not the defeat of an external obstacle');+ expect(md).toContain('is a risk, not a strength');+ });++ it('keeps the two failure modes separable and demands a concrete repair', () => {+ const md = body();+ // They need different repairs, so the risk text must stay separable by a+ // reader (and by a downstream filter).+ expect(md).toContain('`No authored intent:`');+ expect(md).toContain('`Authored intent not delivered:`');+ expect(md).toContain('must name a concrete scene or plan repair');+ // A stale/unverified anchor can never read as verified (epic non-negotiable).+ expect(md).toContain('[stale]');+ expect(md).toContain('[unverified]');+ expect(md).toContain('NOT PROVEN');+ });++ it('lets a satisfied lens end the planning loop', () => {+ // `editorialAutopilot.runPlanning()` re-runs feedback while `risks` is+ // non-empty. A prompt that always emits an evolution risk turns that into a+ // maxRounds spin, so the template has to say the empty answer is correct.+ const md = body();+ expect(md).toContain('this pass contributes nothing');+ expect(md).toContain('An empty `risks` array is the correct answer');+ // No page counts / episode quotas / literal-opposite belief.+ expect(md).toContain('NOT a page count, a chapter count, an episode quota');+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 5153938269..bcb9e51ba3 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -65,6 +65,7 @@ const EXPECTED_STAGE_OLD = {'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b', '513b2b5b8fa98766852cdde7b87198c9', '820b8c157c1977b34eb317e44236519e'],'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c', '8154b4c289b10268df8fd3c625bcdac2'],+ 'fableloom-review-series-plan.md': ['1c1ab552f6f6a4d9d51f1d3bacd89122'],'fableloom-feedback-series-plan.md': ['6c4f6c846acc6186eaa8da297080b9d9'],'fableloom-plan-shots.md': ['4cf0fb96d4e9a17a8ae8285ec134f37f'],'fableloom-review-shots.md': ['699ba1189f67338728b74834269759a9'],@@ -117,6 +118,7 @@ const EXPECTED_STAGE_NEW = {'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937','fableloom-outline-episode.md': '2ff6fb72777ff0c6fc70f3afd0ddfd53','fableloom-review-episode-outline.md': '0f549ed25dea8566ce2d3c515968783b',+ 'fableloom-review-series-plan.md': '588c82fafd733581490f24cb6fb4bfa7','fableloom-feedback-series-plan.md': '2d1b40041223baa02a1517a102f103c2','fableloom-plan-shots.md': '9b1cd4b406ee327d6dc3fcbd57b48483','fableloom-review-shots.md': '8cf5fe685cc5f75537caddea1d272a00',diff --git a/server/lib/characterEvolution.js b/server/lib/characterEvolution.jsindex 6bfb38a960..f7e9218db7 100644--- a/server/lib/characterEvolution.js+++ b/server/lib/characterEvolution.js@@ -414,3 +414,37 @@ export function renderCharacterEvolutionForPrompt(evolution, refs = {}) {if (!stageLines.length && outcome === 'undeclared' && !note) return null;return [`declared outcome: ${outcome}${note}`, ...stageLines].join('\n');}++/**+ * Render every authored lens in a per-character LIST as one prompt block, or+ * `null` when nothing in the list carries one.+ *+ * Both hosts keep a per-character list — `series.characterArcs[]` on the+ * pipeline side, `loom.seriesPlan.characterEvolutions[]` on the FableLoom side+ * — and each needs the same nesting, the same "null, not ''" contract (which+ * is what keeps a consumer's `{{#characterEvolution*}}` section empty and its+ * behavior byte-identical to pre-lens), and the same per-entry evidence+ * resolution. Written once here rather than per host, because the rule that+ * differs is only WHERE the reference sets come from.+ *+ * `refs` is either one reference-set object shared by every entry (FableLoom:+ * episode ids and scene keys are loom-wide) or a function called per entry to+ * derive its own (pipeline: a lens resolves against ITS OWN arc's transition+ * beats, never the whole cast's).+ */+export function renderCharacterEvolutionListForPrompt(list, refs = {}) {+ if (!Array.isArray(list)) return null;+ const refsFor = typeof refs === 'function' ? refs : () => refs;+ const blocks = [];+ for (const entry of list) {+ if (!entry || typeof entry !== 'object') continue;+ const lens = renderCharacterEvolutionForPrompt(entry.evolution, refsFor(entry));+ if (!lens) continue;+ const name = entry.characterName || '(unnamed character)';+ // Indent the lens body under its character so a multi-character block stays+ // readable — the renderer already indents stage lines two spaces relative+ // to the outcome line, and this preserves that nesting.+ blocks.push(`- ${name}\n${lens.split('\n').map((line) => ` ${line}`).join('\n')}`);+ }+ return blocks.length ? blocks.join('\n') : null;+}diff --git a/server/lib/seriesCharacterArc.js b/server/lib/seriesCharacterArc.jsindex 57943f4587..98f566d44b 100644--- a/server/lib/seriesCharacterArc.js+++ b/server/lib/seriesCharacterArc.js@@ -39,7 +39,7 @@ import {isCanonCharacterId,isStoryBeatId,optIssueNumber,- renderCharacterEvolutionForPrompt,+ renderCharacterEvolutionListForPrompt,sanitizeCharacterEvolution,} from './characterEvolution.js';import { trimTo, trimToClause } from './textUtils.js';@@ -246,18 +246,5 @@ export function characterArcEvidenceRefs(arc) {* degrade to exactly its pre-lens behavior.*/export function renderCharacterEvolutionsForPrompt(arcs) {- if (!Array.isArray(arcs)) return null;- const blocks = [];- for (const arc of arcs) {- if (!arc || typeof arc !== 'object') continue;- const lens = renderCharacterEvolutionForPrompt(arc.evolution, characterArcEvidenceRefs(arc));- if (!lens) continue;- const name = arc.characterName || '(unnamed character)';- // Indent the lens body under its character so a multi-character block stays- // readable — the renderer already indents stage lines two spaces relative- // to the outcome line, and this preserves that nesting.- const body = lens.split('\n').map((line) => ` ${line}`).join('\n');- blocks.push(`- ${name}\n${body}`);- }- return blocks.length ? blocks.join('\n') : null;+ return renderCharacterEvolutionListForPrompt(arcs, characterArcEvidenceRefs);}diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 16e858a1bc..a07e55db3f 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -19,6 +19,7 @@ import { runStagedLLM } from '../stageRunner.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { resolveLlmRoutePin } from '../../lib/llmRoutePin.js';import { renderStoryCanonDigest } from '../../lib/universePromptRenderers.js';+import { renderCharacterEvolutionListForPrompt } from '../../lib/characterEvolution.js';import { GRAPH_ISSUE_CODES, analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';import {FABLELOOM_CAMERA_MOVEMENT_VALUES,@@ -45,7 +46,7 @@ import {participationContractForPrompt,} from '../../lib/fableLoomParticipation.js';import { getUniverse } from '../universeBuilder.js';-import { LOOM_LIMITS, findEpisode, findNode, getLoom, mutateLoom } from './records.js';+import { LOOM_LIMITS, fableLoomEvolutionEvidenceRefs, findEpisode, findNode, getLoom, mutateLoom } from './records.js';import { asLoomFormat, loomFormatLabel, narrationFormatContract, sceneFormatContract } from './formats.js';const TRANSCRIPT_TURNS_MAX = 12;@@ -264,6 +265,19 @@ const seriesPlanDigest = (loom) => JSON.stringify({})),}, null, 2);+// The OPTIONAL five-stage evolution lens (#6443), rendered for whichever cast+// members carry one. `seriesPlanDigest` above is a hand-picked projection of+// `loom.seriesPlan` — it whitelists fields, so the lens would NOT ride along+// inside it — and the plan review needs the lens gated on its own anyway:+// unset ⇒ '', the template's {{#characterEvolutions}} section renders nothing,+// and the review degrades to exactly its pre-lens behavior. Anchors resolve+// against the whole loom (episode ids and scene keys are loom-wide), so a stage+// pointing at a deleted episode reads `[stale]` instead of passing as proof.+const characterEvolutionsDigest = (loom) => renderCharacterEvolutionListForPrompt(+ loom.seriesPlan?.characterEvolutions,+ fableLoomEvolutionEvidenceRefs(loom),+) || '';+const seriesTeleplayDigest = (loom) => loom.episodes.map((episode) => [`## Episode ${episode.number}: ${episode.title || 'Untitled'}`,episode.synopsis ? `Synopsis: ${trimTo(episode.synopsis, 500)}` : '',@@ -1054,6 +1068,7 @@ export async function reviewSeriesPlan(loomId, { providerId, model, effort, operstoryContext: [storyContext(loom, undefined, { includeSeriesPlan: false }), planningOnly ? 'PRE-OUTLINE REVIEW: Evaluate the arc, challenge design and episode assignments. Missing or stale episode outlines are expected at this stage and will be drafted or repaired next; do not report their absence as a plan defect. Keep plot-point notes concise; episode beat outlines have their own fields.' : ''].filter(Boolean).join('\n'),canonDigest: canonDigest || '(none)',seriesPlanJson: seriesPlanDigest(loom),+ characterEvolutions: characterEvolutionsDigest(loom),}, { providerId, model, effort, operationId }, {action: 'review-series-plan', label: 'Reviewing series plan', source: 'fableloom-review-series-plan',});diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 253ee63673..652e1880e4 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -1355,6 +1355,80 @@ describe('series plan AI', () => {}), expect.objectContaining({ providerOverride: 'writer' }));});+ it('sends no evolution block, and a byte-identical plan digest, when no lens is authored', async () => {+ // The epic's non-negotiable: with the lens unset the review must be exactly+ // the pre-#6443 review. The gated section renders nothing only if the+ // variable is '' — and `seriesPlanDigest` must not have grown a field.+ const { loomId } = await setup();+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'Strong spine.', risks: [] }, runId: 'run-a' });+ await reviewSeriesPlan(loomId, { planningOnly: true });+ const variables = runStagedLLM.mock.calls[0][1];+ expect(variables.characterEvolutions).toBe('');+ expect(JSON.parse(variables.seriesPlanJson)).not.toHaveProperty('characterEvolutions');+ });++ it('feeds the authored lens to the plan review and never presents a dead anchor as proof', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, {+ seriesPlan: {+ characterEvolutions: [+ {+ characterName: 'Mara',+ evolution: {+ outcome: 'full-change',+ stages: [+ { stageId: 'control-strategy-failing', testedBelief: 'Only leverage keeps her safe.' },+ { stageId: 'final-proof', characterChoice: 'She hands the ledger back.', evidence: { episodeId } },+ ],+ },+ },+ {+ characterName: 'Joss',+ evolution: {+ outcome: 'tragic-refusal',+ stages: [{ stageId: 'cost-tested', causalConsequence: 'He keeps the ledger.', evidence: { episodeId: 'ep-deleted-0000' } }],+ },+ },+ ],+ },+ });+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'The proof lands.', risks: [] }, runId: 'run-b' });+ await reviewSeriesPlan(loomId, { planningOnly: true });+ const block = runStagedLLM.mock.calls[0][1].characterEvolutions;+ expect(block).toContain('- Mara');+ expect(block).toContain('declared outcome: full-change');+ expect(block).toContain('declared outcome: tragic-refusal');+ // Mara's anchor names a live episode; Joss's names a deleted one. Resolving+ // against the loom is what keeps the dead pointer from reading as proof.+ expect(block).toContain(`episode ${episodeId} [anchored]`);+ expect(block).toContain('episode ep-deleted-0000 [stale]');+ });++ it('accepts an empty risks array from a lens-satisfied plan under the planning gate', async () => {+ // `editorialAutopilot.runPlanning()` loops while `risks` is non-empty, so a+ // lens the plan satisfies has to be able to END that loop — the verdict+ // contract must not read "no evolution risk" as a missing verdict.+ const { loomId } = await setup();+ await updateLoom(loomId, {+ seriesPlan: {+ characterEvolutions: [{+ characterName: 'Mara',+ evolution: { outcome: 'flat-testing', stages: [{ stageId: 'final-proof', characterChoice: 'She holds the line.' }] },+ }],+ },+ });+ runStagedLLM.mockResolvedValueOnce({+ content: {+ summary: 'Every authored stage pays off.',+ strengths: ['The refusal costs her the crew.'],+ risks: [],+ recommendations: [],+ },+ });+ const result = await reviewSeriesPlan(loomId, { planningOnly: true });+ expect(result.analysis.risks).toEqual([]);+ });+it('passes complete challenge outcomes and arc endings to review without duplicate plan context', async () => {const { loomId, episodeId } = await setup();const storyArc = `${'An established turn. '.repeat(340)}The final reconciliation.`;