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: manuscript completeness pass starved the draft to empty on a large canon

[._.]/ Adam Eivy9382eab746eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3f429a41c2..a18d1411e8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,10 @@
- Scheduled improvement tasks (documentation, security, code-quality, performance, test-coverage, accessibility, dependency-updates, ui-bugs, mobile-responsive, release-check) no longer keep an app-name-hardcoded "PortOS" prompt on existing installs. These prompts went generic (`{appName}`) a while ago, but were never versioned — so deployed instances kept the old PortOS-targeted text (and some had it mis-flagged as a user customization). They are now versioned with their prior defaults preserved, and `loadSchedule` self-heals the mis-flag, so every install auto-upgrades to the generic body on the next boot/update without clobbering genuine custom prompts.
+## Fixed
+
+- **Manuscript editorial review no longer reports a fully-drafted book as "empty."** The completeness pass injected the entire universe canon (characters + places + objects JSON, which for a large universe can be 800K+ chars / 200K+ tokens) as fixed context on every call. On any model whose context window the canon exceeded, the budgeter's usable-input budget collapsed to zero and the manuscript was sliced to an empty string — so the LLM "reviewed" a blank draft and returned a wall of identical "the drafted manuscript is empty" findings that could never be resolved, hard-pausing the autopilot at editorial review. The canon is now hard-capped to a reference-sized budget and window-aware-trimmed so the manuscript always keeps a budget floor (mirroring the editorial *check* runner's #1459 protection): a frontier-window model reviews the whole book in one pass, a smaller window chunks it — but the draft is never starved to empty.
+
## Added
- **Context-window size on available-model cards (Settings → Local LLM).** The model cards in the install catalog and the Hugging Face search results now show each model's native context window (e.g. "128K ctx") alongside its size and parameter count — previously this only appeared on already-installed models, so you couldn't compare context windows before deciding what to install. Live Hugging Face results read the true value from the repo's GGUF metadata (`gguf.context_length`, backfilled from the same per-repo fetch that already supplies file sizes); curated catalog entries carry it when it's a documented spec for that build.
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 8cd0f136af..c2e86860a3 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1864,6 +1864,50 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
expect(out.issues[0]).not.toHaveProperty('replace');
});
+ it('capCanonReference caps combined canon size, trimming the largest block first', () => {
+ const blocks = {
+ objects: 'O'.repeat(10_000),
+ characters: 'C'.repeat(4_000),
+ places: 'P'.repeat(500),
+ };
+ const trimmed = planner.capCanonReference(blocks, 6_000);
+ expect(trimmed).toBe(true);
+ const total = Object.values(blocks).reduce((n, v) => n + v.length, 0);
+ // Within budget (a small trim-marker allowance per cut block).
+ expect(total).toBeLessThanOrEqual(6_200);
+ // The smallest block survives untouched; the largest absorbed the cut.
+ expect(blocks.places).toBe('P'.repeat(500));
+ expect(blocks.objects.length).toBeLessThan(10_000);
+ });
+
+ it('capCanonReference is a no-op when already within budget', () => {
+ const blocks = { a: 'x'.repeat(100), b: 'y'.repeat(100) };
+ expect(planner.capCanonReference(blocks, 10_000)).toBe(false);
+ expect(blocks.a).toBe('x'.repeat(100));
+ });
+
+ it('never feeds the LLM an empty manuscript on a constrained window (canon cannot starve the draft)', async () => {
+ // Regression: an oversized canon/world context used to collapse usableChars
+ // to 0 and slice the manuscript to '', so the model "reviewed" an empty
+ // draft and reported the whole book missing. The canon cap + manuscript
+ // floor must keep real script text in every chunk.
+ const s = await setupSeries();
+ const script = 'PAGE 1\nPANEL 1\nThe foundry hums. '.repeat(400); // ~13K chars of real script
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Act 1', arcPosition: 1, stages: { comicScript: { output: script, status: 'ready' } } });
+ // Force a small planning window so the budgeter must chunk/trim.
+ stageContextSpy = vi.fn(async () => ({ provider: { id: 'p' }, model: 'm', contextWindow: 32_768 }));
+ const seen = [];
+ stageRunnerSpy = vi.fn(async (template, ctx) => {
+ seen.push(ctx.manuscript || '');
+ return { content: { issues: [] }, runId: 'rc', providerId: 'p', model: 'm' };
+ });
+ await planner.analyzeManuscriptCompleteness(s.id, { withEdits: true });
+ expect(seen.length).toBeGreaterThan(0);
+ // Every chunk the model saw must carry real manuscript text — never ''.
+ expect(seen.every((m) => m && m.trim().length > 0)).toBe(true);
+ expect(seen.some((m) => m.includes('The foundry hums'))).toBe(true);
+ });
+
it('analyzeManuscriptCompleteness reads the manuscript and returns shaped findings', async () => {
const s = await setupSeries();
await issuesSvc.createIssue({
diff --git a/server/services/pipeline/arcPlanner/completenessPass.js b/server/services/pipeline/arcPlanner/completenessPass.js
index a7150c6725..501fe0c113 100644
--- a/server/services/pipeline/arcPlanner/completenessPass.js
+++ b/server/services/pipeline/arcPlanner/completenessPass.js
@@ -4,7 +4,10 @@
*/
import { resolveStageContext, runStagedLLM } from '../../../lib/stageRunner.js';
-import { estimateTokens, planManuscriptPass } from '../../../lib/contextBudget.js';
+import {
+ estimateTokens, planManuscriptPass, fitContextToManuscriptFloor,
+ trimContextToBudget, MANUSCRIPT_FLOOR_TOKENS, CHARS_PER_TOKEN,
+} from '../../../lib/contextBudget.js';
import { getSeries } from '../series.js';
import { STAGE_OUTPUT_MAX } from '../issues.js';
import { getSeriesCanon } from '../seriesCanon.js';
@@ -103,6 +106,42 @@ export const COMPLETENESS_OUTPUT_RESERVE_TOKENS = 6_000;
// advice, so it needs materially more output room or a long edit list truncates.
export const COMPLETENESS_WITH_EDITS_OUTPUT_RESERVE_TOKENS = 12_000;
+// The canon/world reference blocks (existing{Characters,Places,Objects}Json,
+// worldCanonText, …) can be enormous — a large universe's object catalog alone
+// runs 300K+ chars. The completeness pass needs them only as a name+gist
+// reference for continuity, NOT as the full record set. Left unbounded they can
+// exceed the model's whole context window, which collapses `usableChars` to 0
+// and slices the MANUSCRIPT (the primary content) to '' — so the model
+// "reviews" an empty draft and reports the entire book missing. Hard-cap the
+// combined canon reference so it can never crowd the manuscript out of the
+// budget (the window-aware floor in `analyzeManuscriptCompleteness` squeezes it
+// further on a small window). ~20K tokens is plenty to anchor continuity.
+export const COMPLETENESS_CANON_REFERENCE_CHARS = 80_000;
+
+// baseCtx keys that carry the large, trimmable canon/world reference blocks.
+// Order is irrelevant — the cap trims the largest block first regardless.
+const CANON_CONTEXT_KEYS = [
+ 'existingObjectsJson', 'existingCharactersJson', 'existingPlacesJson',
+ 'worldCanonText', 'worldCategoriesText', 'worldCompositesText',
+];
+
+// Hard-cap the combined size of the canon/world reference blocks to `maxChars`,
+// trimming the largest block first so the giant object catalog absorbs the cut
+// while small blocks survive intact. Mutates `blocks` in place; returns true if
+// it trimmed anything. Window-independent (token efficiency + a floor the
+// window-aware pass can squeeze further).
+export function capCanonReference(blocks, maxChars = COMPLETENESS_CANON_REFERENCE_CHARS) {
+ const total = () => Object.values(blocks).reduce((n, v) => n + (v?.length || 0), 0);
+ if (total() <= maxChars) return false;
+ const largestFirst = Object.keys(blocks).sort((a, b) => (blocks[b]?.length || 0) - (blocks[a]?.length || 0));
+ for (const k of largestFirst) {
+ if (total() <= maxChars) break;
+ const overshoot = total() - maxChars;
+ blocks[k] = trimContextToBudget(blocks[k], Math.max(0, (blocks[k]?.length || 0) - overshoot));
+ }
+ return true;
+}
+
// Earlier-chapter findings summarized into the rolling digest fed to later
// chunks, and the char cap on that digest (kept small so it fits the margin).
export const COMPLETENESS_PRIOR_DIGEST_MAX = 40;
@@ -174,23 +213,54 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {};
const signal = options.signal || null;
- // Base (non-manuscript) context is fixed overhead present in every call.
+ // Base (non-manuscript) context. The canon/world reference blocks dominate it
+ // and, left unbounded, starve the manuscript out of the window (see
+ // COMPLETENESS_CANON_REFERENCE_CHARS). Two-step protection, mirroring the
+ // editorial check runner (#1459):
+ // 1. hard-cap the canon reference (window-independent), then
+ // 2. window-aware-trim it so the manuscript always keeps a budget floor.
const baseCtx = await buildCompletenessContext(series, '', options.preloadedWorld);
- const overheadTokens = estimateTokens(JSON.stringify(baseCtx)) + 2_000; // + template/instructions
const { contextWindow } = await resolveStageContext(COMPLETENESS_STAGE, {
providerOverride: options.providerOverride,
modelOverride: options.modelOverride,
});
+ const outputReserveTokens = withEdits
+ ? COMPLETENESS_WITH_EDITS_OUTPUT_RESERVE_TOKENS
+ : COMPLETENESS_OUTPUT_RESERVE_TOKENS;
+
+ // Pull the large trimmable canon/world blocks out of the fixed overhead.
+ const canonBlocks = {};
+ for (const k of CANON_CONTEXT_KEYS) {
+ if (typeof baseCtx[k] === 'string' && baseCtx[k]) canonBlocks[k] = baseCtx[k];
+ }
+ const hardCapped = capCanonReference(canonBlocks, COMPLETENESS_CANON_REFERENCE_CHARS);
+ // Fixed (non-trimmable) overhead = everything EXCEPT the canon blocks and the
+ // manuscript, plus a template/instruction allowance.
+ const fixedCtx = { ...baseCtx, manuscript: '' };
+ for (const k of CANON_CONTEXT_KEYS) delete fixedCtx[k];
+ const fixedOverheadTokens = estimateTokens(JSON.stringify(fixedCtx)) + 2_000;
+ // Window-aware floor: on a small window, squeeze the canon further so the
+ // manuscript keeps at least a floor of input budget (never sliced to '').
+ const corpusChars = sections.reduce((n, s) => n + (s.content?.length || 0), 0);
+ const fit = fitContextToManuscriptFloor(canonBlocks, {
+ contextWindow,
+ fixedOverheadTokens,
+ outputReserveTokens,
+ floorTokens: Math.min(MANUSCRIPT_FLOOR_TOKENS, Math.ceil(corpusChars / CHARS_PER_TOKEN)),
+ });
+ if (hardCapped || fit.trimmed) {
+ console.log(`✂️ completeness: canon reference trimmed to keep manuscript budget — series=${String(seriesId).slice(0, 12)} window=${contextWindow ?? 'floor'}`);
+ }
+ const fittedBaseCtx = { ...baseCtx, ...fit.context };
+
const plan = planManuscriptPass({
contextWindow,
sections: sections.map((s) => ({ ...s, text: `${manuscriptSectionHeader(s)}\n\n${s.content}` })),
- overheadTokens,
- outputReserveTokens: withEdits
- ? COMPLETENESS_WITH_EDITS_OUTPUT_RESERVE_TOKENS
- : COMPLETENESS_OUTPUT_RESERVE_TOKENS,
+ overheadTokens: fit.overheadTokens,
+ outputReserveTokens,
});
- const runOne = (manuscript) => runStagedLLM(COMPLETENESS_STAGE, { ...baseCtx, manuscript, withEdits }, {
+ const runOne = (manuscript) => runStagedLLM(COMPLETENESS_STAGE, { ...fittedBaseCtx, manuscript, withEdits }, {
providerOverride: options.providerOverride,
modelOverride: options.modelOverride,
returnsJson: true,