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

refactor([issue-1488]): migrate editorialAnalysis to manuscriptContentBudgetChars too + simplify floor max

[._.]/ Adam Eivy1c71ce73db29
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c23c85df12..9d90a48ff4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,7 +11,7 @@
- **The built-in "Recommended" model cards now have the same RAM-aware quant picker as the Hugging Face search.** Recommended models used to hard-code one quant each; cards backed by a Hugging Face repo now show the **Quant** menu and default to the highest-fidelity build that fits this machine's memory, so the recommendation adapts to your hardware instead of being fixed.
- **[issue-1539] Recommended models that pull from Ollama's own registry by bare name now get the RAM-aware quant picker too.** Previously only Hugging Face-backed recommended cards offered a **Quant** menu; cards for Ollama registry models (Llama 3.2, Qwen2.5, GPT-OSS, Llama 3.3, …) showed a single hard-coded build. PortOS now discovers each of those models' available quantizations from the Ollama registry and presents them in the same picker, with per-quant fit hints and the highest-fidelity build that fits your memory selected by default — so every recommended card adapts to your hardware, regardless of which registry the model comes from. When a model can't be reached on the registry, its card keeps its single curated build as before.
- **Hugging Face search results now rank by downloads and recency more strongly.** A model's download count and how recently it was updated now dominate the result ordering (recency is graduated — a model updated this week outranks an equivalent one from months or years ago, and stale models are demoted), so popular, actively-maintained models surface first instead of being outweighed by publisher/format bonuses.
-- **[issue-1488] Pinning a small-context local model to a heavy analysis stage no longer overflows its window.** The reverse-outline, continuity-bible, comic-script verification, and alternate-POV rewrite stages used to size the manuscript they send to a fixed 48–60K-character floor regardless of the model — fine on a big-context provider, but on a genuinely small-window local model (e.g. an 8K-context model) that floor plus the prompt could exceed the window. These stages now scale the manuscript to the model's actual window, trimming it to fit a small one (never down to empty — a usable minimum is always kept) while still feeding the whole manuscript to a large-context model exactly as before.
+- **[issue-1488] Pinning a small-context local model to a heavy analysis stage no longer overflows its window.** The reverse-outline, continuity-bible, comic-script verification, alternate-POV rewrite, and per-issue editorial-analysis stages used to size the manuscript they send to a fixed 48–60K-character floor regardless of the model — fine on a big-context provider, but on a genuinely small-window local model (e.g. an 8K-context model) that floor plus the prompt could exceed the window. These stages now scale the manuscript to the model's actual window, trimming it to fit a small one (never down to empty — a usable minimum is always kept) while still feeding the whole manuscript to a large-context model exactly as before.
## Comic pages
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.js
index 40ee61034f..cffdc133b5 100644
--- a/server/lib/contextBudget.js
+++ b/server/lib/contextBudget.js
@@ -89,7 +89,9 @@ export function manuscriptContentBudgetChars({
floorTokens = MANUSCRIPT_FLOOR_TOKENS,
} = {}) {
const budgetTokens = usableInputTokens({ contextWindow, overheadTokens, outputReserveTokens, safetyMargin });
- return Math.max(Math.max(0, floorTokens), budgetTokens) * CHARS_PER_TOKEN;
+ // budgetTokens is already ≥ 0 (usableInputTokens floors it); the explicit 0
+ // guards against a caller passing a negative floorTokens.
+ return Math.max(0, floorTokens, budgetTokens) * CHARS_PER_TOKEN;
}
/**
diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.js
index 64ba69b9a2..462705056d 100644
--- a/server/services/pipeline/editorialAnalysis.js
+++ b/server/services/pipeline/editorialAnalysis.js
@@ -19,7 +19,7 @@ import { join } from 'path';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.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 { getIssue, listIssues } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
@@ -35,17 +35,14 @@ const LABEL_MAX = 120;
const EXCERPT_MAX = 200;
const EMOTION_MAX = 40;
const NOTE_MAX = 500;
-// Cap the content we send to the model. Prose/script stage output is bounded
-// at STAGE_OUTPUT_MAX (~400KB) which would blow the context window (and the
-// JSON instruction block with it) on a long issue, yielding a truncated /
-// malformed response that extractJson rejects (it throws "Invalid JSON in AI
-// response", surfacing as an analysis error rather than a silent empty
-// snapshot). ~48K chars (~12K tokens) leaves ample room for the prompt + a
-// heavy-tier reply. This is a FLOOR — the real cap scales up to the target
-// model's context window (see analyzeIssue), so a big-context model isn't
-// needlessly truncated to 48K.
-const CONTENT_MAX = 48_000;
-// Output reserve for the analysis JSON (sections + character arcs).
+// Output reserve for the analysis JSON (sections + character arcs). The content
+// we send is capped by manuscriptContentBudgetChars in analyzeIssue, which scales
+// to the model's context window above a manuscript floor — so a big-context model
+// gets the whole issue while a small/local one trims to fit (with a truncation
+// marker) rather than overflowing on a fixed 48K floor (#1488). Prose/script stage
+// output is otherwise bounded at STAGE_OUTPUT_MAX (~400KB), which would blow the
+// window (and the JSON instruction block with it) on a long issue and yield a
+// malformed response extractJson rejects.
const ANALYSIS_OUTPUT_RESERVE_TOKENS = 4_000;
const nowIso = () => new Date().toISOString();
@@ -193,19 +190,19 @@ export async function analyzeIssue(issueId, { providerId, model, force = false }
const characterNames = (canon.characters || []).map((c) => c?.name).filter(Boolean).slice(0, 40);
const arc = series?.arc || null;
- // Scale the content cap to the target model's context window — never below
- // CONTENT_MAX (so we never truncate more than before), but a big-context
- // model gets the whole issue instead of a 48K slice.
+ // Scale the content cap to the target model's context window, reserving a
+ // manuscript floor so a small/local provider window trims the issue to fit
+ // rather than overflowing on a fixed 48K floor (#1488); a big-context model gets
+ // the whole issue.
const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
const overheadTokens = 1_500 + estimateTokens(
[characterNames.join(', '), arc?.protagonistArc || '', (arc?.themes || []).join(', ')].join(' '),
);
- const budgetChars = usableInputTokens({
+ const contentMax = manuscriptContentBudgetChars({
contextWindow,
overheadTokens,
outputReserveTokens: ANALYSIS_OUTPUT_RESERVE_TOKENS,
- }) * CHARS_PER_TOKEN;
- const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ });
const ctx = {
series: { name: series?.name || 'Untitled series', logline: series?.logline || '' },
diff --git a/server/services/pipeline/editorialAnalysis.test.js b/server/services/pipeline/editorialAnalysis.test.js
index 51146757a1..ef21f137c5 100644
--- a/server/services/pipeline/editorialAnalysis.test.js
+++ b/server/services/pipeline/editorialAnalysis.test.js
@@ -20,7 +20,7 @@ vi.mock('../../lib/stageRunner.js', () => ({
const content = llmQueue.shift();
return { content, model: 'mock-model', providerId: 'mock-provider', runId: 'run-1' };
}),
- // Large window so the content cap stays at its CONTENT_MAX floor in tests.
+ // Large window so the content cap never truncates the issue in tests.
resolveStageContext: vi.fn(async () => ({ provider: { id: 'mock-provider' }, model: 'mock-model', contextWindow: 1_000_000 })),
}));