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
docs: plan context-aware manuscript editorial (full-manuscript <-> chunked)
[._.]/ Adam Eivy8fe63eb7097a
diff --git a/PLAN.md b/PLAN.mdindex 698b0e7865..701004aeb2 100644--- a/PLAN.md+++ b/PLAN.md@@ -9,6 +9,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelClaimable, well-specified, no decision needed — `/claim`-able. Unordered.+- [ ] [context-aware-editorial-budgeting] **Make manuscript editorial passes context-window-aware (full-manuscript ↔ chunked).** The editorial passes feed manuscript text to the LLM with no awareness of the target model's context window: completeness concatenates the whole series up to a hardcoded `BACKFILL_SOURCE_MAX = 200_000` chars (`server/services/pipeline/arcPlanner.js:722`), manuscript-fix sends single-issue *or* whole-manuscript in one call (`server/services/pipeline/manuscriptFix.js:278`), and editorial analysis caps at `CONTENT_MAX = 48_000` (`server/services/pipeline/editorialAnalysis.js:174`). Result: big-context models (Claude 4.8 ~1M, GPT 5.5) are needlessly capped, and models smaller than the manuscript silently truncate. Add a `contextWindow` field to the aiToolkit provider (sibling to the `numCtx` field added by the part-(a) truncation fix), a pure `contextBudget` helper that picks `mode: 'whole'` when manuscript + story-bible + output-reserve fits else `mode: 'chunked'` (chunk by issue + always include the story bible + a rolling findings digest, then merge with first-wins dedupe), and wire it into all three passes — deriving the caps from the budget instead of the constants. The whole-manuscript "place edits throughout" case in manuscript-fix must stay whole when it fits. **Full design + open decisions to lock before coding: `docs/plans/2026-05-31-context-aware-manuscript-editorial.md`.** (Not blindly claimable — read the doc's "Risks / decisions" section first.)- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` ~lines 655 + resume block ~317; VideoGen `attachJobEvents` ~line 450). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites.- [ ] [capabilities-cheap-memory-count] **Capabilities route should count active memories without sorting/paginating.** `GET /api/capabilities` calls `getMemories({ status: 'active' })` (`server/routes/capabilities.js` ~line 69) only to read `.total`, but `getMemories` loads the full index, filters, sorts, and paginates before returning `{ total, memories }` — the sort + slice is wasted work on a page polled every ~20s. Add a lightweight `countMemories({ status })` (or a `countOnly` option) to `server/services/memory.js` that returns the filtered count without the sort/paginate, and switch the route to it. Micro-opt; the index is cached via `loadIndex`, so low urgency.- [ ] [banner-icon-aria-hidden] **Apply `aria-hidden="true"` to `<Banner>`'s rendered icon.** `client/src/components/ui/Banner.jsx` (~line 62) renders the `icon` prop as a bare `<Icon …>` — when the icon is decorative (the body text already conveys the meaning), screen readers should skip it. Either wrap the icon render in `<span aria-hidden="true">` inside Banner, or thread an `iconAriaHidden` prop. Once landed, re-migrate the `ImportTab.jsx` error row to `<Banner tone="error" size="md" icon={AlertCircle} actions={…}>` (it was reverted from `<Banner>` because the icon prop doesn't pass through a11y attributes).diff --git a/docs/plans/2026-05-31-context-aware-manuscript-editorial.md b/docs/plans/2026-05-31-context-aware-manuscript-editorial.mdnew file mode 100644index 0000000000..7f89662ad1--- /dev/null+++ b/docs/plans/2026-05-31-context-aware-manuscript-editorial.md@@ -0,0 +1,102 @@+# Context-aware manuscript editorial (full-manuscript ↔ chunked)++**Date:** 2026-05-31+**Status:** Designed, not implemented. Part (a) (the urgent Ollama truncation fix) shipped separately; this doc covers part (b).+**PLAN.md anchor:** `[context-aware-editorial-budgeting]`++## Problem++The editorial review features feed manuscript text to an LLM with **no awareness of the+target model's context window**:++- **Manuscript completeness** ("Finish the draft", `server/services/pipeline/arcPlanner.js:722`,+ `collectIssueSourceText` + `BACKFILL_SOURCE_MAX = 200_000`) concatenates the **whole series**+ (up to 200K chars ≈ 50K tokens) into **one** LLM call.+- **Manuscript fix** ("Generate fix", `server/services/pipeline/manuscriptFix.js:278`) sends one+ comment's resolved targets — a single issue **or the whole manuscript** when the comment is+ unanchored/story-level — in one call. This whole-manuscript path is required: a structural/arc+ fix must place edits *throughout* the manuscript, so it genuinely needs the whole text in context.+- **Editorial analysis** (reader-emotion, `server/services/pipeline/editorialAnalysis.js:174`,+ `CONTENT_MAX = 48_000`) is already per-issue, but its cap is also a hardcoded constant.++Two failure modes result:++1. **Small-context models silently truncate.** Before part (a), Ollama's OpenAI endpoint defaulted+ to a ~4K window and dropped everything past it — so local editorial "reviewed" ~3% of the book+ with no error. Part (a) lifts the default window (per-request `num_ctx`), but a 50K-token+ manuscript still won't fit a model whose real ceiling is, say, 8K–32K.+2. **Big-context models are needlessly capped.** Claude 4.8 (~1M ctx) and GPT 5.5 are hard-capped at+ the 200K-char / 48K-char constants, throwing away manuscript the model could easily hold.++We want to support **both** full-manuscript and chunked review, choosing automatically based on the+target model's context budget — whole manuscript when it fits, chunk + story-bible + merge when it+doesn't.++## Design++### 1. Declare each provider's context window++Add a `contextWindow` (tokens) field to the aiToolkit provider config — sibling to the `numCtx`+field added in part (a). (`numCtx` = the per-request window we *ask Ollama for*; `contextWindow` =+the budget the editorial planner is *allowed to assume*. For local Ollama they track each other; for+cloud providers `numCtx` stays null and `contextWindow` reflects the model's real ceiling.)++- Schema parity: `server/lib/aiToolkit/validation.js` `providerSchema` + `createProvider()` in+ `server/lib/aiToolkit/providers.js` (mirror the `numCtx` additions from part (a)).+- Seed sensible defaults in `data.reference/` provider seeds: Claude 4.8 ≈ 1_000_000, GPT 5.5 ≈ its+ published ceiling, Mistral Large 128_000, local backends from the model (fall back to `numCtx`).+- The pipeline reads the **effective** window for the resolved provider/model in `stageRunner.js`+ (provider override > stage pin > active), reserving headroom for output + the story bible.++### 2. A context budgeter++New pure helper (`server/lib/pipeline/contextBudget.js`, unit-tested), roughly:++```+estimateTokens(text) // chars/4 heuristic is fine; no tokenizer dep+fitsWholeManuscript({ manuscriptTokens, storyBibleTokens, outputReserve, contextWindow })+planEditorialPasses({ issues, storyBible, contextWindow, outputReserve })+ -> { mode: 'whole', text } | { mode: 'chunked', chunks: [{ issues, storyBible, runningSummary }] }+```++- `mode: 'whole'` when `manuscript + storyBible + outputReserve <= contextWindow` → existing single+ call, but with the cap derived from `contextWindow` instead of the hardcoded 200K/48K.+- `mode: 'chunked'` otherwise → chunk by issue/chapter (reuse the per-issue plumbing already in+ `editorialAnalysis.js`), **always** include the story bible (`server/lib/storyBible.js`) +゚a rolling+ summary of prior chunks' findings so cross-chapter continuity is still caught, then **merge**+ per-section findings into the same `{ edits: [...] }` / findings shape the UI already consumes.++### 3. Wire the budgeter into the three passes++- `arcPlanner.analyzeManuscriptCompleteness` — replace the `BACKFILL_SOURCE_MAX` hardcap with the+ budgeter; when chunked, run the completeness prompt per chunk and merge findings (dedupe by+ issueNumber + anchorQuote).+- `manuscriptFix.generateManuscriptFix` — the whole-manuscript "place edits throughout" case stays+ whole when it fits; when it doesn't, fall back to a two-pass map/merge (locate target sections,+ then generate edits per section) rather than silently truncating.+- `editorialAnalysis.analyzeIssue` — derive `CONTENT_MAX` from the budget instead of the constant.++### 4. Merge semantics++Chunked passes must reconcile findings the way the monolithic split migrations do (see the+`[[project_monolithic_split_migration_fidelity]]` memory): first-wins dedupe, preserve issue+ordering, never drop a finding silently. Log (single-line, emoji-prefixed) when a pass was chunked+and how many chunks, so a chunked review never *looks* like a whole-book review when it wasn't.++## Risks / decisions to lock before implementing++- **Token estimation without a tokenizer.** chars/4 is conservative; combined with a configurable+ `outputReserve` (default ~8K) and a safety margin (~10%) it avoids over-filling. Decide the margin.+- **Editing vendored aiToolkit.** `contextWindow` belongs in the toolkit provider shape (same as+ `numCtx`); keep it generic (no PortOS imports) so upstream syncs don't fight it.+- **Rolling-summary cost.** Chunked continuity needs prior-chunk context; a summary keeps it bounded.+ Decide whether the summary is LLM-generated per chunk or a structured findings digest (prefer the+ latter — cheaper, deterministic, no extra model call).+- **UI signal.** Surface "reviewed in N chunks vs. whole" in the Manuscript Editor so the user knows+ the review's coverage shape.++## Out of scope++- Per-model tokenizer integration (the chars/4 heuristic is enough; revisit only if mis-estimation+ bites).+- Streaming/iterative editorial UI changes beyond the chunk-count indicator.