Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-1488]): budget standalone pipeline stages to the provider window instead of a fixed CONTENT_MAX floor

[._.]/ Adam Eivyd6cbbdb448c9
diff --git a/server/lib/README.md b/server/lib/README.md
index 770eca0950..9077d1d2a1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -92,7 +92,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `runners.js` | Image-runner family constants. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
-| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
+| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and LoRA trainer. Pure. |
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.js
index 34c31dfa91..40ee61034f 100644
--- a/server/lib/contextBudget.js
+++ b/server/lib/contextBudget.js
@@ -63,6 +63,35 @@ export function usableInputTokens({
return Math.max(0, afterMargin - Math.max(0, outputReserveTokens) - Math.max(0, overheadTokens));
}
+/**
+ * Char cap for a SINGLE-block manuscript/script pass — a stage that sends one big
+ * content block (the drafted manuscript, comic script, or POV passage) plus fixed
+ * prompt overhead, with no separate trimmable context block (so the richer
+ * `fitContextToManuscriptFloor` doesn't apply). Returns the usable INPUT budget in
+ * chars (window − overhead − output reserve − safety margin), floored at a
+ * manuscript minimum so a small/local provider window never sizes the content to
+ * empty, and free to grow to fill a large window.
+ *
+ * This replaces the historical `Math.max(CONTENT_MAX, budgetChars)` floor at the
+ * standalone pipeline stages (#1488). That pinned a fixed 48–60K-char floor
+ * regardless of the resolved window, so a genuinely small (e.g. 8K) local provider
+ * overflowed: the floor (~12–15K manuscript tokens) plus overhead + output reserve
+ * exceeded the window. Flooring at the manuscript minimum instead keeps the #1459
+ * philosophy — never starve the content block to empty — while respecting the
+ * provider window: a small window trims the content to fit (the caller appends its
+ * own `[… truncated …]` marker), a large window scales up exactly as before.
+ */
+export function manuscriptContentBudgetChars({
+ contextWindow,
+ overheadTokens = 0,
+ outputReserveTokens = DEFAULT_OUTPUT_RESERVE_TOKENS,
+ safetyMargin = DEFAULT_SAFETY_MARGIN,
+ floorTokens = MANUSCRIPT_FLOOR_TOKENS,
+} = {}) {
+ const budgetTokens = usableInputTokens({ contextWindow, overheadTokens, outputReserveTokens, safetyMargin });
+ return Math.max(Math.max(0, floorTokens), budgetTokens) * CHARS_PER_TOKEN;
+}
+
/**
* Decide how much of a re-sent context block (the reverse-outline scene map,
* character arcs, plotline coverage, …) a chunked manuscript pass can afford,
diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.js
index 7e2ac3153f..c60d159671 100644
--- a/server/lib/contextBudget.test.js
+++ b/server/lib/contextBudget.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
estimateTokens,
usableInputTokens,
+ manuscriptContentBudgetChars,
planManuscriptPass,
capContextOverhead,
trimContextToBudget,
@@ -212,6 +213,53 @@ describe('contextBudget', () => {
// starve the manuscript chunk to empty on a small/fallback context window.
// ---------------------------------------------------------------------------
+ describe('manuscriptContentBudgetChars', () => {
+ it('scales up to the usable input budget on a large window', () => {
+ // 200k window, 0 margin/reserve, 0 overhead -> 200k tokens usable -> 800k chars.
+ const cap = manuscriptContentBudgetChars({
+ contextWindow: 200_000,
+ overheadTokens: 0,
+ outputReserveTokens: 0,
+ safetyMargin: 0,
+ });
+ expect(cap).toBe(200_000 * CHARS_PER_TOKEN);
+ });
+ it('respects a medium window instead of forcing the historical 48–60K floor (#1488)', () => {
+ // 16k window, 10% margin -> 14745; minus 6000 reserve minus 1500 overhead = 7245
+ // tokens -> 28980 chars. The old Math.max(60_000, budgetChars) would have pinned
+ // 60_000 chars (~15k tokens) and overflowed this window.
+ const cap = manuscriptContentBudgetChars({
+ contextWindow: 16_384,
+ overheadTokens: 1_500,
+ outputReserveTokens: 6_000,
+ });
+ const budgetTokens = usableInputTokens({ contextWindow: 16_384, overheadTokens: 1_500, outputReserveTokens: 6_000 });
+ expect(cap).toBe(budgetTokens * CHARS_PER_TOKEN);
+ expect(cap).toBeLessThan(60_000); // would have overflowed under the old fixed floor
+ });
+ it('floors at the manuscript minimum on a tiny window + large overhead so the content is never empty', () => {
+ // 8k window with a heavy output reserve drives the usable input budget to ~0;
+ // the floor (MANUSCRIPT_FLOOR_TOKENS) guarantees a non-empty, bounded chunk
+ // (a few paragraphs) instead of the 48–60K overflow the old floor produced.
+ const cap = manuscriptContentBudgetChars({
+ contextWindow: 8_192,
+ overheadTokens: 1_500,
+ outputReserveTokens: 6_000,
+ });
+ expect(cap).toBe(MANUSCRIPT_FLOOR_TOKENS * CHARS_PER_TOKEN);
+ expect(cap).toBeGreaterThan(0);
+ });
+ it('honors a custom floor', () => {
+ const cap = manuscriptContentBudgetChars({
+ contextWindow: 1_000,
+ overheadTokens: 0,
+ outputReserveTokens: 5_000, // exhausts the window
+ floorTokens: 500,
+ });
+ expect(cap).toBe(500 * CHARS_PER_TOKEN);
+ });
+ });
+
describe('capContextOverhead', () => {
it('passes context through unchanged when the window comfortably fits everything', () => {
const r = capContextOverhead({ contextWindow: 100_000, contextTokens: 2_000, fixedOverheadTokens: 1_500 });
diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.js
index 84072c82b4..c9e67b04b0 100644
--- a/server/services/pipeline/continuityBible.js
+++ b/server/services/pipeline/continuityBible.js
@@ -29,7 +29,7 @@ import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { createSseRunner } from '../../lib/sseUtils.js';
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
-import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
import { seriesStore, getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
@@ -65,10 +65,10 @@ const SUBJECT_MAX = 120;
const STATEMENT_MAX = 600;
const ANCHOR_MAX = 240;
-// Floor on manuscript chars sent to the model — scaled UP to the target model's
-// context window in generateContinuityBible (mirrors reverseOutline), so a
-// big-context model reads the whole manuscript rather than a 60K slice.
-const CONTENT_MAX = 60_000;
+// Output space reserved when budgeting the manuscript chunk against the model's
+// context window (see manuscriptContentBudgetChars in generateContinuityBible,
+// mirrors reverseOutline) — the corpus scales to fill the window above a manuscript
+// floor, so a big-context model reads the whole manuscript while a small one trims.
const LEDGER_OUTPUT_RESERVE_TOKENS = 6_000;
const nowIso = () => new Date().toISOString();
@@ -258,12 +258,11 @@ export async function generateContinuityBible(seriesId, { providerId, model, for
const characterNames = (canonFacts.filter((f) => f.canonKind === 'character').map((f) => f.subject)).slice(0, 60);
const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
const overheadTokens = 1_500 + estimateTokens([series?.name || '', characterNames.join(', ')].join(' '));
- const budgetChars = usableInputTokens({
+ const contentMax = manuscriptContentBudgetChars({
contextWindow,
overheadTokens,
outputReserveTokens: LEDGER_OUTPUT_RESERVE_TOKENS,
- }) * CHARS_PER_TOKEN;
- const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ });
truncated = corpus.length > contentMax;
const vars = {
diff --git a/server/services/pipeline/continuityBible.test.js b/server/services/pipeline/continuityBible.test.js
index d1106e1297..e78ce44215 100644
--- a/server/services/pipeline/continuityBible.test.js
+++ b/server/services/pipeline/continuityBible.test.js
@@ -21,9 +21,9 @@ vi.mock('../../lib/stageRunner.js', () => ({
}));
vi.mock('../../lib/contextBudget.js', () => ({
- usableInputTokens: vi.fn(() => 100_000),
+ // Large content budget so the manuscript is never truncated in these tests.
+ manuscriptContentBudgetChars: vi.fn(() => 1_000_000),
estimateTokens: vi.fn(() => 100),
- CHARS_PER_TOKEN: 4,
}));
const seriesFixture = new Map();
diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.js
index 5c6fedc588..ac36a31ca6 100644
--- a/server/services/pipeline/perspectiveRewrite.js
+++ b/server/services/pipeline/perspectiveRewrite.js
@@ -23,7 +23,7 @@ import { createHash, randomUUID } from 'crypto';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
-import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
import { richCanonDescriptorFragments, flattenCanonDescriptorFragments } from '../../lib/canonPrompt.js';
import { getIssue } from './issues.js';
import { getSeries } from './series.js';
@@ -48,10 +48,10 @@ const RATIONALE_MAX = 600;
const ONE_LINE_MAX = 400;
const REWRITE_MAX_CHARS = 200_000;
-// Floor on source chars sent to the model — scaled UP to the target model's
-// context window (mirrors editorialAnalysis), so a big-context model rewrites
-// the whole passage rather than a 48K slice.
-const CONTENT_MAX = 48_000;
+// Output space reserved when budgeting the source passage against the model's
+// context window (see resolveStageContentMax) — the passage scales to fill the
+// window above a manuscript floor, so a big-context model rewrites the whole
+// passage while a small one trims to fit rather than overflowing a 48K floor.
const REWRITE_OUTPUT_RESERVE_TOKENS = 6_000;
const ANALYSIS_OUTPUT_RESERVE_TOKENS = 3_000;
@@ -184,19 +184,20 @@ const formatLabel = (stage) =>
stage === 'comicScript' ? 'comic script' : stage === 'teleplay' ? 'teleplay' : 'prose';
// Resolve a stage's usable content budget in chars, scaled to the (possibly
-// per-stage-pinned) model's context window and never below CONTENT_MAX. The
-// rewrite and analysis stages can be pinned to different providers/models, so
-// each must be budgeted against its OWN window — and `overheadText` must cover
-// every non-content token the stage's prompt renders (e.g. the full cast roster
-// the rewrite prompt prints), or a large cast silently overfills the window.
+// per-stage-pinned) model's context window, reserving a manuscript floor so a
+// small/local provider window trims the passage to fit rather than overflowing on
+// a fixed 48K floor (#1488); a big-context model scales up. The rewrite and
+// analysis stages can be pinned to different providers/models, so each must be
+// budgeted against its OWN window — and `overheadText` must cover every non-content
+// token the stage's prompt renders (e.g. the full cast roster the rewrite prompt
+// prints), or a large cast silently overfills the window.
async function resolveStageContentMax(stage, { providerId, model, overheadText, outputReserveTokens }) {
const { contextWindow } = await resolveStageContext(stage, { providerOverride: providerId, modelOverride: model });
- const budgetChars = usableInputTokens({
+ return manuscriptContentBudgetChars({
contextWindow,
overheadTokens: 1_500 + estimateTokens(overheadText),
outputReserveTokens,
- }) * CHARS_PER_TOKEN;
- return Math.max(CONTENT_MAX, budgetChars);
+ });
}
// ---------- generation ----------
diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.js
index 2ba863fd39..8b8fe99362 100644
--- a/server/services/pipeline/reverseOutline.js
+++ b/server/services/pipeline/reverseOutline.js
@@ -26,7 +26,7 @@ import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { createSseRunner } from '../../lib/sseUtils.js';
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
-import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
import { seriesStore, getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
@@ -58,10 +58,10 @@ const ISSUE_ID_MAX = 64;
const HASH_MAX = 128;
const PROVIDER_MAX = 120;
-// Floor on manuscript chars sent to the model — scaled UP to the target model's
-// context window in generateReverseOutline (mirrors editorialAnalysis), so a
-// big-context model segments the whole manuscript rather than a 60K slice.
-const CONTENT_MAX = 60_000;
+// Output space reserved when budgeting the manuscript chunk against the model's
+// context window (see manuscriptContentBudgetChars in generateReverseOutline) —
+// the corpus scales to fill the window above a manuscript floor, so a big-context
+// model segments the whole manuscript while a small one trims to fit.
const OUTLINE_OUTPUT_RESERVE_TOKENS = 6_000;
const PLOTLINE_KINDS = Object.freeze(['main', 'subplot', 'pov', 'thematic', 'other']);
@@ -245,15 +245,16 @@ export async function generateReverseOutline(seriesId, { providerId, model, forc
const canon = series ? await getSeriesCanon(series).catch(() => ({ characters: [] })) : { characters: [] };
const characterNames = (canon.characters || []).map((c) => c?.name).filter(Boolean).slice(0, 60);
- // Scale the content cap to the model's context window — never below CONTENT_MAX.
+ // Scale the content cap to the model's context window, reserving a manuscript
+ // floor so a small/local provider window trims the corpus to fit rather than
+ // overflowing on a fixed 60K floor (#1488); a big window scales up.
const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
const overheadTokens = 1_500 + estimateTokens([series?.name || '', series?.styleNotes || '', characterNames.join(', ')].join(' '));
- const budgetChars = usableInputTokens({
+ const contentMax = manuscriptContentBudgetChars({
contextWindow,
overheadTokens,
outputReserveTokens: OUTLINE_OUTPUT_RESERVE_TOKENS,
- }) * CHARS_PER_TOKEN;
- const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ });
const truncated = corpus.length > contentMax;
const vars = {
diff --git a/server/services/pipeline/reverseOutline.test.js b/server/services/pipeline/reverseOutline.test.js
index dcea0c9a3f..3697fa7bdb 100644
--- a/server/services/pipeline/reverseOutline.test.js
+++ b/server/services/pipeline/reverseOutline.test.js
@@ -22,9 +22,9 @@ vi.mock('../../lib/stageRunner.js', () => ({
}));
vi.mock('../../lib/contextBudget.js', () => ({
- usableInputTokens: vi.fn(() => 100_000),
+ // Large content budget so the manuscript is never truncated in these tests.
+ manuscriptContentBudgetChars: vi.fn(() => 1_000_000),
estimateTokens: vi.fn(() => 100),
- CHARS_PER_TOKEN: 4,
}));
// Series store (recordDir for the sibling path) + getSeries.
diff --git a/server/services/pipeline/scriptVerify.js b/server/services/pipeline/scriptVerify.js
index 31dff54108..5fdc6583c6 100644
--- a/server/services/pipeline/scriptVerify.js
+++ b/server/services/pipeline/scriptVerify.js
@@ -15,13 +15,12 @@
*/
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
-import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
import { getIssue } from './issues.js';
import { getSeries } from './series.js';
import { shapeVerifyIssues } from './arcPlanner.js';
const STAGE = 'pipeline-script-verify';
-const CONTENT_MAX = 48_000;
const OUTPUT_RESERVE_TOKENS = 2_000;
const VERIFY_PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;
const VERIFY_PANEL_RE = /^(?:###\s+)?Panel\s+([\dIVX]+)\s*(?:\([^)]+\))?\s*:?\s*$/i;
@@ -206,17 +205,17 @@ export async function verifyComicScript(issueId, { providerId, model } = {}) {
const series = await getSeries(issue.seriesId).catch(() => null);
- // Scale the content cap to the target model's context window — never below
- // CONTENT_MAX (so we never truncate more than the historical floor), but a
- // big-context model gets the whole script. Mirrors editorialAnalysis.
+ // Scale the content cap to the target model's context window, reserving a
+ // manuscript floor so a small/local provider window trims the script to fit
+ // rather than overflowing on a fixed 48K floor (#1488); a big-context model gets
+ // the whole script.
const { contextWindow } = await resolveStageContext(STAGE, { providerDefault: providerId, modelOverride: model });
const overheadTokens = 1_200 + estimateTokens([series?.name, series?.logline, issue.title].filter(Boolean).join(' '));
- const budgetChars = usableInputTokens({
+ const contentMax = manuscriptContentBudgetChars({
contextWindow,
overheadTokens,
outputReserveTokens: OUTPUT_RESERVE_TOKENS,
- }) * CHARS_PER_TOKEN;
- const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ });
const content = script.length > contentMax
? `${script.slice(0, contentMax)}\n\n[script truncated for verification — ${script.length} chars total]`
: script;