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
give foundation world repairs write headroom so a full premise can't stall the gate
[._.]/ Adam Eivy2e8f9b4e9598
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ca0b428e23..fae70435c2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -192,6 +192,8 @@## Series Pipeline+- **A world bible that has filled up no longer traps Autopilot at the foundation gate forever.** The foundation judge asked for what it should ask for — "this magic system has no stable constraint system; add a ruleset with its inputs, range, costs, failure modes, and hard impossibilities" — and the world repair had nowhere to put it. Everything a repair can write lands in the universe premise, and rounds of earlier repairs had grown that premise to 19,995 of its 20,000-character ceiling. The model was handed the full premise, told to preserve it, told to add a ruleset, and told to stay under 20,000; the only response that satisfies all four is the premise it already had. That came back under the cap, so it passed validation as a successful repair, the judge re-read an unchanged world and scored it identically, and the gate spent every round it was given before pausing on a foundation it could never have fixed. Two things changed. A bible field that is already near its ceiling now gets a **write budget below** it, and the repair is told plainly that the addition does not fit and that consolidating the existing prose — merging duplicated lore, collapsing parallel examples, never dropping a rule, cost, limit, or named entity — is part of the job; a rewrite that comes back the same size is now rejected and retried instead of being accepted as progress. And when the judge's own view of the world had to be shortened to fit its model's context, that shortening used to slice the end of the premise — exactly where a freshly written ruleset lands — so the judge could not see the repair it had just demanded. The budget is now spent on the **named-canon inventory** instead (the list of places and objects the judge already tends to say is over-supplied), keeping logline, premise, style, and influences whole. If a repair genuinely cannot be made to fit, the run pauses and says the bible is full and needs pruning, rather than looping.+- **Foundation results now call the next repair target what it is.** The gate deliberately chooses the largest weight-adjusted deficit, so a worldbuilding score of 8 can be the best next use of a repair round ahead of a structure score of 7. The Autopilot timeline and Series Review called that field the "weakest" dimension, which made the weighting look broken and obscured why a higher raw score ran first. They now say "next target," the options help names the largest weighted deficit, and server telemetry uses the same term; the persisted/API field remains backward-compatible.- **Character-first planning now finishes the whole story cast instead of repeatedly polishing six people.** The foundation repair selector had a hard top-six cutoff, so a larger ensemble could spend every bounded repair round revisiting the same principals while later story-referenced characters remained blank. It now derives the series roster from authored arcs and issue synopses, processes every referenced character in sequential six-character work batches, and gives each batch the full ensemble map so voices, values and relationships stay differentiated. The foundation judge and its cache use that same series-scoped roster, so undeveloped characters belonging to other stories in a shared universe no longer make this series fail its character gate; before an arc exists, the small fallback remains and the architect may add only genuinely missing core roles.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 38f4e807d7..2080b52d10 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -47,7 +47,7 @@ import { BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { getUniverse, updateUniverse } from '../universeBuilder.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';-import { expandWorldTemplate } from '../universeBuilderExpand.js';+import { expandWorldTemplate, narrativeRepairTargets } from '../universeBuilderExpand.js';import { getSeries, updateSeries } from './series.js';import { listIssues } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';@@ -526,19 +526,44 @@ function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransitreturn lines.join('\n');}-function renderWorldFoundation(universe) {+// Below this the named-canon line carries no usable signal — render the+// omission marker instead of a handful of dangling entity names.+const NAMED_CANON_MIN_CHARS = 200;++/**+ * Render the world as the worldbuilding dimension is scored on it, bounded by+ * `maxChars`.+ *+ * The budget is spent by dropping the NAMED-CANON inventory, never the narrative+ * spine. Causal rules, costs, hard limits, and failure modes live in the premise+ * and style notes; the entity list is the noun inventory whose over-supply the+ * judge already penalizes, and it is the part that grows without bound. Slicing+ * the joined block instead (what this did before) cut the TAIL of the premise —+ * exactly where a freshly authored ruleset lands — so a world repair the judge+ * had just demanded became invisible to the next judge, the score never moved,+ * and the foundation gate burned its rounds against a repair it could not see.+ */+function renderWorldFoundation(universe, { maxChars = Infinity } = {}) {if (!universe) return '(no linked universe — worldbuilding cannot be judged from canon)';- const entities = renderEntitiesSummary(universe, { maxPerKind: { characters: 0 } }) || '(no named places or objects)';const influences = universe.influences && typeof universe.influences === 'object'? `Embrace: ${(universe.influences.embrace || []).join(', ') || '—'}; Avoid: ${(universe.influences.avoid || []).join(', ') || '—'}`: '(none)';- return [+ const spine = [`Universe logline: ${universe.logline || '(none)'}`,`Universe premise: ${universe.premise || '(none)'}`,`Universe style: ${universe.styleNotes || '(none)'}`,`Influences: ${influences}`,- `Named canon: ${entities}`,].join('\n');+ const entities = renderEntitiesSummary(universe, { maxPerKind: { characters: 0 } }) || '(no named places or objects)';+ const canonLine = `Named canon: ${entities}`;+ const remaining = maxChars - spine.length - 1;+ if (canonLine.length <= remaining) return `${spine}\n${canonLine}`;+ if (remaining >= NAMED_CANON_MIN_CHARS) return `${spine}\n${canonLine.slice(0, remaining - 1).trimEnd()}…`;+ if (spine.length <= maxChars) return `${spine}\nNamed canon: [omitted to fit the judging budget]`;+ // The spine alone overruns: the premise is larger than this judge model's+ // world budget. Slicing is unavoidable here, but say so rather than letting+ // the judge score a silently amputated world.+ return `${spine.slice(0, maxChars)}\n\n[world summary truncated for judging]`;}// Build the judge's variable bag from the whole foundation. Content is budgeted@@ -547,20 +572,17 @@ function renderWorldFoundation(universe) {function buildFoundationContext({ series, universe, canon, issues = [], contentMax }) {const characters = Array.isArray(canon?.characters) ? canon.characters : [];const seriesCharacters = seriesFoundationCharacters(characters, series, issues);- const worldEntitiesSummary = renderWorldFoundation(universe);const characterRoster = seriesCharacters.length? seriesCharacters.map((character) => renderCharacterLine(character, { core: true })).join('\n'): '(no canon characters)';const sectionMax = Math.max(1_000, Math.floor(contentMax / 3));+ const world = renderWorldFoundation(universe, { maxChars: sectionMax });// Character quality lives in the choices between start and end, not merely// the endpoints. Reuse the canonical authored-arc renderer here so the judge// sees decisions, relapses, sacrifices, and their issue placement. The// repair prompt keeps the legacy compact summary because it already receives// the full `series.characterArcs` JSON separately.const arcText = renderArc(series, issues, { includeArcTransitions: true });- const world = worldEntitiesSummary.length > sectionMax- ? `${worldEntitiesSummary.slice(0, sectionMax)}\n\n[world summary truncated for judging]`- : worldEntitiesSummary;const roster = characterRoster.length > sectionMax? `${characterRoster.slice(0, sectionMax)}\n\n[character roster truncated for judging]`: characterRoster;@@ -1169,7 +1191,17 @@ async function refineWorld(universeId, { providerId, model, effort, finding = {}});// `wrote === false` means every refinable field is locked — report it so the// gate pauses 'inapplicable' for human review instead of silently no-op-ing.- return wrote ? { applied: true } : { applied: false, reason: 'every refinable world field is locked' };+ if (!wrote) return { applied: false, reason: 'every refinable world field is locked' };+ // A repair that landed against a field already at its storage ceiling had to+ // consolidate existing prose to make room. Say so on the fix frame: when the+ // gate later pauses on non-convergence, "the premise is full" is the fact that+ // tells a human to prune the bible rather than re-run the same repair.+ const saturated = Object.entries(narrativeRepairTargets(universe))+ .filter(([, budget]) => budget.saturated)+ .map(([field]) => field);+ return saturated.length+ ? { applied: true, reason: `world bible ${saturated.join(' and ')} sat at the storage ceiling; the repair had to consolidate existing canon to fit` }+ : { applied: true };}/**@@ -1251,6 +1283,7 @@ export const __testing = {isFoundationStale,buildFoundationContext,renderArc,+ renderWorldFoundation,renderCharacterLine,REPAIR_OUTLINE_MAX_CHARS,CHARACTER_FOUNDATION_BATCH_SIZE,diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex 53b5356900..123765a3b4 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -16,14 +16,23 @@ vi.mock('../../lib/stageRunner.js', () => ({}));vi.mock('../promptService.js', () => ({ getStage: vi.fn(() => ({ name: 'writer' })) }));-vi.mock('../universeBuilder.js', () => ({+// Storage is stubbed; the record-shape layer is real. `universeBuilder/sanitize.js`+// is the pure constants+sanitizers half of the barrel (no storage, no peer-sync),+// so pulling it in keeps the real LOGLINE_MAX/PREMISE_MAX/STYLE_NOTES_MAX the+// narrative write budget is derived from instead of a mock copy that can drift.+vi.mock('../universeBuilder.js', async () => ({+ ...(await import('../universeBuilder/sanitize.js')),getUniverse: vi.fn(async () => null),updateUniverse: vi.fn(async (id, patch) => ({ id, ...patch })),}));vi.mock('../universeCharacterExpand.js', async (importActual) => ({...(await importActual()),}));-vi.mock('../universeBuilderExpand.js', () => ({+// Only the LLM round-trip is mocked. `narrativeRepairTargets` is pure write-budget+// math the world repair reports saturation from — re-implementing it in the mock+// would make these tests agree with a copy instead of the real contract.+vi.mock('../universeBuilderExpand.js', async (importActual) => ({+ ...(await importActual()),expandWorldTemplate: vi.fn(async () => ({ logline: 'L2', premise: 'P2', styleNotes: 'S2', influences: null })),}));vi.mock('./series.js', async (importActual) => ({@@ -456,6 +465,51 @@ describe('foundation judge context — complete planning altitude', () => {});});+describe('renderWorldFoundation — budget spends the noun inventory, not the rules', () => {+ const rulesTail = 'RESONANCE RULESET: range 40m, cost one week of hearing, fails in wet air, cannot cross bone.';+ const worldWithRules = (entityCount) => ({+ logline: 'A colony sings its machines awake.',+ premise: `${'Established lore paragraph. '.repeat(200)}${rulesTail}`,+ styleNotes: 'Humid, tactile, close third person.',+ places: Array.from({ length: entityCount }, (_, index) => ({+ id: `plc-${index}`,+ name: `Place ${index}`,+ description: `A named location the judge already has plenty of. ${'detail '.repeat(20)}`,+ })),+ });++ it('keeps the premise tail — where a freshly authored ruleset lands — and drops canon nouns instead', () => {+ const world = worldWithRules(60);+ const unbounded = __testing.renderWorldFoundation(world);+ expect(unbounded).toContain('Named canon:');+ expect(unbounded).toContain(rulesTail);++ const budgeted = __testing.renderWorldFoundation(world, { maxChars: 6_500 });+ expect(budgeted.length).toBeLessThanOrEqual(6_500 + 60);+ // The repair the judge asked for survives the budget…+ expect(budgeted).toContain(rulesTail);+ // …and the entity inventory is what paid for it.+ expect(budgeted).not.toContain('Place 59');+ });++ it('omits the canon line outright rather than rendering a useless stub', () => {+ const out = __testing.renderWorldFoundation(worldWithRules(60), { maxChars: 5_900 });+ expect(out).toContain('Named canon: [omitted to fit the judging budget]');+ expect(out).toContain(rulesTail);+ });++ it('still marks a truncation when the narrative spine alone overruns the budget', () => {+ const out = __testing.renderWorldFoundation(worldWithRules(2), { maxChars: 1_000 });+ expect(out.length).toBeLessThanOrEqual(1_000 + 40);+ expect(out).toContain('[world summary truncated for judging]');+ });++ it('reports a missing universe unchanged', () => {+ expect(__testing.renderWorldFoundation(null, { maxChars: 10 }))+ .toBe('(no linked universe — worldbuilding cannot be judged from canon)');+ });+});+describe('judgeFoundation — cache / fast-pass', () => {it('returns the cached snapshot without an LLM call when the inputs hash matches', async () => {const series = { id: 'ser-1', name: 'S', universeId: null };diff --git a/server/services/universeBuilderExpand.effort.test.js b/server/services/universeBuilderExpand.effort.test.jsindex d58705c8a1..2687a814df 100644--- a/server/services/universeBuilderExpand.effort.test.js+++ b/server/services/universeBuilderExpand.effort.test.js@@ -11,7 +11,7 @@ vi.mock('../lib/promptRunner.js', () => ({runPromptThroughProvider: (...args) => runPromptThroughProviderMock(...args),}));-const { expandWorldTemplate } = await import('./universeBuilderExpand.js');+const { expandWorldTemplate, narrativeRepairTargets } = await import('./universeBuilderExpand.js');const provider = { id: 'codex-tui', name: 'Codex TUI', type: 'tui' };@@ -187,3 +187,105 @@ describe('expandWorldTemplate reasoning effort', () => {expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('Return a complete replacement');});});++// A judge-directed repair ADDS material. Without a write budget below the hard+// cap, a bible field that earlier repairs filled to the ceiling makes the repair+// unsatisfiable: the model returns a same-size rewrite, it passes the cap check,+// the judge re-scores an unchanged world, and the autopilot foundation gate+// loops until it pauses on non-convergence.+describe('expandWorldTemplate narrative write budget — saturated bible fields', () => {+ const SATURATED_PREMISE = 'p'.repeat(19_995);++ it('leaves a field under the headroom mark on its full cap', () => {+ const targets = narrativeRepairTargets({ premise: 'p'.repeat(1_000) });+ expect(targets.premise).toMatchObject({ max: 20_000, target: 20_000, saturated: false });+ });++ it('budgets a saturated field below its cap so the repair has somewhere to land', () => {+ const targets = narrativeRepairTargets({ premise: SATURATED_PREMISE });+ expect(targets.premise).toMatchObject({ target: 17_000, saturated: true, priorLength: 19_995 });+ expect(targets.logline).toMatchObject({ target: 500, saturated: false });+ });++ it('tells the repair to consolidate rather than append when the premise is at the ceiling', async () => {+ runPromptThroughProviderMock.mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'p'.repeat(16_000),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-consolidated',+ });++ await expandWorldTemplate({+ starterPrompt: 'Example Universe',+ premise: SATURATED_PREMISE,+ foundationDirective: 'Add a resonance ruleset with inputs, range, costs, and hard impossibilities.',+ providerId: 'codex-tui',+ narrativeOnly: true,+ });++ const { prompt } = runPromptThroughProviderMock.mock.calls[0][0];+ expect(prompt).toContain('# Consolidation mandate — premise is at the storage ceiling');+ expect(prompt).toContain('max 17000 characters');+ expect(prompt).toContain('the established premise is already 19995 characters');+ expect(prompt).toContain('Never drop a causal rule, hard limit, cost, failure mode');+ // Fields with room keep their full cap and stay out of the mandate.+ expect(prompt).toContain('one sentence (max 500 characters)');+ });++ it('rejects a same-size rewrite that fits the cap but not the write budget', async () => {+ runPromptThroughProviderMock+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'q'.repeat(19_990),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-no-op-rewrite',+ })+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'q'.repeat(15_000),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-consolidated',+ });++ const result = await expandWorldTemplate({+ starterPrompt: 'Example Universe',+ premise: SATURATED_PREMISE,+ foundationDirective: 'Add a resonance ruleset.',+ providerId: 'codex-tui',+ narrativeOnly: true,+ });++ expect(runPromptThroughProviderMock).toHaveBeenCalledTimes(2);+ const retry = runPromptThroughProviderMock.mock.calls[1][0].prompt;+ expect(retry).toContain('premise exceeds 17000 characters (got 19990)');+ // The compression target shrinks from the WRITE budget, not the hard cap —+ // 90% of 20000 would hand back a draft that fails the same contract.+ expect(retry).toContain('premise: at most 15300 characters');+ expect(result.premise).toBe('q'.repeat(15_000));+ });++ it('names the saturated field when the repair cannot be made to fit', async () => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'r'.repeat(19_500),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-never-fits',+ });++ await expect(expandWorldTemplate({+ starterPrompt: 'Example Universe',+ premise: SATURATED_PREMISE,+ foundationDirective: 'Add a resonance ruleset.',+ providerId: 'codex-tui',+ narrativeOnly: true,+ })).rejects.toThrow(/The stored premise already fills its budget/);+ });+});diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex c3f6e4e8c2..094fa78483 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -43,6 +43,48 @@ const LABEL_MAX = 80;const NARRATIVE_REPAIR_MAX_ATTEMPTS = 3;const NARRATIVE_REPAIR_HEADROOM = [0.9, 0.8];+// A judge-directed narrative repair must ADD material — an operational ruleset,+// a missing cost, a named hard limit — to a bible field that EARLIER repairs may+// already have filled to its storage ceiling. Enforcing only the hard cap made+// that unsatisfiable: with a premise sitting at 19,995 of 20,000 characters+// there is no room for the rules the judge asked for, so the model returned a+// same-size rewrite, the field passed validation (it was under the cap), the+// foundation judge re-read an unchanged world, scored it identically, and the+// autopilot's foundation gate burned every round on a repair that could not+// physically land. Saturated fields therefore get a WRITE TARGET below the cap+// plus an explicit consolidate-then-extend mandate, and the storage contract is+// checked against that target — so the existing retry ladder forces the+// consolidation instead of accepting a no-op rewrite.+export const NARRATIVE_REPAIR_WRITE_HEADROOM = 0.85;++// The narrative-bible scalars a foundation repair persists, with their hard+// storage caps. Single source for the write budget, the prompt contract, and+// the violation check so the three can't drift.+const NARRATIVE_FIELD_CAPS = Object.freeze([+ ['logline', LOGLINE_MAX],+ ['premise', PREMISE_MAX],+ ['styleNotes', STYLE_NOTES_MAX],+]);++/**+ * Per-field write budget for a narrative repair, derived from what is ALREADY+ * stored. A field under the headroom mark may use its full cap (nothing to make+ * room for); a saturated one is asked to come back under the headroom target so+ * the repair has somewhere to go. Pure + unit-tested.+ *+ * @returns {Record<string, { max, target, priorLength, saturated }>}+ */+export function narrativeRepairTargets(prior = {}) {+ const targets = {};+ for (const [key, max] of NARRATIVE_FIELD_CAPS) {+ const priorLength = typeof prior?.[key] === 'string' ? prior[key].trim().length : 0;+ const headroomTarget = Math.floor(max * NARRATIVE_REPAIR_WRITE_HEADROOM);+ const saturated = priorLength > headroomTarget;+ targets[key] = { max, priorLength, saturated, target: saturated ? headroomTarget : max };+ }+ return targets;+}+// Bible/prompt fields the LLM sees as "current universe state" so re-expansion// stays consistent with prior refinements. Derived from LOCKABLE_FIELDS so a// new lockable field automatically reaches this prompt; excludes starterPrompt@@ -65,6 +107,7 @@ function buildExpansionPrompt({priorStyleNotes = '',locked = {},foundationDirective = '',+ writeTargets,}) {const embrace = Array.isArray(influences?.embrace)? influences.embrace.filter(Boolean)@@ -110,17 +153,38 @@ ${stateLines.join('\n\n')}\n`// unchanged, but give judge-directed repairs the narrow contract they can// actually apply.if (narrativeOnly) {+ // Name the budget the validator will actually enforce. A saturated field+ // also gets its current size, because "write at most N" is not actionable+ // when the model is simultaneously told to preserve an established value+ // that is already larger than N — it has to know consolidation is the job.+ const budgetLine = (key) => {+ const { target, saturated, priorLength } = writeTargets[key];+ return saturated+ ? `max ${target} characters — the established ${key} is already ${priorLength} characters, so the repair CANNOT be appended: consolidate the existing prose under that budget first, then add what the directive requires`+ : `max ${target} characters`;+ };+ const saturatedFields = NARRATIVE_FIELD_CAPS+ .map(([key]) => key)+ .filter((key) => writeTargets[key].saturated);+ const consolidationSection = saturatedFields.length+ ? `\n# Consolidation mandate — ${saturatedFields.join(', ')} ${saturatedFields.length === 1 ? 'is' : 'are'} at the storage ceiling+The repair does not fit alongside the current text, so making room is part of this task, not optional.+- Merge duplicated lore, collapse parallel examples into one precise sentence, and cut ornamental restatement and throat-clearing.+- Never drop a causal rule, hard limit, cost, failure mode, named entity, faction, or site-specific operation to save space — those are the load-bearing content. Cut the prose around them.+- Never truncate: no sentence, paragraph, rule, or list item may end unfinished.+- Silently count characters before answering. A response over budget is rejected in full.\n`+ : '';return `You are a senior speculative-fiction worldbuilder repairing the narrative bible for a comic/TV series. This is a focused continuity repair, not a visual-exploration or canon-invention pass.# Starter idea${starterPrompt}-${influencesSection}${currentStateSection}${foundationSection}+${influencesSection}${currentStateSection}${foundationSection}${consolidationSection}# Output contractReturn one JSON object with exactly these top-level keys and no others:-- logline: string, one sentence (max ${LOGLINE_MAX} characters).-- premise: string, 1-3 concise paragraphs (max ${PREMISE_MAX} characters) defining the setting, conflict, stakes, and every operational rule needed to satisfy the repair directive.-- styleNotes: string (max ${STYLE_NOTES_MAX} characters) preserving the established tonal and sensory identity while making any worldbuilding guidance concrete enough for writers to apply.+- logline: string, one sentence (${budgetLine('logline')}).+- premise: string, concise paragraphs (${budgetLine('premise')}) defining the setting, conflict, stakes, and every operational rule needed to satisfy the repair directive.+- styleNotes: string (${budgetLine('styleNotes')}) preserving the established tonal and sensory identity while making any worldbuilding guidance concrete enough for writers to apply.# Repair rules- Resolve the judge's exact contradiction or omission. Do not answer it with extra lore that leaves the named causal problem intact.@@ -263,14 +327,11 @@ const extractJson = (raw) => {);};-const narrativeRepairViolations = (parsed) => [- ['logline', LOGLINE_MAX],- ['premise', PREMISE_MAX],- ['styleNotes', STYLE_NOTES_MAX],-].flatMap(([key, max]) => {+const narrativeRepairViolations = (parsed, writeTargets) => NARRATIVE_FIELD_CAPS.flatMap(([key]) => {+ const { target } = writeTargets[key];const value = typeof parsed?.[key] === 'string' ? parsed[key].trim() : '';if (!value) return [`${key} is missing`];- return value.length > max ? [`${key} exceeds ${max} characters (got ${value.length})`] : [];+ return value.length > target ? [`${key} exceeds ${target} characters (got ${value.length})`] : [];});const hasCompleteNarrativeCandidate = (candidate) => (@@ -279,17 +340,21 @@ const hasCompleteNarrativeCandidate = (candidate) => ()));-function buildNarrativeCompressionPrompt({ candidate, violations, compressionAttempt }) {+function buildNarrativeCompressionPrompt({+ candidate, violations, compressionAttempt, writeTargets,+}) {const headroom = NARRATIVE_REPAIR_HEADROOM[Math.min(compressionAttempt - 1,NARRATIVE_REPAIR_HEADROOM.length - 1,)];- const targets = {- logline: Math.floor(LOGLINE_MAX * headroom),- premise: Math.floor(PREMISE_MAX * headroom),- styleNotes: Math.floor(STYLE_NOTES_MAX * headroom),- };- const source = Object.fromEntries(['logline', 'premise', 'styleNotes'].map((key) => [+ // Shrink from the effective WRITE target, not the hard cap — a saturated field+ // is already budgeted below its cap, and compressing to 90% of the cap would+ // hand back a draft that violates the same contract it just failed.+ const targets = Object.fromEntries(NARRATIVE_FIELD_CAPS.map(([key]) => [+ key,+ Math.floor(writeTargets[key].target * headroom),+ ]));+ const source = Object.fromEntries(NARRATIVE_FIELD_CAPS.map(([key]) => [key,typeof candidate?.[key] === 'string' ? candidate[key].trim() : '',]));@@ -455,6 +520,12 @@ export async function expandWorldTemplate({const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: "No AI provider available for universe expansion" });+ // Derived from what is ALREADY stored, once, before the retry loop: the write+ // budget must not drift between the prompt that asks for the repair and the+ // contract that validates it.+ const writeTargets = narrativeRepairTargets({+ logline: priorLogline, premise: priorPremise, styleNotes: priorStyleNotes,+ });const fullPrompt = buildExpansionPrompt({starterPrompt: starterPrompt.trim(),influences: safeInfluences,@@ -466,6 +537,7 @@ export async function expandWorldTemplate({locked,foundationDirective,narrativeOnly,+ writeTargets,});const totalIn = safeInfluences.embrace.length + safeInfluences.avoid.length;const preservedVarCount = Object.values(preservedVariations || {}).reduce(@@ -500,6 +572,7 @@ export async function expandWorldTemplate({candidate: parsed,violations: narrativeViolations,compressionAttempt: attempt,+ writeTargets,}): `${fullPrompt}\n\n# Storage-contract retry\nThe previous response was incomplete: ${narrativeViolations.join('; ')}. Return a complete replacement with every required field; do not omit or leave any field blank.`: fullPrompt;@@ -523,7 +596,7 @@ export async function expandWorldTemplate({`🌍 Universe Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,);if (!narrativeOnly) break;- narrativeViolations = narrativeRepairViolations(parsed);+ narrativeViolations = narrativeRepairViolations(parsed, writeTargets);if (narrativeViolations.length === 0) break;if (attempt + 1 < maxAttempts) {const retryMode = hasCompleteNarrativeCandidate(parsed)@@ -533,8 +606,17 @@ export async function expandWorldTemplate({}}if (narrativeViolations.length > 0) {+ // Name the saturated fields in the message: when a repair can't fit, the+ // actionable next step for a human is "consolidate the bible", which is not+ // obvious from a bare character count.+ const saturated = NARRATIVE_FIELD_CAPS+ .map(([key]) => key)+ .filter((key) => writeTargets[key].saturated);+ const saturationNote = saturated.length+ ? ` The stored ${saturated.join(' and ')} already fills its budget, so the repair has no room — consolidate the world bible and retry.`+ : '';throw new ServerError(- `Universe Builder narrative repair failed its storage contract after ${NARRATIVE_REPAIR_MAX_ATTEMPTS} attempts: ${narrativeViolations.join('; ')}`,+ `Universe Builder narrative repair failed its storage contract after ${NARRATIVE_REPAIR_MAX_ATTEMPTS} attempts: ${narrativeViolations.join('; ')}.${saturationNote}`,{ status: 502, code: 'LLM_OUTPUT_CONTRACT' },);}