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
feat: feed prior-chunk findings digest to chunked LLM editorial checks (#1383)
[._.]/ Adam Eivyac7e7060fe2c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0c23122ba6..72dc7b4c3d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -130,3 +130,5 @@- **A TUI run whose model id is rejected by the backend now fails (and falls back) instead of returning a screen-scrape of the error.** When a Claude Code TUI run hit a non-recoverable model-id rejection — e.g. a bare Anthropic id like `claude-opus-4-8` passed to a Bedrock-backed Claude Code, which answers `API Error (…): 400 The provided model identifier is invalid` and suggests `global.anthropic.…` — the TUI just sat at an unanswered prompt. The one-shot runner saw output go idle, marked the run `success`, and (no `tui-response.txt` having been written) scraped the error *screen* and returned it as the model's "response." Downstream that surfaced as a baffling failure: AI manuscript Reformat reported `AI reformat changed the wording` (its integrity guard correctly rejecting the screen garbage), while other TUI-backed stages silently consumed the noise. The one-shot TUI runner now recognizes Claude Code's terminal model-id rejection (Bedrock 400 "model identifier is invalid" and Anthropic 404 `not_found_error`) and fails the run as `MODEL_NOT_FOUND`, so `runPromptThroughProvider` benches the provider and retries its configured fallback (e.g. `claude-code-tui` → `claude-code-bedrock`, whose Bedrock ids are valid) — turning a silent corruption into a transparent recovery, or, with no fallback, an actionable error. The check is line-anchored, requires the 400/404 to immediately follow the `API Error` prefix (so a retryable 429/500 Claude Code auto-retries is left alone), and is deliberately scoped to the one-shot runner — *not* the shared fallback detector the long-running agent spawn paths use, so an agent that merely echoes the error line in its own output (cat-ing a log, running the tests, investigating this very failure) can't have its run killed and misclassified. (`server/lib/aiToolkit/errorDetection.js`, `server/lib/tuiPromptRunner.js`)- **The "Verify arc" hover tooltip on the series arc page no longer renders clipped behind the nav and other cards.** The `VerifyScopeTooltip` panel sat in the arc-header's button row as an `absolute`-positioned child. That row scrolls horizontally (the "Derive from manuscript" button overflows on narrow widths), so its `overflow` clipped the popover and trapped it in an ancestor stacking context — no `z-index` could lift it above the sidebar nav or the cards below. Rewrote it as a portal-rendered (`createPortal` to `<body>`), `position: fixed` popover anchored below-right of its trigger via the live `getBoundingClientRect()`, so it floats above everything and is clamped on-screen on narrow viewports. (A prior pass bumped the z-index to `z-[60]`, which didn't help because the clip was an `overflow`/stacking-context problem, not a layering one.) `aria-describedby` wiring is preserved. (`client/src/components/pipeline/ArcCanvas.jsx`)++- **[issue-1383] Chunked LLM editorial checks now carry cross-chapter continuity between chunks.** When a manuscript is too long for the provider's context window, the manuscript-consuming LLM checks review it chunk-by-chunk and merge findings first-wins (#1340). But a per-chunk view is blind to problems that span chapters: `style.conformance` couldn't see that chapter 1 established past-tense when judging chapter 3, and `objects.unmotivated-interaction` could flag a "missing setup" for an object that an earlier chunk already accounted for. Those two checks now opt into a rolling **prior-findings digest** (`editorialPriorFindingsDigest`) — each chunk after the first is prefixed with a capped, first-wins summary of the findings gathered so far, riding INSIDE the manuscript var so no stage-prompt template changes (mirrors the completeness pass's `priorFindingsDigest`). The digest instructs the model not to repeat prior findings and to flag only new problems plus cross-chapter continuity issues the earlier findings reveal; exact repeats are still deduped by `editorialFindingKey`. The chunk planner reserves `EDITORIAL_PRIOR_DIGEST_TOKENS` so prepending the digest can't overrun the window, and `prose.info-dumping` deliberately stays per-chunk (its problems are localized). The shared chunk loop is factored into one `runChunkedManuscriptCheck` helper used by both the staged and custom-check paths. (`server/lib/editorial/checkRegistry.js`, #1383)diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 980643011c..8a3a8dd085 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -14,9 +14,19 @@ This directory is **pure** (no side-effecting imports — only `zod` and the purmanuscript-consuming LLM check plans the corpus into provider-sized chunksthrough `ctx.planManuscriptChunks` — all injected by the runner. Per-chunkfindings are merged first-wins (capped at the check's `maxFindings`) via-`mergeChunkFindings`/`editorialFindingKey`, so a long series is fully reviewed+`editorialFindingKey` (the pure `mergeChunkFindings` helper exposes the same+merge for callers that collect-then-merge), so a long series is fully reviewedregardless of the provider's context window (#1340).+Checks whose problems span chapters can opt into a **cross-chunk continuity+digest** (#1383): pass `crossChunkDigest: true` to `runManuscriptLlmCheck` and+each chunk after the first is prefixed with `editorialPriorFindingsDigest` of the+findings gathered so far (it rides INSIDE the manuscript var, so no prompt+template change). The chunk planner reserves `EDITORIAL_PRIOR_DIGEST_TOKENS` for+it. `style.conformance` (tense/POV established earlier) and+`objects.unmotivated-interaction` (setup/payoff across chapters) opt in;+`prose.info-dumping` stays per-chunk (its problems are localized).+## Discovery ruleBefore adding an editorial rule, check whether an existing registry entry coversdiff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex bb08555ffa..d75eec3518 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -25,7 +25,7 @@*/import { z } from 'zod';-import { estimateTokens } from '../contextBudget.js';+import { estimateTokens, CHARS_PER_TOKEN } from '../contextBudget.js';export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);@@ -226,6 +226,68 @@ export function mergeChunkFindings(lists, max = Infinity) {return [...merged.values()].slice(0, Math.max(0, max));}+// Cross-chunk continuity digest (#1383). When a manuscript is too long for the+// provider window it is reviewed chunk-by-chunk; a check whose problems span+// chapters (an object set up early and paid off late; tense/POV established in+// chapter 1 judged against chapter 3) can't see that with a per-chunk view.+// These constants bound the rolling digest of prior-chunk findings fed to later+// chunks so it stays small enough to ride in the chunk's spare budget.+export const EDITORIAL_PRIOR_DIGEST_MAX = 40;+export const EDITORIAL_PRIOR_DIGEST_CHARS = 2_400;+// Token budget the chunk planner reserves for the digest so prepending it can't+// push a chunk over the provider window (the digest string is capped to+// EDITORIAL_PRIOR_DIGEST_CHARS, so this reserve is an exact upper bound).+export const EDITORIAL_PRIOR_DIGEST_TOKENS = Math.ceil(EDITORIAL_PRIOR_DIGEST_CHARS / CHARS_PER_TOKEN);++// One-block digest of findings already recorded for earlier chunks, prepended+// INSIDE the next chunk's manuscript var so no prompt template changes (mirrors+// completenessPass.priorFindingsDigest). Pure + capped for unit-testing. Returns+// '' when there are no prior findings so the first chunk is untouched.+export function editorialPriorFindingsDigest(findings) {+ if (!Array.isArray(findings) || !findings.length) return '';+ const lines = findings.slice(0, EDITORIAL_PRIOR_DIGEST_MAX).map((f) => {+ const where = Number.isInteger(f.issueNumber) ? `Issue ${f.issueNumber}` : (f.location || 'general');+ return `- [${where}] ${f.category}: ${f.problem}`;+ });+ const more = findings.length > EDITORIAL_PRIOR_DIGEST_MAX+ ? `\n(+${findings.length - EDITORIAL_PRIOR_DIGEST_MAX} more earlier findings)` : '';+ const header = '# Editorial findings already recorded for EARLIER parts of this manuscript\n'+ + 'Do not repeat these. Flag only NEW problems in the text below, plus any cross-chapter '+ + 'continuity these earlier findings reveal (e.g. an object set up earlier, or a tense/POV '+ + 'choice established in an earlier chapter).\n\n';+ return `${header}${lines.join('\n')}${more}\n\n---\n\n`.slice(0, EDITORIAL_PRIOR_DIGEST_CHARS);+}++// Shared chunk loop for the manuscript-consuming LLM checks: run `callChunk` on+// each provider-sized chunk, normalize + merge findings first-wins (capped at+// `max` across the whole run). When `crossChunkDigest` is set, each chunk after+// the first is prefixed with a digest of the findings gathered so far so the+// model keeps cross-chapter continuity in view; the digest rides INSIDE the+// chunk text passed to `callChunk`, so the per-check prompt template is+// unchanged. Merges incrementally (vs collect-then-merge) so the digest is O(1)+// to derive from the running map.+async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk, crossChunkDigest = false }) {+ const merged = new Map();+ for (const manuscript of chunks) {+ // Stop launching further chunk calls once the run is cancelled — the runner+ // only checks the signal around the whole check, so without this a multi-+ // chunk check keeps paying for LLM calls whose results will be discarded.+ if (ctx.signal?.aborted) break;+ const digest = crossChunkDigest && merged.size ? editorialPriorFindingsDigest([...merged.values()]) : '';+ const content = await callChunk(`${digest}${manuscript}`);+ for (const f of mapLlmFindings(content?.findings, {+ severityDefault: ctx.severityDefault,+ category,+ max,+ withIssueNumber: true,+ })) {+ const k = editorialFindingKey(f);+ if (!merged.has(k)) merged.set(k, f);+ }+ }+ return [...merged.values()].slice(0, Math.max(0, max));+}+// Shared body for a manuscript-consuming LLM check. Plans the manuscript into// provider-sized chunks for `stage` (via the runner-injected// `ctx.planManuscriptChunks`), runs the model on each chunk, and merges the@@ -239,24 +301,23 @@ export function mergeChunkFindings(lists, max = Infinity) {// etc.) on top of EDITORIAL_PROMPT_OVERHEAD_TOKENS — those vars ride alongside// the chunked manuscript, so under-counting them lets a chunk overrun the// provider window.-async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, buildVars }) {+async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, buildVars, crossChunkDigest = false }) {const max = ctx.config?.maxFindings ?? 12;- const chunks = await ctx.planManuscriptChunks(stage, { overheadTokens });- const perChunk = [];- for (const manuscript of chunks) {- // Stop launching further chunk calls once the run is cancelled — the runner- // only checks the signal around the whole check, so without this a multi-- // chunk check keeps paying for LLM calls whose results will be discarded.- if (ctx.signal?.aborted) break;- const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript), { returnsJson: true, source: stage });- perChunk.push(mapLlmFindings(content?.findings, {- severityDefault: ctx.severityDefault,- category,- max,- withIssueNumber: true,- }));- }- return mergeChunkFindings(perChunk, max);+ // Reserve room for the prior-findings digest later chunks ride so prepending+ // it can't push a chunk over the provider window (only when this check opts in).+ const chunks = await ctx.planManuscriptChunks(stage, {+ overheadTokens: overheadTokens + (crossChunkDigest ? EDITORIAL_PRIOR_DIGEST_TOKENS : 0),+ });+ return runChunkedManuscriptCheck(ctx, {+ chunks,+ category,+ max,+ crossChunkDigest,+ callChunk: async (manuscript) => {+ const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript), { returnsJson: true, source: stage });+ return content;+ },+ });}// Normalize raw LLM findings into partial manuscriptReview comments: validate@@ -331,19 +392,18 @@ async function runManuscriptLlmCheckInline(ctx, { category, instructions }) {const overheadTokens = EDITORIAL_PROMPT_OVERHEAD_TOKENS+ estimateTokens(buildCustomCheckPrompt({ instructions, manuscript: '', maxFindings: max }));const chunks = await ctx.planManuscriptChunks(null, { overheadTokens });- const perChunk = [];- for (const manuscript of chunks) {- if (ctx.signal?.aborted) break;- const prompt = buildCustomCheckPrompt({ instructions, manuscript, maxFindings: max });- const { content } = await ctx.callInlineLLM(prompt, { returnsJson: true, source: CUSTOM_CHECK_RUN_SOURCE });- perChunk.push(mapLlmFindings(content?.findings, {- severityDefault: ctx.severityDefault,- category,- max,- withIssueNumber: true,- }));- }- return mergeChunkFindings(perChunk, max);+ return runChunkedManuscriptCheck(ctx, {+ chunks,+ category,+ max,+ // Custom checks are localized to the authored instruction — no cross-chunk+ // digest (the built-in continuity/style checks opt in explicitly).+ callChunk: async (manuscript) => {+ const prompt = buildCustomCheckPrompt({ instructions, manuscript, maxFindings: max });+ const { content } = await ctx.callInlineLLM(prompt, { returnsJson: true, source: CUSTOM_CHECK_RUN_SOURCE });+ return content;+ },+ });}// ---------------------------------------------------------------------------@@ -729,6 +789,10 @@ export const EDITORIAL_CHECKS = [// The objects-attachment summary is fixed per-call overhead.overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(objects),buildVars: (manuscript) => ({ manuscript, objects }),+ // An object's motivation can be set up in an earlier chapter and paid off+ // later; without the digest a later chunk may flag a "missing setup" an+ // earlier chunk already accounted for (#1383).+ crossChunkDigest: true,});},},@@ -912,6 +976,9 @@ export const EDITORIAL_CHECKS = [// The style-guide expectations are fixed per-call overhead.overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(expectations),buildVars: (manuscript) => ({ manuscript, styleGuide: expectations }),+ // Tense/POV drift is inherently cross-chapter — a per-chunk view can't see+ // that chapter 1 established past-tense when judging chapter 3 (#1383).+ crossChunkDigest: true,});},},diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 463cf48f21..4fb908a770 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -18,6 +18,10 @@ import {getAllChecks,CUSTOM_CHECK_ID_PREFIX,CUSTOM_CHECK_MAX_FINDINGS_DEFAULT,+ editorialPriorFindingsDigest,+ EDITORIAL_PRIOR_DIGEST_MAX,+ EDITORIAL_PRIOR_DIGEST_CHARS,+ EDITORIAL_PRIOR_DIGEST_TOKENS,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';@@ -537,6 +541,104 @@ describe('objects.unmotivated-interaction — LLM check (#1288)', () => {});});+describe('cross-chunk continuity digest (#1383)', () => {+ describe('editorialPriorFindingsDigest formatter', () => {+ it('returns empty string for no / non-array findings', () => {+ expect(editorialPriorFindingsDigest([])).toBe('');+ expect(editorialPriorFindingsDigest(null)).toBe('');+ expect(editorialPriorFindingsDigest(undefined)).toBe('');+ });++ it('lists prior findings by issue (or location) + category + problem under a header', () => {+ const digest = editorialPriorFindingsDigest([+ { issueNumber: 1, category: 'style', problem: 'past tense established' },+ { location: 'Prologue', category: 'continuity', problem: 'watch introduced' },+ ]);+ expect(digest).toMatch(/EARLIER parts of this manuscript/);+ expect(digest).toContain('- [Issue 1] style: past tense established');+ expect(digest).toContain('- [Prologue] continuity: watch introduced');+ expect(digest.endsWith('---\n\n')).toBe(true);+ });++ it('caps the listed findings and notes how many more were omitted', () => {+ const many = Array.from({ length: EDITORIAL_PRIOR_DIGEST_MAX + 5 }, (_, i) => ({+ issueNumber: i + 1, category: 'style', problem: `p${i}`,+ }));+ const digest = editorialPriorFindingsDigest(many);+ expect(digest).toMatch(/\(\+5 more earlier findings\)/);+ });++ it('caps the whole digest to EDITORIAL_PRIOR_DIGEST_CHARS so the reserve is an exact upper bound', () => {+ const huge = Array.from({ length: EDITORIAL_PRIOR_DIGEST_MAX }, (_, i) => ({+ issueNumber: i + 1, category: 'continuity', problem: 'x'.repeat(500),+ }));+ const digest = editorialPriorFindingsDigest(huge);+ expect(digest.length).toBeLessThanOrEqual(EDITORIAL_PRIOR_DIGEST_CHARS);+ expect(EDITORIAL_PRIOR_DIGEST_TOKENS * 4).toBeGreaterThanOrEqual(EDITORIAL_PRIOR_DIGEST_CHARS);+ });+ });++ // A check that opts into the digest prefixes every chunk AFTER the first with a+ // digest of the findings gathered so far, riding inside the manuscript var.+ const runTwoChunks = async (checkId, ctxExtras) => {+ const seen = [];+ let overhead = null;+ await getCheck(checkId).run({+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ planManuscriptChunks: async (_stage, opts) => { overhead = opts.overheadTokens; return ['CHUNK_ONE', 'CHUNK_TWO']; },+ callStagedLLM: async (_stage, vars) => {+ seen.push(vars.manuscript);+ // Only the first chunk surfaces a finding, so the digest fed to chunk two+ // carries exactly that one.+ const findings = seen.length === 1+ ? [{ severity: 'high', issueNumber: 1, problem: 'tense slip in chapter one', anchorQuote: 'I walk' }]+ : [];+ return { content: { findings } };+ },+ ...ctxExtras,+ });+ return { seen, overhead };+ };++ it('style.conformance feeds the prior-chunk digest to later chunks and reserves budget for it', async () => {+ const { seen, overhead } = await runTwoChunks('style.conformance', {+ series: { styleGuide: { tense: 'past', povPerson: 'first' } },+ });+ // First chunk is untouched (no prior findings yet).+ expect(seen[0]).toBe('CHUNK_ONE');+ // Second chunk is prefixed with the digest of chunk one's finding, then its text.+ expect(seen[1]).toContain('EARLIER parts of this manuscript');+ expect(seen[1]).toContain('tense slip in chapter one');+ expect(seen[1].endsWith('CHUNK_TWO')).toBe(true);+ // The digest reserve is folded into the chunk-planner overhead.+ expect(overhead).toBeGreaterThanOrEqual(EDITORIAL_PRIOR_DIGEST_TOKENS);+ });++ it('objects.unmotivated-interaction feeds the prior-chunk digest to later chunks', async () => {+ const { seen } = await runTwoChunks('objects.unmotivated-interaction', {+ canon: {+ objects: [{ id: 'o1', name: 'Watch', attachments: [{ characterId: 'c1', emotion: 'grief' }] }],+ characters: [{ id: 'c1', name: 'Mara' }],+ },+ });+ expect(seen[0]).toBe('CHUNK_ONE');+ expect(seen[1]).toContain('EARLIER parts of this manuscript');+ expect(seen[1].endsWith('CHUNK_TWO')).toBe(true);+ });++ it('prose.info-dumping stays per-chunk — no digest is prepended (its problems are localized)', async () => {+ const { seen } = await runTwoChunks(INFODUMP, {+ manuscript: 'CHUNK_ONE',+ });+ expect(seen[0]).toBe('CHUNK_ONE');+ // Second chunk is the raw text — no continuity digest even though chunk one+ // produced a finding.+ expect(seen[1]).toBe('CHUNK_TWO');+ expect(seen[1]).not.toContain('EARLIER parts of this manuscript');+ });+});+describe('objects.backstory-consistency — LLM check (#1288)', () => {const canonWithRow = () => ({objects: [{ id: 'o1', name: 'Watch', attachments: [{ characterId: 'c1', emotion: 'grief', origin: 'gift from her father in 1990' }] }],