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
fix: budget every section of the character-foundation repair prompt (#3726)
[._.]/ Adam Eivy813452b2ba70
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fae70435c2..0c24fe8984 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -233,3 +233,5 @@- **A CoS agent that correctly concludes "nothing to fix here" is no longer failed for not opening a pull request.** The PR-claim check asks the forge whether a run that promised a change request produced one, and recorded a bare "no" as `pr-missing`. But "no PR" only means the agent slipped if there was something to open one *for*: an agent that investigates its task, finds the reported defect already fixed on `main`, and stops without touching a file leaves a branch with zero commits — and `gh pr create` refuses that branch because there is no diff, not because anyone made a mistake. Since `pr-missing` is deliberately non-actionable so a genuine miss can retry, a correct no-op conclusion was instead re-run to the full retry budget, spending three agents to reach the same answer three times and then escalating it to a human as a failure. A missing PR on a branch that holds **no commits** is now recorded as the completion it is, logged so the run stays visible rather than passing silently, while a missing PR on a branch that holds real commits still fails exactly as before. The commit count is taken against `origin/<default>` rather than the worktree's local copy, which routinely sits behind the commit the worktree branched from and would otherwise report inherited merge commits as the agent's own work; an unreadable count is treated as unknown and leaves the failure standing, since not being able to look is not evidence of an empty branch. The advice attached to a real miss also no longer asserts the branch "is pushed" — that was never checked — and now names how many commits are waiting.- **[issue-3744] A worktree agent is no longer failed for a commit that merged upstream under a rebased sha.** The primary-checkout branch-jack guard cleared benign movement by asking whether the primary carried commits its upstream lacked — but it asked that **by sha**, while the attribution step beside it asked **by patch-id**. PortOS rebase-merges PRs, so a merged commit carries a different sha upstream than the copy a local `git merge --ff-only` puts on the primary; the sha comparison read that copy as unpushed and treated it as stranded, and attribution then matched it against the agent's branch — where it existed only because `/do:pr` had rebased onto that same upstream commit — and called that proof of authorship. The observed run had already opened *and merged* its PR, yet was failed with `primary-checkout-mutated`, escalated to a human, and told to consider `reset --hard` over a commit whose content was fully pushed. The upstream exclusion is now patch-id-precise like the attribution beside it, so a rebase-merged copy clears the checkout exactly as a zero sha count does; a genuinely unpushed commit with no upstream twin is still reported, and the original branch-jack shape is still caught. The failure prose also stopped quoting a commit count derived from a baseline that no longer exists: a mid-run `git pull --rebase` on the primary rewrites the sha stamped at spawn, which made `rev-list ^baseline` span the whole fork point and report "16 new commits" for a run that moved the primary by one and stranded none — that case now says the baseline was rewritten instead of passing the number off as movement.++- **[issue-3726] The character-foundation repair stage no longer builds a prompt too large to answer.** A real autonomous run assembled a 72,404-char prompt for `pipeline-character-foundation` and burned the CLI runner's full 5-minute wall clock without emitting a single byte, failing the whole run. The stage already had a budget — `REPAIR_OUTLINE_MAX_CHARS`, added after a 35KB prompt hung both a primary and a fallback TUI provider — but it bound only one of the prompt's three large sections, and not the largest: 35KB of raw series seed and 15KB of candidate cast rode along unbudgeted, while the outline itself overran its own soft cap by 49% because `renderArc`'s volume spine and character-arc tail were unconditional and could exceed `maxChars` outright. Each section now carries a 12,000-char budget and degrades in priority order rather than being sliced mid-sentence: the series seed sheds its style-guide exemplars (craft material a character repair cannot use) before flattening authored arcs to their want/need spine; the cast payload compacts the full-ensemble roster to a name/role/want/need line and drops members before it touches the batch actually under repair; and `renderArc` drops whole episode lines, then per-volume synopses (keeping `V# title: logline`), and finally clamps — so `maxChars` is a hard bound for any volume/episode/arc shape, pinned by a property test. Every tier names what it left out so the model can tell a short plan from a budgeted one, and the JSON sections stay parseable at every tier. The stage also now requests an explicit 10-minute timeout, matching what TUI providers already default to: the runner's 300s default is what actually killed the run.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 2080b52d10..6de6079034 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -451,18 +451,39 @@ function repairableSeriesFoundationCharacters(characters, series, issues = []) {const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);+const pluralLines = (count) => (count === 1 ? 'line' : 'lines');++// Last-resort clamp for `renderArc`. Every tier above it drops WHOLE lines so the+// render stays coherent, but a budget smaller than the arc header itself (or a+// series with more volume loglines than the budget has room for) can still+// overrun — and `maxChars` is a hard contract, not a target. Slice, and keep the+// marker only when there is room for it.+const ARC_TRUNCATION_NOTE = '\n[series plan truncated to fit the prompt budget]';+function clampArcToBudget(text, maxChars) {+ if (!Number.isFinite(maxChars) || text.length <= maxChars) return text;+ if (maxChars <= ARC_TRUNCATION_NOTE.length) return text.slice(0, Math.max(0, maxChars));+ return `${text.slice(0, maxChars - ARC_TRUNCATION_NOTE.length)}${ARC_TRUNCATION_NOTE}`;+}+/*** Render the synopsis-level series plan: arc header, per-volume loglines and* synopses, the episode list under each volume, and the authored character arcs.*- * `maxChars` bounds the result. The per-episode synopsis list is the ONLY part- * that grows without bound — a series gains episodes forever, and everything- * else is fixed by the volume count — so the budget is spent by dropping WHOLE- * episode lines from the end, keeping the plan spine (arc, volumes, authored- * character arcs) intact and naming how many were left out. That degrades to a- * coherent outline the model can still reason over, unlike slicing the rendered- * text mid-sentence. Earliest episodes survive a tight budget because that's- * where a character arc's opening transitions hang.+ * `maxChars` is a HARD bound on the result, spent in tiers so the render always+ * degrades to something coherent rather than being sliced mid-sentence:+ *+ * 1. Drop WHOLE episode synopsis lines from the end. Earliest episodes survive+ * a tight budget because that's where a character arc's opening transitions+ * hang.+ * 2. If the spine alone (arc header + every volume's logline/synopsis/hook ++ * the authored character arcs) still overruns, drop the per-volume synopsis+ * and ending-hook lines, keeping `V# title: logline` so the volume order and+ * shape survive. Every episode goes with them.+ * 3. Slice, as a floor, when even the loglines cannot fit — a caller that set a+ * budget gets a smaller string, never a longer one.+ *+ * Each tier names what it left out, so the model can tell a short plan from a+ * budgeted one.** Unbudgeted (the default) the output is byte-identical to the pre-budget* render, so the foundation judge's own section-level truncation is unchanged.@@ -483,15 +504,13 @@ function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransit`Volumes (${seasons.length}):`,];const volumes = seasons.map((season) => {- const spine = [- ` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`,- ` Synopsis: ${season.synopsis || '(none)'}`,- ];- if (season.endingHook) spine.push(` Ending hook: ${season.endingHook}`);+ const logline = ` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`;+ const detail = [` Synopsis: ${season.synopsis || '(none)'}`];+ if (season.endingHook) detail.push(` Ending hook: ${season.endingHook}`);const episodes = orderedIssues.filter((issue) => issue?.seasonId === season.id).map((issue) => ` #${issue.number ?? '?'} ${issue.title || 'Untitled'}: ${issue?.stages?.idea?.input || '(no synopsis)'}`);- return { spine, episodes };+ return { logline, detail, episodes };});const characterArcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];const tail = ['', `Authored character arcs (${characterArcs.length}):`];@@ -503,15 +522,26 @@ function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransit}}- // The spine is unconditional; episodes fill whatever is left. `remaining` goes- // negative when the spine alone overruns the budget, which drops every episode- // rather than throwing — a caller that set a budget wants a smaller prompt, not- // a failed render.- let remaining = maxChars - joinedLength([...head, ...volumes.flatMap((v) => v.spine), ...tail]);+ // Tier 1: the full spine is unconditional; episodes fill whatever is left.+ const fullSpine = [...head, ...volumes.flatMap((volume) => [volume.logline, ...volume.detail]), ...tail];+ let remaining = maxChars - joinedLength(fullSpine);+ const notes = [];+ // Tier 2: the spine alone overruns, so the per-volume synopsis/hook lines go+ // and every episode goes with them — dropping craft detail to make room for+ // episode lines would invert the priority the tiers exist to express.+ const withDetail = remaining >= 0;+ if (!withDetail) {+ const droppedDetail = volumes.reduce((total, volume) => total + volume.detail.length, 0);+ if (droppedDetail > 0) {+ notes.push(` [${droppedDetail} volume synopsis ${pluralLines(droppedDetail)} omitted to fit the prompt budget]`);+ }+ remaining = -1;+ }let omitted = 0;const lines = [...head];for (const volume of volumes) {- lines.push(...volume.spine);+ lines.push(volume.logline);+ if (withDetail) lines.push(...volume.detail);for (const episode of volume.episodes) {if (episode.length + 1 <= remaining) {lines.push(episode);@@ -521,9 +551,9 @@ function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransit}}}- if (omitted > 0) lines.push(` [${omitted} later episode synopsis line${omitted === 1 ? '' : 's'} omitted to fit the prompt budget]`);- lines.push(...tail);- return lines.join('\n');+ if (omitted > 0) lines.push(` [${omitted} later episode synopsis ${pluralLines(omitted)} omitted to fit the prompt budget]`);+ lines.push(...notes, ...tail);+ return clampArcToBudget(lines.join('\n'), maxChars);}// Below this the named-canon line carries no usable signal — render the@@ -789,8 +819,172 @@ const CHARACTER_FOUNDATION_BATCH_SIZE = 6;// material a reasoning model will chew through before the wall clock runs out,// not how much its context can hold.const REPAIR_OUTLINE_MAX_CHARS = 12_000;++// The outline cap above only ever bound ONE of the repair prompt's three large+// sections. A real character-foundation run built a 72KB prompt — 35KB of raw+// series seed, 18KB of outline, 15KB of candidate cast — and burned a CLI+// runner's full wall clock without emitting a byte. Each section now carries its+// own budget so the total lands near 40K chars, which the stage demonstrably+// completes within. Same reasoning as the outline cap: fixed rather than+// window-derived, because the binding constraint is how much material a+// reasoning model chews through before the clock runs out, not context size.+const REPAIR_SERIES_MAX_CHARS = 12_000;+const REPAIR_CHARACTERS_MAX_CHARS = 12_000;++// The character-foundation stage reasons over the whole ensemble at once, so it+// is the slowest repair stage by a wide margin. The runner's 300s default is+// what actually killed the 72KB run; TUI providers already default to 10+// minutes (`providers.js`), and this gives a CLI provider the same headroom.+const CHARACTER_FOUNDATION_TIMEOUT_MS = 600_000;+const CRAFT_REPAIR_MAX_ATTEMPTS = 2;+// A repair prompt's JSON sections shed the least load-bearing material first,+// then trim the free-text fields that remain, so the payload stays VALID JSON at+// every tier — a mid-object slice would hand the model a parse error instead of+// a smaller brief.+const JSON_TRUNCATION_MARK = '… [truncated to fit the prompt budget]';+function fitJsonToBudget(payload, trimKeys, maxChars) {+ const shrunk = { ...payload };+ let rendered = JSON.stringify(shrunk, null, 2);+ while (rendered.length > maxChars) {+ const key = trimKeys+ .filter((candidate) => typeof shrunk[candidate] === 'string' && shrunk[candidate].length > 0)+ .sort((a, b) => shrunk[b].length - shrunk[a].length)[0];+ // Nothing left that is safe to trim (structural ids/counts only) — return the+ // smallest valid JSON we can build rather than corrupting it with a slice.+ if (!key) return rendered;+ const keep = Math.max(0, shrunk[key].length - Math.max(rendered.length - maxChars, 1) - JSON_TRUNCATION_MARK.length);+ shrunk[key] = keep > 0 ? `${shrunk[key].slice(0, keep)}${JSON_TRUNCATION_MARK}` : '';+ rendered = JSON.stringify(shrunk, null, 2);+ }+ return rendered;+}++// Drop the style guide's exemplars first — they are craft-dimension material and+// tell a character or world repair nothing — then flatten the authored character+// arcs to their want/need spine, which the outline section already renders in+// full. `premise` / `targetFormat` / `issueCountTarget` / `styleNotes` are the+// brief itself and stay unconditional.+function renderRepairSeriesJson(series, maxChars = REPAIR_SERIES_MAX_CHARS) {+ const base = {+ id: series?.id,+ name: series?.name,+ premise: series?.premise,+ targetFormat: series?.targetFormat,+ issueCountTarget: series?.issueCountTarget,+ styleNotes: series?.styleNotes,+ };+ const arcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];+ const trimKeys = ['styleNotes', 'premise'];+ const tiers = [+ { ...base, styleGuide: series?.styleGuide, characterArcs: series?.characterArcs },+ {+ ...base,+ characterArcs: series?.characterArcs,+ omitted: 'styleGuide (craft exemplars) omitted to fit the prompt budget',+ },+ {+ ...base,+ characterArcs: arcs.map((arc) => ({+ characterId: arc?.characterId,+ characterName: arc?.characterName,+ want: arc?.want,+ need: arc?.need,+ })),+ omitted: 'styleGuide and character-arc detail omitted to fit the prompt budget; see the outline section',+ },+ ];+ for (const tier of tiers) {+ const rendered = JSON.stringify(tier, null, 2);+ if (rendered.length <= maxChars) return rendered;+ }+ return fitJsonToBudget(tiers.at(-1), trimKeys, maxChars);+}++// The full-ensemble roster is the unbounded half of the character payload:+// `CHARACTER_FOUNDATION_BATCH_SIZE` bounds `targetCharacters`, but+// `fullSeriesRoster` carries every cast member with every framework field, so it+// grows with the series. Compact the roster to the differentiation spine before+// dropping members — the roster exists so the batch can differentiate and keep+// relationships straight, which a name/role/want/need line still supports.+const compactRosterCharacter = (character) => ({+ id: character?.id,+ name: character?.name,+ role: character?.role,+ want: character?.want || '',+ need: character?.need || '',+});++// `CHARACTER_FOUNDATION_BATCH_SIZE` bounds how MANY characters a batch carries,+// not how large each one is — six characters with long personality/background/+// relationship prose still run to tens of KB. So the last tier caps every string+// field on the batch itself, halving the cap until the payload fits.+const CHARACTER_FIELD_CAP_START = 1_200;+const CHARACTER_FIELD_CAP_FLOOR = 40;+const truncateField = (value, cap) => (+ typeof value === 'string' && value.length > cap+ ? `${value.slice(0, Math.max(0, cap - JSON_TRUNCATION_MARK.length))}${JSON_TRUNCATION_MARK}`+ : value+);+const capCharacterFields = (character, cap) => Object.fromEntries(+ Object.entries(character || {}).map(([key, value]) => [+ key,+ Array.isArray(value) ? value.map((entry) => truncateField(entry, cap)) : truncateField(value, cap),+ ]),+);++function renderRepairCharactersJson(payload, maxChars = REPAIR_CHARACTERS_MAX_CHARS) {+ const render = (value) => JSON.stringify(value, null, 2);+ const full = render(payload);+ if (full.length <= maxChars) return full;++ // The flat array shape (non-character dimensions) is ALL batch — there is no+ // roster to shed — so it trims field text rather than dropping fields, and only+ // falls back to the compact spine when even the tightest cap does not fit.+ if (Array.isArray(payload)) {+ let rendered = full;+ for (let cap = CHARACTER_FIELD_CAP_START; cap >= CHARACTER_FIELD_CAP_FLOOR; cap = Math.floor(cap / 2)) {+ rendered = render(payload.map((character) => capCharacterFields(character, cap)));+ if (rendered.length <= maxChars) return rendered;+ }+ const compact = render(payload.map(compactRosterCharacter));+ return compact.length <= maxChars ? compact : rendered;+ }++ const targets = Array.isArray(payload?.targetCharacters) ? payload.targetCharacters : [];+ const roster = Array.isArray(payload?.fullSeriesRoster) ? payload.fullSeriesRoster : [];+ const compactRoster = roster.map(compactRosterCharacter);+ const rosterNote = (kept) => (kept === compactRoster.length+ ? 'Roster compacted to name/role/want/need to fit the prompt budget.'+ : `Roster compacted and limited to ${kept} of ${compactRoster.length} members to fit the prompt budget.`);+ const build = (kept, cap) => render({+ targetCharacters: cap ? targets.map((character) => capCharacterFields(character, cap)) : targets,+ fullSeriesRoster: compactRoster.slice(0, kept),+ rosterNote: rosterNote(kept),+ ...(cap ? { targetNote: `Character fields over ${cap} characters were truncated to fit the prompt budget.` } : {}),+ });++ // At a given field cap, keep as many roster members as fit. The batch under+ // repair outranks the roster, so the cap only tightens once even an empty+ // roster cannot make room.+ const bestFit = (cap) => {+ let kept = compactRoster.length;+ let rendered = build(kept, cap);+ while (kept > 0 && rendered.length > maxChars) {+ kept -= 1;+ rendered = build(kept, cap);+ }+ return rendered;+ };++ let rendered = bestFit(null);+ for (let cap = CHARACTER_FIELD_CAP_START; rendered.length > maxChars && cap >= CHARACTER_FIELD_CAP_FLOOR; cap = Math.floor(cap / 2)) {+ rendered = bestFit(cap);+ }+ return rendered;+}+function craftRepairViolations(proposal) {const guide = proposal?.styleGuide;if (!guide || typeof guide !== 'object') return ['styleGuide is missing'];@@ -859,24 +1053,16 @@ async function runFoundationRepair(series, issues, dimension, finding, characterdimension,phase: options.phase || (dimension === 'character' ? 'post-arc reconciliation' : 'foundation repair'),foundationFindingJson: JSON.stringify(findingPayload, null, 2),- seriesJson: JSON.stringify({- id: series.id,- name: series.name,- premise: series.premise,- targetFormat: series.targetFormat,- issueCountTarget: series.issueCountTarget,- styleNotes: series.styleNotes,- styleGuide: series.styleGuide,- characterArcs: series.characterArcs,- }, null, 2),+ seriesJson: renderRepairSeriesJson(series),outline: renderArc(series, issues, { maxChars: REPAIR_OUTLINE_MAX_CHARS }),- charactersJson: JSON.stringify(charactersPayload, null, 2),+ charactersJson: renderRepairCharactersJson(charactersPayload),}, {returnsJson: true,providerDefault: options.providerId,modelDefault: options.model,effortDefault: options.effort,source: stage,+ ...(stage === CHARACTER_FOUNDATION_STAGE ? { timeoutOverride: CHARACTER_FOUNDATION_TIMEOUT_MS } : {}),});const proposal = result?.content && typeof result.content === 'object' ? result.content : {};if (dimension !== 'craft') return proposal;@@ -1285,7 +1471,12 @@ export const __testing = {renderArc,renderWorldFoundation,renderCharacterLine,+ renderRepairSeriesJson,+ renderRepairCharactersJson,REPAIR_OUTLINE_MAX_CHARS,+ REPAIR_SERIES_MAX_CHARS,+ REPAIR_CHARACTERS_MAX_CHARS,+ CHARACTER_FOUNDATION_TIMEOUT_MS,CHARACTER_FOUNDATION_BATCH_SIZE,FRAMEWORK_STRING_FIELDS,};diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex 123765a3b4..22d5a8286e 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -356,17 +356,179 @@ describe('renderArc — episode-list budget', () => {}});- it('drops every episode rather than throwing when the spine alone overruns the budget', () => {- const out = __testing.renderArc(bigSeries, manyIssues, { maxChars: 10 });+ it('drops volume synopses, keeping the loglines, when the spine alone overruns the budget', () => {+ // 30 volumes of long synopses: the spine overruns on its own, so tier 2 fires.+ const wideSeries = {+ ...bigSeries,+ seasons: Array.from({ length: 30 }, (_, i) => ({+ id: `sea-${i + 1}`, number: i + 1, title: `V${i + 1}`, logline: 'VL',+ synopsis: 'z'.repeat(300), endingHook: 'EH',+ })),+ };+ const out = __testing.renderArc(wideSeries, manyIssues, { maxChars: 4_000 });+ expect(out.length).toBeLessThanOrEqual(4_000);expect(out).toContain('Logline: AL');+ expect(out).toContain(' V1 V1: VL');+ expect(out).not.toContain(' Synopsis: ');expect(out).not.toContain('#1 Ep 1:');- expect(out).toContain('[40 later episode synopsis lines omitted to fit the prompt budget]');+ expect(out).toContain('[60 volume synopsis lines omitted to fit the prompt budget]');+ });++ it('never exceeds the budget even when the volume loglines alone do not fit', () => {+ const out = __testing.renderArc(bigSeries, manyIssues, { maxChars: 120 });+ expect(out.length).toBeLessThanOrEqual(120);+ expect(out).toContain('Logline: AL');+ expect(out).toContain('[series plan truncated to fit the prompt budget]');});it('keeps the singular form when exactly one episode is dropped', () => {const oneOver = __testing.renderArc(bigSeries, manyIssues.slice(0, 2), { maxChars: 800 });expect(oneOver).toContain('[1 later episode synopsis line omitted to fit the prompt budget]');});++ // Property test: the budget is a hard contract, so sweep the shape of the+ // series (volume count × episode count × arc count) against a sweep of budgets+ // rather than asserting a handful of hand-picked cases. Budgets deliberately+ // include values below the length of the fixed arc header and below the+ // truncation marker itself, which are the inputs the tiered degradation cannot+ // satisfy by dropping lines.+ it('never returns more than maxChars for any volume/episode/arc shape', () => {+ const budgets = [0, 1, 20, 47, 60, 120, 400, 1_000, 4_000, 12_000];+ for (const volumeCount of [0, 1, 3, 12, 40]) {+ for (const episodesPerVolume of [0, 1, 5, 20]) {+ for (const arcCount of [0, 2, 25]) {+ const seasons = Array.from({ length: volumeCount }, (_, i) => ({+ id: `sea-${i + 1}`, number: i + 1, title: `Volume ${i + 1}`,+ logline: 'l'.repeat(80), synopsis: 's'.repeat(250), endingHook: 'h'.repeat(60),+ }));+ const series = {+ arc: { logline: 'a'.repeat(90), summary: 'b'.repeat(200), themes: ['t1', 't2'], protagonistArc: 'p'.repeat(80), shape: 'rise' },+ seasons,+ characterArcs: Array.from({ length: arcCount }, (_, i) => ({+ characterId: `chr-${i}`, characterName: `Cast ${i}`,+ startState: 'x'.repeat(40), endState: 'y'.repeat(40), want: 'w'.repeat(40), need: 'n'.repeat(40),+ })),+ };+ const issues = seasons.flatMap((season, s) => Array.from({ length: episodesPerVolume }, (_, e) => ({+ number: s * episodesPerVolume + e + 1,+ seasonId: season.id,+ title: `Ep ${e + 1}`,+ stages: { idea: { input: 'e'.repeat(300) } },+ })));+ for (const maxChars of budgets) {+ const out = __testing.renderArc(series, issues, { maxChars });+ expect(+ out.length,+ `volumes=${volumeCount} episodes=${episodesPerVolume} arcs=${arcCount} maxChars=${maxChars}`,+ ).toBeLessThanOrEqual(maxChars);+ }+ // Unbudgeted renders stay complete — the tiers must not leak into the default.+ const full = __testing.renderArc(series, issues);+ expect(full).not.toContain('to fit the prompt budget');+ }+ }+ }+ });+});++describe('foundation repair prompt — bounded series seed and cast', () => {+ const bigSeries = () => ({+ id: 'ser-1',+ name: 'Example Series',+ premise: 'p'.repeat(2_000),+ targetFormat: 'novella',+ issueCountTarget: 24,+ styleNotes: 'n'.repeat(1_500),+ styleGuide: {+ voiceExemplars: Array.from({ length: 6 }, (_, i) => ({ passage: 'g'.repeat(1_200), note: `note ${i}` })),+ voiceAntiExemplars: Array.from({ length: 6 }, (_, i) => ({ passage: 'x'.repeat(1_200), note: `anti ${i}` })),+ },+ characterArcs: Array.from({ length: 18 }, (_, i) => ({+ characterId: `chr-${i}`, characterName: `Cast ${i}`,+ want: 'w'.repeat(60), need: 'n'.repeat(60),+ startState: 's'.repeat(400), endState: 'e'.repeat(400),+ transitions: Array.from({ length: 6 }, (_, t) => ({ kind: 'decision', atIssue: t, label: 'l'.repeat(120) })),+ })),+ });++ it('drops style-guide exemplars first, then character-arc detail, to fit the series budget', () => {+ const rendered = __testing.renderRepairSeriesJson(bigSeries());+ expect(rendered.length).toBeLessThanOrEqual(__testing.REPAIR_SERIES_MAX_CHARS);+ expect(() => JSON.parse(rendered)).not.toThrow();+ const parsed = JSON.parse(rendered);+ // The brief itself is unconditional.+ expect(parsed.premise).toBe('p'.repeat(2_000));+ expect(parsed.styleNotes).toBe('n'.repeat(1_500));+ expect(parsed.targetFormat).toBe('novella');+ expect(parsed.issueCountTarget).toBe(24);+ expect(parsed.styleGuide).toBeUndefined();+ // Arcs survive as the want/need spine; the transition beats do not.+ expect(parsed.characterArcs).toHaveLength(18);+ expect(parsed.characterArcs[0].transitions).toBeUndefined();+ expect(parsed.omitted).toMatch(/omitted to fit the prompt budget/);+ });++ it('leaves a small series seed byte-identical to the unbudgeted render', () => {+ const small = { id: 'ser-1', name: 'S', premise: 'P', targetFormat: 'novella', issueCountTarget: 6, styleNotes: 'SN', styleGuide: { voiceExemplars: [] }, characterArcs: [] };+ const parsed = JSON.parse(__testing.renderRepairSeriesJson(small));+ expect(parsed.styleGuide).toEqual({ voiceExemplars: [] });+ expect(parsed.omitted).toBeUndefined();+ });++ it('trims free-text fields as a floor when the brief alone overruns, keeping valid JSON', () => {+ const rendered = __testing.renderRepairSeriesJson({ id: 'ser-1', name: 'S', premise: 'p'.repeat(5_000), styleNotes: 'n'.repeat(5_000) }, 2_000);+ expect(rendered.length).toBeLessThanOrEqual(2_000);+ expect(() => JSON.parse(rendered)).not.toThrow();+ expect(rendered).toContain('truncated to fit the prompt budget');+ });++ const castMember = (i, size) => ({+ id: `chr-${i}`, name: `Cast ${i}`, role: 'lead',+ personality: 'q'.repeat(size), background: 'b'.repeat(size), relationships: 'r'.repeat(size),+ want: 'w'.repeat(60), need: 'n'.repeat(60), ghost: 'g'.repeat(size), wound: 'o'.repeat(size),+ });++ it('caps the candidate cast by size, compacting the full roster before dropping members', () => {+ const payload = {+ targetCharacters: Array.from({ length: 6 }, (_, i) => castMember(i, 200)),+ fullSeriesRoster: Array.from({ length: 40 }, (_, i) => castMember(i, 200)),+ };+ const rendered = __testing.renderRepairCharactersJson(payload);+ expect(rendered.length).toBeLessThanOrEqual(__testing.REPAIR_CHARACTERS_MAX_CHARS);+ const parsed = JSON.parse(rendered);+ // The batch under repair keeps every field intact — it outranks the roster.+ expect(parsed.targetCharacters).toHaveLength(6);+ expect(parsed.targetCharacters[0].background).toBe('b'.repeat(200));+ // The roster degrades to the differentiation spine.+ expect(parsed.fullSeriesRoster.length).toBeGreaterThan(0);+ expect(parsed.fullSeriesRoster[0]).toEqual({ id: 'chr-0', name: 'Cast 0', role: 'lead', want: 'w'.repeat(60), need: 'n'.repeat(60) });+ expect(parsed.rosterNote).toMatch(/fit the prompt budget/);+ });++ it('truncates the batch\'s own fields when six full characters alone overrun the budget', () => {+ const payload = {+ targetCharacters: Array.from({ length: 6 }, (_, i) => castMember(i, 1_500)),+ fullSeriesRoster: Array.from({ length: 40 }, (_, i) => castMember(i, 1_500)),+ };+ const rendered = __testing.renderRepairCharactersJson(payload);+ expect(rendered.length).toBeLessThanOrEqual(__testing.REPAIR_CHARACTERS_MAX_CHARS);+ const parsed = JSON.parse(rendered);+ expect(parsed.targetCharacters).toHaveLength(6);+ expect(parsed.targetCharacters[0].background).toContain('truncated to fit the prompt budget');+ expect(parsed.targetNote).toMatch(/truncated to fit the prompt budget/);+ });++ it('leaves an already-small cast payload untouched', () => {+ const payload = { targetCharacters: [{ id: 'chr-1', name: 'A' }], fullSeriesRoster: [{ id: 'chr-1', name: 'A' }] };+ expect(JSON.parse(__testing.renderRepairCharactersJson(payload))).toEqual(payload);+ });++ it('caps the flat (non-character-dimension) cast array by size too', () => {+ const array = Array.from({ length: 60 }, (_, i) => ({ id: `chr-${i}`, name: `Cast ${i}`, background: 'b'.repeat(900) }));+ const rendered = __testing.renderRepairCharactersJson(array);+ expect(rendered.length).toBeLessThanOrEqual(__testing.REPAIR_CHARACTERS_MAX_CHARS);+ expect(Array.isArray(JSON.parse(rendered))).toBe(true);+ });});describe('foundation repair prompt — bounded outline', () => {@@ -393,10 +555,79 @@ describe('foundation repair prompt — bounded outline', () => {const [, vars] = stageRunner.runStagedLLM.mock.calls.at(-1);// 60 × ~500 chars of synopsis would be ~30KB unbudgeted — the exact shape// that burned both the primary and fallback TUI provider's full timeout.- expect(vars.outline.length).toBeLessThanOrEqual(__testing.REPAIR_OUTLINE_MAX_CHARS + 200);+ expect(vars.outline.length).toBeLessThanOrEqual(__testing.REPAIR_OUTLINE_MAX_CHARS);expect(vars.outline).toContain('omitted to fit the prompt budget');expect(vars.outline).toContain(' V1 V1: VL');});++ // Regression for the 72,404-char character-foundation prompt that burned a CLI+ // runner's full 5-minute wall clock without emitting a byte (#3726).+ describe('character foundation — whole-prompt budget', () => {+ const seasons = Array.from({ length: 8 }, (_, i) => ({+ id: `sea-${i + 1}`, number: i + 1, title: `Volume ${i + 1}`,+ logline: 'l'.repeat(120), synopsis: 's'.repeat(900), endingHook: 'h'.repeat(200),+ }));+ const cast = Array.from({ length: 18 }, (_, i) => ({+ id: `chr-${i}`, name: `Cast ${i}`, role: 'lead',+ personality: 'q'.repeat(700), background: 'b'.repeat(700), relationships: 'r'.repeat(700),+ want: 'w'.repeat(150), need: 'n'.repeat(150), ghost: 'g'.repeat(500), wound: 'o'.repeat(500),+ lie: 'x'.repeat(300), coreTheme: 'c'.repeat(200), motivations: 'm'.repeat(400),+ speechPattern: 'p'.repeat(200), arcType: 'positive', secrets: ['z'.repeat(300)],+ }));++ beforeEach(() => {+ const series = {+ id: 'ser-1', name: 'Example Series', universeId: 'uni-1',+ premise: 'p'.repeat(2_500), targetFormat: 'novella', issueCountTarget: 40,+ styleNotes: 'n'.repeat(1_800),+ seasons,+ styleGuide: {+ voiceExemplars: Array.from({ length: 6 }, () => ({ passage: 'g'.repeat(1_200), note: 'note' })),+ voiceAntiExemplars: Array.from({ length: 6 }, () => ({ passage: 'x'.repeat(1_200), note: 'anti' })),+ },+ characterArcs: cast.map((character) => ({+ characterId: character.id, characterName: character.name,+ want: character.want, need: character.need,+ startState: 'a'.repeat(400), endState: 'e'.repeat(400),+ transitions: Array.from({ length: 6 }, (_, t) => ({ kind: 'decision', atIssue: t + 1, label: 'l'.repeat(150) })),+ })),+ };+ const universe = { id: 'uni-1', characters: cast };+ seriesSvc.getSeries.mockResolvedValue(series);+ universeBuilder.getUniverse.mockResolvedValue(universe);+ universeBuilder.updateUniverse.mockImplementation(async (id, mutator) => ({ id, ...(mutator(universe) || {}) }));+ issuesSvc.listIssues.mockResolvedValue(seasons.flatMap((season, s) => Array.from({ length: 10 }, (_, e) => ({+ number: s * 10 + e + 1, seasonId: season.id, title: `Ep ${e + 1}`,+ stages: { idea: { input: 'y'.repeat(600) } },+ }))));+ stageRunner.runStagedLLM.mockResolvedValue({ content: { characters: [], characterArcs: [] } });+ });++ it('keeps every stage prompt under 45,000 chars for 8 volumes / 18 characters / a full style guide', async () => {+ await applyFoundationFix('ser-1', 'character', { finding: { gap: 'blank lead', fix: 'build the causal chain' } });++ const calls = stageRunner.runStagedLLM.mock.calls.filter(([name]) => name === 'pipeline-character-foundation');+ expect(calls.length).toBeGreaterThan(0);+ for (const [, vars] of calls) {+ const total = Object.values(vars).reduce((sum, value) => sum + String(value ?? '').length, 0);+ expect(total).toBeLessThan(45_000);+ expect(vars.seriesJson.length).toBeLessThanOrEqual(__testing.REPAIR_SERIES_MAX_CHARS);+ expect(vars.charactersJson.length).toBeLessThanOrEqual(__testing.REPAIR_CHARACTERS_MAX_CHARS);+ expect(vars.outline.length).toBeLessThanOrEqual(__testing.REPAIR_OUTLINE_MAX_CHARS);+ }+ });++ it('requests a 10-minute timeout so a CLI provider is not killed by the 300s default', async () => {+ await applyFoundationFix('ser-1', 'character', { finding: { gap: 'blank lead', fix: 'build the causal chain' } });++ expect(__testing.CHARACTER_FOUNDATION_TIMEOUT_MS).toBe(600_000);+ expect(stageRunner.runStagedLLM).toHaveBeenCalledWith(+ 'pipeline-character-foundation',+ expect.anything(),+ expect.objectContaining({ timeoutOverride: 600_000 }),+ );+ });+ });});describe('foundation judge context — complete planning altitude', () => {