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
refactor: barrel-split checkInfra, layeredIntelligence, and seriesAutopilot by sub-domain (#2842)
[._.]/ Adam Eivya0e559d50041
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b25aeba5e5..ec0bf13319 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -74,3 +74,4 @@- **[issue-2844] Drop the `@dnd-kit/utilities` dependency** — the package was pulled in only for `CSS.Transform.toString()` at three drag-and-drop sites (influence chips, CoS sortable tasks, video timeline blocks). A ~10-line owned helper, `dndTransformToCss` in `client/src/lib/dndTransform.js`, replaces it with byte-identical output (rounded `translate3d` + verbatim `scaleX`/`scaleY`, `undefined` for a null transform), and the direct dependency is removed from `client/package.json` and its lockfile. It remains in the tree only as a transitive peer of `@dnd-kit/core`/`sortable`, which stay.- **[issue-2846] Add a client `sleep(ms)` helper and rebuild `useLocalStorageBool` on `safeStorage`** — `client/src/utils/sleep.js` mirrors the server helper and replaces the three duplicated inline delays (`lazyWithReload`'s retry backoff, `staleChunkReload`'s purge race timeout, `voiceClient`'s decoder-tick wait). `useLocalStorageBool`/`useLocalStoragePersisted` now delegate their four hand-rolled `try/catch` storage helpers to `client/src/lib/safeStorage.js`, which gains a `safeWriteJsonStorage` that guards `JSON.stringify` alongside `setItem`. The JSON read keeps a private sentinel so a stored `null` still runs the caller's `parse` migration instead of collapsing into "missing".- **[issue-2899] Fold the Creative Director / Music Video / Sprites `selectBackend()` dispatchers into `pgFileFacade`** — Creative Director, Music Video, and Sprites each memoized their own copy of the same file-vs-Postgres selector (already drifted: differing error text, differing test-mode predicate). A new `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` in `server/lib/pgFileFacade.js` wraps the existing `createPgFileFacade`/`resolvePgBackend` backbone for stores whose backends are whole modules rather than built objects, so the escape-hatch posture, the health-check → `ensureSchema` → one-time-migration bring-up, and the selection memoization live in one place. Public store surfaces are unchanged (`getProjectsBackendName()` still reports `'file'`/`'postgres'`), each store keeps its own requirement message, and Sprites keeps its stronger `isTestRunner()` test-mode signal via the new `isTestMode` hook — no gating semantics were weakened. The selector also exposes a `reset()` test seam matching the `_reset<X>Backend()` exports on the artists/tracks/albums/authors stores, which still hand-roll the same dispatcher and are tracked separately.+- **[issue-2842] Barrel-split `checkInfra`, `layeredIntelligence`, and `seriesAutopilot` by sub-domain** — the three remaining ~2.6k-line multi-domain server files each become a thin re-exporting barrel over a new same-named directory, mirroring the `arcPlanner.js` split (#1152). `server/lib/editorial/checkInfra.js` → `checkInfra/{externals,taxonomy,revealForeshadowing,craftStages,voiceCanon,structureStages,povAndNames,canonScaffolding,llmRunner,readability,rosterCast,sceneAnalysis,proseDensity,comic}.js`; `server/services/layeredIntelligence.js` → `layeredIntelligence/{constants,config,dedup,proposal,outcomes,awareness,gates,prompt,runCli,sources,semanticDedup,forgeFiler,jiraFiler,planFiler}.js`; `server/services/pipeline/seriesAutopilot.js` → `seriesAutopilot/{state,config,convergence,stepResolver,session,childRuns,editorialSteps,visualSteps,revisionSteps,dispatch,dryRun,orchestrator}.js`. No caller changes — every existing deep import still resolves through the barrel, and `seriesAutopilot`'s `__testing` bundle is reassembled from the split modules. Three new `*Barrel.test.js` suites pin the contract (every module export reachable through the barrel as the same object, no cross-module symbol collisions). The largest resulting module is 439 lines, down from 2,635.diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 73313e682f..5841710c38 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -194,7 +194,8 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of| Module | Purpose ||---|---|| `checkRegistry.js` | The public entry point. Assembles `EDITORIAL_CHECKS` by spreading the per-category arrays from `./checks/*.js`, re-exports the shared infra from `./checkInfra.js`, and keeps the registry's lookup/state helpers that need the assembled array: `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387), fail-fast guards (`assertValidChecks`), and `getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`, `orderChecksByDependencies` (the dependency topo-sort, #1627) plus the user-defined-check helpers (`buildCustomCheck`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Decomposed from a 7,474-line god file in #1829. |-| `checkInfra.js` | Shared check infrastructure extracted in #1829: imports + constants + stage names + the pure summary/helper functions (e.g. `runManuscriptLlmCheck`, `canonCharacterTraitsSummary`, `editorialFindingKey`, `buildCustomCheckPrompt`, `normalizeCheckScopes`/`primaryCheckScope`) that the check definitions and the registry tail depend on. Kept side-effect-free so `./checks/*.js` import from it without a cycle through `checkRegistry.js` (whose `EDITORIAL_CHECKS` spread would otherwise hit a TDZ on the checks' eagerly-evaluated `configSchema`s). Re-exports its externals (zod + the sibling primitive modules) so a check file imports everything from one hub. |+| `checkInfra.js` | Shared check infrastructure extracted in #1829: imports + constants + stage names + the pure summary/helper functions (e.g. `runManuscriptLlmCheck`, `canonCharacterTraitsSummary`, `editorialFindingKey`, `buildCustomCheckPrompt`, `normalizeCheckScopes`/`primaryCheckScope`) that the check definitions and the registry tail depend on. Kept side-effect-free so `./checks/*.js` import from it without a cycle through `checkRegistry.js` (whose `EDITORIAL_CHECKS` spread would otherwise hit a TDZ on the checks' eagerly-evaluated `configSchema`s). Re-exports its externals (zod + the sibling primitive modules) so a check file imports everything from one hub. **Since #2842 this file is a pure re-exporting barrel over `./checkInfra/*.js`** (it had grown to 2,635 lines spanning a dozen sub-domains); every existing `from './checkInfra.js'` import still resolves, and new code may import the focused module directly. |+| `checkInfra/*.js` | The sub-domain modules behind the `checkInfra.js` barrel (#2842, same treatment #1152 gave `arcPlanner.js`): `externals` (the zod/`estimateTokens`/sibling-scanner hub), `taxonomy` (scopes/kinds/severities/`EDITORIAL_SOURCES`/field types), `revealForeshadowing`, `craftStages`, `structureStages` (stage names + their prompt summaries), `voiceCanon` (voice/state/trait/continuity-ledger summaries), `povAndNames`, `canonScaffolding` (relationship-link + object-attachment walkers), `llmRunner` (chunked manuscript runs, prior-findings/setup digests, finding normalization, custom-check prompts), `readability`, `rosterCast`, `sceneAnalysis`, `proseDensity`, `comic` (lettering + comic↔prose sync). Import via the barrel or directly; `checkInfraBarrel.test.js` pins the re-export contract. || `checks/*.js` | The `EDITORIAL_CHECKS` definitions, grouped by category (#1829): `naming`, `cast`, `pov`, `characterArc`, `continuity` (incl. #2178 `continuity.premature-reveal` — the information-economy guard that flags a reveal-gated canon fact leaked before its reveal issue, reconciled against `revealGatedCanonSummary`; gated on `canonHasRevealGated`), `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`, `slop` (#2165 — `prose.slop-banned-words`/`prose.ai-tells`/`prose.structural-tics`/`prose.burstiness`, built on `../slopScore.js`), `world` (#2175 — `world.unforeshadowed-solution`/`world.cost-free-power`, the review-side companion to the Sanderson's-Laws worldbuilding doctrine injected into the universe-expansion generation prompt; reconciles against canon + the continuity-bible world-rule facts). Each exports a `<group>Checks` array of declarative check entries (scope, kind, severity, `configSchema`, `gate`, `run(ctx)`); `checkRegistry.js` imports and spreads them. Internal to the registry — imported only via `checkRegistry.js`, not the barrel. || `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). || `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). |diff --git a/server/lib/editorial/checkInfra.js b/server/lib/editorial/checkInfra.jsindex 83c58ee623..d3e8cb6c3d 100644--- a/server/lib/editorial/checkInfra.js+++ b/server/lib/editorial/checkInfra.js@@ -1,5 +1,5 @@/**- * Editorial check shared infrastructure (#1829).+ * Editorial check shared infrastructure (#1829) — re-exporting barrel (#2842).** Extracted from checkRegistry.js: the imports, constants, stage names, and* pure summary/helper functions that the EDITORIAL_CHECKS entries (now in@@ -7,2629 +7,25 @@* check files import from here without a cycle through checkRegistry.js (whose* EDITORIAL_CHECKS array spreads the check files — importing infra back from the* registry would hit a TDZ on eagerly-evaluated configSchemas).+ *+ * This file had grown to 2,635 lines spanning a dozen unrelated sub-domains.+ * Issue #2842 split it into ./checkInfra/* the same way #1152 split+ * `arcPlanner.js`; this barrel re-exports everything so existing+ * `from './checkInfra.js'` imports keep working. New code may import the+ * focused module directly.*/-import { z } from 'zod';-import { estimateTokens } from '../contextBudget.js';-import { renderCharacterArcsForPrompt } from '../seriesCharacterArc.js';-import { parseComicScript } from '../comicScriptParser.js';-import {- analyzeComicLettering,- DEFAULT_LETTERING_THRESHOLDS,-} from './letteringDensity.js';-import { analyzeBalloonAttribution } from './balloonAttribution.js';-import { analyzeNamePair, comparisonName, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';-import { findCliches, findModifierStacking } from './cliches.js';-import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner, findDialogueTagVariety, splitScenes } from './dialogue.js';-import { findItalicThoughts } from './italicThoughts.js';-import {- findFilterWords,- findHedgeWords,- findCrutchWords,- findAdverbs,- findPassiveVoice,- filterPassiveVoice,- findGestures,-} from './proseTics.js';-import {- findWordEchoes,- findRepeatedOpeners,- measureSentenceRhythm,-} from './repetition.js';-import {- findBannedWordsTier1,- findSuspiciousWordClusters,- findAiTells,- findNotJustButPatterns,- findNotSayingPatterns,- findNegativeAssertions,- findTheWaySimiles,- findTriadicShortSentences,- findStructuralTics,- emDashDensityPer1000,- transitionOpenerRatio,- paragraphLengthUniformity,- countSectionBreaks,- MIN_DENSITY_OCCURRENCES,-} from './slopScore.js';-import {- analyzePanelRhythm,- comicPageTurnSummary,- authoredRevealSummary,-} from './comicPacing.js';-import { findAxisReversals, findShotTypeMonotony, summarizeStoryboardShots } from './shotContinuity.js';-import { revealGatedCanonRows, canonHasRevealGated } from '../storyBible.js';--// Re-exported so ./checks/*.js and ./checkRegistry.js import everything from here.-export {- DEFAULT_LETTERING_THRESHOLDS,- MIN_DENSITY_OCCURRENCES,- analyzeBalloonAttribution,- analyzeComicLettering,- analyzeNamePair,- analyzePanelRhythm,- attributeDialogueByOwner,- authoredRevealSummary,- comicPageTurnSummary,- comparisonName,- countSectionBreaks,- emDashDensityPer1000,- estimateTokens,- filterPassiveVoice,- findAdverbs,- findAiTells,- findAxisReversals,- findBannedWordsTier1,- findCliches,- findCrutchWords,- findDialogueTagVariety,- findFilterWords,- findFirstLetterClusters,- findGestures,- findHedgeWords,- findItalicThoughts,- findModifierStacking,- findNegativeAssertions,- findNotJustButPatterns,- findNotSayingPatterns,- findPassiveVoice,- findRepeatedOpeners,- findSaidBookisms,- findShotTypeMonotony,- findStructuralTics,- findSuspiciousWordClusters,- findTheWaySimiles,- findTriadicShortSentences,- findUnattributedDialogueRuns,- findWordEchoes,- measureSentenceRhythm,- normalizeName,- paragraphLengthUniformity,- parseComicScript,- renderCharacterArcsForPrompt,- splitScenes,- summarizeStoryboardShots,- transitionOpenerRatio,- canonHasRevealGated,- revealGatedCanonRows,- z,-};---export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);--// A check's `scope` may be a single scope string OR an array of scopes (#1628).-// A dual-scope check is one rule meaningful at more than one granularity — e.g.-// `relationships.reciprocity` reasons series-wide but could also flag a newly-// added relationship per issue — declared `scope: ['series', 'issue']` instead of-// being split into two near-duplicate checks. These helpers normalize either form-// so every consumer (the load-time guard, the catalog grouping, the dry-run plan)-// fans a check across exactly its declared scopes.-//-// `normalizeCheckScopes` returns the declared scopes deduped and in canonical-// CHECK_SCOPES order; an unknown/empty input returns []. `primaryCheckScope`-// returns the first declared scope (canonical order) for the consumers that still-// bucket/sort by a single value — for a single-scope check it is just that scope.-export function normalizeCheckScopes(scope) {- const raw = Array.isArray(scope) ? scope : (scope == null ? [] : [scope]);- return CHECK_SCOPES.filter((s) => raw.includes(s));-}--export const primaryCheckScope = (scope) => normalizeCheckScopes(scope)[0] || null;--export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);-export const CHECK_SEVERITIES = Object.freeze(['high', 'medium', 'low']);-export const SEVERITIES = CHECK_SEVERITIES;--// The inputs a check can read, declared per-check via `sources` (#1387). The-// staleness runner (server/services/pipeline/editorial/checkRunner.js) fingerprints-// EXACTLY a check's declared sources, so a finding only goes stale when content-// the check actually analyzed drifts — editing the style guide no longer marks a-// naming finding stale, and editing the ticking clock no longer marks every-// canon-only finding stale. Every token here must have a matching resolver in the-// runner's `SOURCE_RESOLVERS` (a load-time guard there fails fast if they drift).-// - 'manuscript' — the stitched manuscript corpus (implies needsManuscript)-// - 'canon' — the universe/series canon (characters, relationships, objects)-// - 'continuityBible' — the series CONTINUITY-BIBLE facts ledger (#1305): the-// extracted ground-truth facts the timeline/canon-contradiction-// check (#1581) reconciles the prose against — `[{ category,-// subject, statement, issueNumber }]` across the bible's-// categories (physical, age, dates/elapsed time, location,-// possession, world rules, who-knows-what). The runner fetches-// it via `getFactsLedger` (gated on this source) and injects-// `ctx.continuityBible` (the facts array).-// - 'series.styleGuide' — the series style guide (tense/POV/rating/reading level)-// - 'series.arc.tickingClock' — the series arc's ticking clock-// - 'reverseOutline' — the cached reverse-outline scene segmentation (#1286);-// scenes carry components/povCharacter/charactersPresent.-// The runner fetches it (gated on this source) and injects-// `ctx.reverseOutline` (the scenes array).-// - 'reverseOutline.plotlines' — the cached reverse-outline's PLOTLINE list (#1286):-// `[{ id, label, kind, color }]` plus the per-scene-// `plotlineId`/`secondaryPlotlineId` tags. The runner fetches-// the outline (gated on this source) and injects-// `ctx.reverseOutlinePlotlines`. The plot-structure check (#1310)-// reconciles dropped subplots against these tagged plotlines —-// which start and then fizzle without a resolution scene.-// - 'series.arc.readerMap' — the series arc's authored reader-map (#1299): the-// writer-logged hooks (questions planted) and payoffs-// (their resolutions). The Chekhov check reconciles its-// detected setups/payoffs against these authored ones.-// - 'editorialArcs' — the detected per-character arc directions from the series-// editorial analysis aggregate (#1295). The runner fetches it-// (gated on this source) and injects `ctx.editorialArcs`-// (`[{ name, arcDirection, issueCount, isProtagonist }]`). This-// is the coarse, DETECTED arc signal — distinct from the-// AUTHORED `series.characterArcs` model below.-// - 'series.characterArcs' — the AUTHORED per-character story arcs (#1293):-// `series.characterArcs[]` (`{ characterId, characterName,-// want, need, startState, endState, transitions[] }`). The-// arc.transitions check reconciles detected change moments-// against these authored transitions + flat-arc warnings.-// - 'storyboard.shots' — the per-issue storyboard shot lists-// (`stages.storyboards.scenes[].shots[]`) the-// visual-continuity check (#1315) reasons over:-// each shot carries `shotType` / `screenDirection`-// / `continuityFromShotId` (server/lib/shotGrammar.js).-// Served off the already-loaded `ctx.issues` (no-// extra I/O); the runner injects `ctx.storyboardScenes`-// (a flat list of `{ issueNumber, scene }` for every-// issue that has storyboard scenes).-// - 'comicScript' — every issue's AUTHORITATIVE comic content, keyed by-// issue number: the edited comic-pages split-// (`stages.comicPages.pages[]`) when present, else the-// generated `stages.comicScript.output`. The-// lettering-density check (#1313) counts per-panel/per-page-// word + balloon load over it (caption/dialogue/SFX only).-// Both comic-source checks read the same parsed pages via-// `comicLetteringIssues(ctx.issues)` (`[{ number, pages }]`);-// the runner fingerprints ONLY the lettering fields for this-// token, so a visual-description edit doesn't stale a-// lettering finding.-// - 'comicScript.pacing' — the same parsed comic pages, for the page-turn-beats-// LLM check (#1314), which reads each panel's visual-// `description` (+ caption/dialogue/SFX text) for its prompt-// digest. Distinct token from 'comicScript' because that-// broader read means a description edit must stale a page-turn-// finding while the lettering token stays put (and vice-versa).-// - 'comicScript.layout' — LAYOUT ONLY (per-page panel COUNT) for the panel-rhythm-// check (#1314), which reads nothing but counts. Separate from-// 'comicScript.pacing' so a text-only edit (reword a caption /-// description without adding/removing a panel) does NOT stale a-// rhythm finding — the splash/crowding/grid verdict can't have-// changed. All three comic tokens share `ctx.issues` (no extra I/O).-export const EDITORIAL_SOURCES = Object.freeze([- 'manuscript',- 'canon',- 'continuityBible',- 'series.styleGuide',- 'series.arc.tickingClock',- 'series.arc.readerMap',- // The authored foreshadowing ledger (#2172): the arc-overview-emitted- // plant → reinforce → payoff seeds the Chekhov check reconciles its detected- // setups/payoffs against. Lives on the already-loaded series record (no extra- // I/O); fingerprinting it stales Chekhov findings when the author edits the ledger.- 'series.arc.foreshadowing',- 'series.arc.themes',- // The author-supplied real-world fact reference the opt-in research.fact-accuracy- // check reconciles the prose against (#1588). Lives on the already-loaded series- // record (no extra I/O); fingerprinting it stales fact findings when the author- // edits the reference.- 'series.factReference',- 'reverseOutline',- 'reverseOutline.plotlines',- 'editorialArcs',- 'series.characterArcs',- 'storyboard.shots',- 'comicScript',- 'comicScript.pacing',- 'comicScript.layout',- // Each issue's PROSE-stage text SPECIFICALLY (#1589) — NOT the default manuscript- // precedence (comicScript ▸ teleplay ▸ prose), which for a hybrid issue returns- // the comic script. The comic↔prose-sync check reads this to compare prose against- // the comic; fingerprinting it separately means a prose edit stales a sync finding- // without a comic-only edit doing so (and vice-versa, via comicScript.pacing).- 'prose',-]);--// Default per-run finding cap for user-defined checks (#1346) — mirrors the-// built-in LLM checks' `maxFindings` default so a long manuscript can't flood-// the review. Defined up here so the custom-check prompt builder and config-// schema (both below) share one source.-export const CUSTOM_CHECK_MAX_FINDINGS_DEFAULT = 12;--// The serializable config-field types a check can declare for its UI form.-// `configSchema` (a Zod schema) stays the validation authority on the server;-// `configFields` is the wire-safe *render* descriptor the Editorial Checks UI-// reads to build the per-check config form (the Zod schema can't cross the wire).-// Keep this in lockstep with the controls EditorialCheckCard's ConfigField-// renders — only advertise a type the UI can actually draw (no 'select' until-// the <select> control + an `options` contract land).-export const CHECK_FIELD_TYPES = Object.freeze(['number', 'boolean', 'text']);--// Stage name for the info-dumping LLM check. The prompt ships in-// data.reference/prompts/stages/ and its config in stage-config.json; both-// propagate to existing installs via setup-data.js (missing-file copy +-// JSON_MERGE_TARGETS stage merge), so no migration is needed for a NEW stage.-export const INFO_DUMPING_STAGE = 'pipeline-editorial-info-dumping';--// Stage names for the two object-attachment LLM checks (#1288). Like the-// info-dumping stage, each prompt ships in data.reference/prompts/stages/ and-// its config in stage-config.json; both propagate to fresh installs via-// setup-data.js and to existing installs via migration 094 (boot runs-// migrations but NOT setup-data, so the migration is required — see-// scripts/migrations/094-object-attachment-check-stages.js).-export const OBJECT_MOTIVATION_STAGE = 'pipeline-editorial-object-motivation';-export const OBJECT_BACKSTORY_STAGE = 'pipeline-editorial-object-backstory';--// Stage name for the object weight-proportionality LLM check (#1624): judges-// whether an object's narrative weight (established backstory + payoff depth)-// matches its prominence in the prose — flagging a minor object given a heavy-// backstory ("a one-line locket with a 3-issue origin") or a climactic object-// with no lineage to earn it ("a heirloom that decides the finale, never set-// up"). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration-// 143 (boot runs migrations but NOT setup-data, so the migration is required).-// Like the two object-attachment checks above it feeds the canon's per-object-// significance/attachment summary as context and reads the stitched manuscript-// to weigh prose prominence against that established weight.-export const OBJECT_WEIGHT_STAGE = 'pipeline-editorial-object-weight-proportionality';--// Stage name for the style-guide conformance LLM check (#1303). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 096 (boot runs-// migrations but NOT setup-data, so the migration is required).-export const STYLE_CONFORMANCE_STAGE = 'pipeline-editorial-style-conformance';--// Stage name for the protagonist-interiority LLM check (#1294). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 099 (boot runs-// migrations but NOT setup-data, so the migration is required).-export const INTERIORITY_STAGE = 'pipeline-editorial-interiority';--// Stage name for the Chekhov's-guns setup/payoff LLM check (#1299). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 100 (boot runs-// migrations but NOT setup-data, so the migration is required).-export const CHEKHOV_STAGE = 'pipeline-editorial-chekhov';--// Stage name for the premature-reveal editorial LLM check (#2178 — CWQE Phase-// 13). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration-// 168 (boot runs migrations but NOT setup-data, so the migration is required).-export const PREMATURE_REVEAL_STAGE = 'pipeline-editorial-premature-reveal';--// Render the reveal-gated canon (#2178) into a compact text block the-// premature-reveal check passes alongside the manuscript, so the model knows-// which facts are SECRETS not yet due and when each is meant to surface. Each-// row names the entry, its reveal issue (or hard spoiler), the spoiler-free-// surface stand-in the reader IS allowed to see, and the underlying fact that-// must NOT leak early. Pure + deterministic so it's unit-testable and its token-// cost counts into the per-chunk overhead. Returns '' when no canon is-// reveal-gated (the check gates on `canonHasRevealGated` so this won't be-// called with an empty set, but the guard keeps it safe).-export function revealGatedCanonSummary(canon) {- const rows = revealGatedCanonRows(canon);- if (!rows.length) return '';- const lines = rows.map((r) => {- const when = r.spoiler- ? 'HARD SPOILER — must not appear in ANY drafted issue'- : `revealed in Issue ${r.revealIssue} — must not appear before then`;- const surface = r.surfaceDescriptor- ? ` Pre-reveal, the reader may only know: "${r.surfaceDescriptor}".`- : '';- const fact = r.fact ? ` The gated fact (must NOT leak early): ${r.fact}.` : '';- return `- ${r.kind} "${r.name}" (${when}).${surface}${fact}`;- });- return 'Reveal-gated canon (these facts are deliberately withheld — flag any that a first-time reader would '- + 'learn from the prose before the fact is due):\n' + lines.join('\n');-}--// Render reveal-gated canon (#2178) as AUTHORED PAYOFFS for the Chekhov check —-// a gated entry's `revealIssue` is effectively an authored payoff point (the-// issue where the withheld fact is meant to fire). Folded into the Chekhov-// `authoredSetups` block so the check can flag a reveal that arrives with zero-// prior setup (an orphaned payoff). Only NUMERIC reveal gates render — a hard-// `spoiler` has no scheduled payoff issue to reconcile against. Returns '' when-// no numeric-gated entry exists (the block renders nothing). Pure.-export function revealGatedPayoffsSummary(canon) {- const rows = revealGatedCanonRows(canon).filter((r) => Number.isInteger(r.revealIssue));- if (!rows.length) return '';- const lines = rows.map((r) => {- const what = r.fact || `the withheld fact about ${r.kind} "${r.name}"`;- return `- ${r.kind} "${r.name}" — reveal-gated fact due to pay off in Issue ${r.revealIssue}: ${what}`;- });- return 'Authored reveal-gated payoffs (each gated fact is meant to be revealed — fire — in its named issue; '- + 'flag a reveal that arrives with no prior setup):\n' + lines.join('\n');-}--// Stage name for the chapter-ending cliffhanger LLM check (#1298). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 102 (boot runs-// migrations but NOT setup-data, so the migration is required).-export const ENDINGS_CLIFFHANGER_STAGE = 'pipeline-editorial-endings-cliffhanger';--// Render the authored reader-map hooks/payoffs (#1299) into a compact text block-// the Chekhov check passes alongside the manuscript so the model reconciles its-// DETECTED setups/payoffs against what the writer has already LOGGED — e.g. an-// authored hook with no detected payoff, or a detected payoff the writer never-// logged. Pure + deterministic so it's unit-testable and so its token cost can be-// counted into the per-chunk overhead. Returns '' when nothing is authored (the-// prompt's `{{#authoredSetups}}` section then renders nothing).-// Shared preamble for the authored-entry renderers below: an entry's-// `label — note` (or whichever is present), '' when neither is usable so-// callers can `.filter(Boolean)`.-function entryLabelNoteText(e) {- const label = typeof e?.label === 'string' ? e.label.trim() : '';- const note = typeof e?.note === 'string' ? e.note.trim() : '';- return label && note ? `${label} — ${note}` : (label || note);-}--// Render one reader-map entry (hook or payoff) to a `- text (arc position N)` line.-// Shared by authoredSetupPayoffSummary + authoredPayoffsSummary. Returns '' for an-// entry with no usable label/note so callers can `.filter(Boolean)`.-function renderReaderMapEntryLine(e) {- const text = entryLabelNoteText(e);- if (!text) return '';- // A coarse expected-location hint so the model can reason about WHERE an- // authored hook should have paid off (reconciliation signal, #1299).- const pos = Number.isFinite(e?.atArcPosition) ? ` (arc position ${e.atArcPosition})` : '';- return `- ${text}${pos}`;-}--// Render one foreshadowing-ledger entry (#2172) to a `- text (plant issue N →-// reinforced issue M → payoff issue P)` line so the Chekhov check reconciles-// its detected plants/payoffs against the author-declared ledger instead of-// inferring every seed from scratch. Returns '' for an entry with no usable-// label/note so callers can `.filter(Boolean)`.-function renderForeshadowingEntryLine(e) {- const text = entryLabelNoteText(e);- if (!text) return '';- const span = [];- if (Number.isFinite(e?.plantIssue)) span.push(`plant issue ${e.plantIssue}`);- if (Array.isArray(e?.reinforceIssues) && e.reinforceIssues.length) {- span.push(`reinforced issue ${e.reinforceIssues.join(', ')}`);- }- if (Number.isFinite(e?.payoffIssue)) span.push(`payoff issue ${e.payoffIssue}`);- return span.length ? `- ${text} (${span.join(' → ')})` : `- ${text}`;-}--// Build the authored-foreshadowing-ledger block (#2172). Exported for the-// Chekhov check + unit tests; returns '' when nothing is authored so the-// prompt's `{{#authoredSetups}}` section renders nothing.-export function authoredForeshadowingSummary(foreshadowing) {- const entries = Array.isArray(foreshadowing) ? foreshadowing : [];- const lines = entries.map(renderForeshadowingEntryLine).filter(Boolean);- if (!lines.length) return '';- return `Authored foreshadowing ledger (planted seeds the writer logged — plant → reinforce → payoff):\n${lines.join('\n')}`;-}--// `foreshadowing` (#2172) is the author-declared plant→reinforce→payoff ledger-// on `series.arc.foreshadowing`; it's folded into the SAME authored-setups-// block the reader-map hooks/payoffs render into, so the Chekhov prompt-// consumes it through its existing `{{#authoredSetups}}` section without a-// template change.-export function authoredSetupPayoffSummary(readerMap, foreshadowing) {- const hooks = Array.isArray(readerMap?.hooks) ? readerMap.hooks : [];- const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];- const hookLines = hooks.map(renderReaderMapEntryLine).filter(Boolean);- const payoffLines = payoffs.map(renderReaderMapEntryLine).filter(Boolean);- const ledgerBlock = authoredForeshadowingSummary(foreshadowing);- if (!hookLines.length && !payoffLines.length && !ledgerBlock) return '';- const parts = [];- if (hookLines.length) parts.push(`Authored hooks (questions the writer planted):\n${hookLines.join('\n')}`);- if (payoffLines.length) parts.push(`Authored payoffs (resolutions the writer logged):\n${payoffLines.join('\n')}`);- if (ledgerBlock) parts.push(ledgerBlock);- return parts.join('\n\n');-}--// Render ONLY the authored reader-map payoffs (#1583) — the resolutions the writer-// LOGGED that the reader was promised. The climax / resolution-power check passes-// this (NOT authoredSetupPayoffSummary, which also bundles hooks) so the prompt's-// "payoffs the climax should deliver" framing stays accurate: a hook is a question-// the writer planted, not a climax obligation, so feeding hooks here would risk the-// model flagging an ordinary unanswered hook as a missing climax resolution. Pure +-// deterministic so it's unit-testable and its token cost can be counted into the-// per-chunk overhead. Returns '' when no payoff is authored (the prompt's-// `{{#authoredPayoffs}}` section then renders nothing and the check reasons from the-// prose + themes alone).-export function authoredPayoffsSummary(readerMap) {- const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];- const payoffLines = payoffs.map(renderReaderMapEntryLine).filter(Boolean);- if (!payoffLines.length) return '';- return `Authored payoffs (resolutions the writer logged — what the reader was promised):\n${payoffLines.join('\n')}`;-}--// Stage name for the cliché / dead-metaphor / overwriting LLM check (#1308).-// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs-// via setup-data.js) and migrates to existing installs via migration 101 (boot-// runs migrations but NOT setup-data, so the migration is required). The-// deterministic siblings (prose.cliches, prose.modifier-stacking) need no stage.-export const DEAD_METAPHOR_STAGE = 'pipeline-editorial-dead-metaphor';--// Stage names for the four LLM prose anti-pattern checks (#1300). Each prompt-// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migrations 103–106 (boot-// runs migrations but NOT setup-data, so the migration is required — see-// scripts/migrations/103-…js … 106-…js). The deterministic sibling-// (prose.italic-thoughts) needs no stage.-export const OPENING_START_STAGE = 'pipeline-editorial-opening-start';-export const MIRROR_DESCRIPTION_STAGE = 'pipeline-editorial-mirror-description';-export const DIALOGUE_PLEASANTRIES_STAGE = 'pipeline-editorial-dialogue-pleasantries';-export const KILL_YOUR_DARLINGS_STAGE = 'pipeline-editorial-kill-your-darlings';--// Stage name for the adversarial-cuts prose-tightening LLM check (#2168). Ships-// in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js); new file so no migration needed. Asks a ruthless editor-// persona to cut 8–12% of the text, classifying each cut (FAT, REDUNDANT,-// OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL). Safe types (OVER-EXPLAIN, REDUNDANT)-// can be batch-applied mechanically.-export const ADVERSARIAL_CUTS_STAGE = 'pipeline-editorial-adversarial-cuts';--// The six cut types the adversarial-cuts check returns, ordered by safe-to-auto--// apply (the first two are the "safe majority" per the design doc). The applier-// defaults to OVER-EXPLAIN + REDUNDANT only; other types require manual review.-export const CUT_TYPES = Object.freeze([- 'OVER-EXPLAIN',- 'REDUNDANT',- 'FAT',- 'GENERIC',- 'TELL',- 'STRUCTURAL',-]);-// The subset that can be auto-applied without manual review.-export const SAFE_CUT_TYPES = Object.freeze(['OVER-EXPLAIN', 'REDUNDANT']);--// Stage names for the two scene-grounding LLM checks (#1309): sensory balance-// (all-visual / sensory-bare scenes) and white-room (ungrounded, setting-less-// scenes). Each prompt ships in data.reference/prompts/stages/ + stage-config.json-// (fresh installs via setup-data.js) and migrates to existing installs via-// migration 107 (boot runs migrations but NOT setup-data, so the migration is-// required). Both consume the reverse-outline scene segmentation as context and-// degrade to a whole-issue manuscript scan when no outline exists.-export const SENSORY_BALANCE_STAGE = 'pipeline-editorial-sensory-balance';-export const WHITE_ROOM_STAGE = 'pipeline-editorial-white-room';--// Stage name for the interiority-balance LLM check (#1623): visually dense but-// emotionally empty scenes — heavy on description, light on POV reaction. Ships-// in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 142 (boot runs-// migrations but NOT setup-data, so the migration is required). Like the two-// scene-grounding checks above it consumes the reverse-outline scene-// segmentation as context and degrades to a whole-issue manuscript scan when no-// outline exists.-export const INTERIORITY_BALANCE_STAGE = 'pipeline-editorial-interiority-balance';--// Stage name for the character-arc transition-detection LLM check (#1293). Ships-// in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 109 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the-// stitched manuscript plus the reverse-outline scene map and the AUTHORED-// per-character arcs to surface genuine change moments + flat-arc warnings.-export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';--// Stage name for the character-arc regression / premature-closure LLM check-// (#1619). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration 141-// (boot runs migrations but NOT setup-data, so the migration is required). Reads-// the stitched manuscript plus the reverse-outline scene map and the AUTHORED-// per-character arcs, tracks each character's progress across the issues, and-// flags regression (growth then an unmotivated revert), a circular arc (ends-// where it began), or premature closure (an arc resolved early then flat for the-// rest of the series). Complements arc.transitions (which detects the change-// MOMENTS) by judging the SHAPE of each character's progress across the whole arc.-export const ARC_REGRESSION_STAGE = 'pipeline-editorial-arc-regression';--// Stage name for the telling-not-showing-emotion LLM check (#1306). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 110 (boot runs-// migrations but NOT setup-data, so the migration is required). The deterministic-// copy-edit siblings (prose.filter-words, prose.crutch-words, prose.adverbs,-// prose.passive-voice, prose.repeated-gestures, prose.word-echoes,-// prose.sentence-rhythm) need no stage.-export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';--// Stage names for the two dialogue-craft LLM checks (#1307): on-the-nose /-// subtext-free dialogue, and per-character voice distinctiveness. Each prompt-// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migrations 112–113 (boot-// runs migrations but NOT setup-data, so the migration is required). The-// deterministic siblings (dialogue.said-bookisms, dialogue.attribution-clarity)-// need no stage.-export const ON_THE_NOSE_STAGE = 'pipeline-editorial-on-the-nose';-export const VOICE_DISTINCTIVENESS_STAGE = 'pipeline-editorial-voice-distinctiveness';--// Finding subtypes for `dialogue.on-the-nose` (#1626) — the stage prompt classifies-// each subtext-free line into *why* it reads on-the-nose so the writer gets specific,-// actionable feedback instead of a flat "on-the-nose" label. Surfaced on the finding-// (and persisted comment) as `subtype`; the runner validates the model's value against-// this allow-list and drops anything off-list (→ null) so a stray label can't leak through.-export const ON_THE_NOSE_SUBTYPES = ['exposition', 'emotion-tell', 'relationship-report'];--// Stage name for the narrator voice / tone-consistency LLM check (#1586) — the-// narration-level sibling of voice-distinctiveness (which covers per-CHARACTER-// dialogue). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration 134-// (boot runs migrations but NOT setup-data, so the migration is required).-export const VOICE_CONSISTENCY_STAGE = 'pipeline-editorial-voice-consistency';--// Render each canon character's authored voice fields into a compact text block-// the voice-distinctiveness LLM check passes alongside the manuscript, so the-// model can flag lines that contradict a character's recorded speechPattern /-// speechAccent (closing the "voice fields feed generation only" gap, #1307) and-// reason about whether characters sound distinct from one another. Pure +-// deterministic so it's unit-testable and its token cost can be counted into the-// per-chunk overhead. Returns '' when no character carries a voice field (the-// prompt's {{#voiceProfiles}} section then renders nothing and the check-// degrades to a pure interchangeability scan).-export function characterVoiceProfiles(canon) {- const chars = Array.isArray(canon?.characters) ? canon.characters : [];- const lines = [];- for (const c of chars) {- if (!c || typeof c !== 'object') continue;- const name = typeof c.name === 'string' ? c.name.trim() : '';- if (!name) continue;- const pattern = typeof c.speechPattern === 'string' ? c.speechPattern.trim() : '';- const accent = typeof c.speechAccent === 'string' ? c.speechAccent.trim() : '';- if (!pattern && !accent) continue;- const parts = [`- ${name}`];- if (pattern) parts.push(`speech pattern: ${pattern}`);- if (accent) parts.push(`accent/dialect: ${accent}`);- lines.push(parts.join(' — '));- }- if (!lines.length) return '';- return `Authored character voices (canon speechPattern / speechAccent):\n${lines.join('\n')}`;-}--// Render the series style guide's INTENDED narrative voice — the authored `tone`-// words (e.g. "witty", "grim", "lyrical") — into a compact block the narrator-// voice-consistency check (#1586) passes alongside the manuscript, so the model-// can measure each issue's narration against the declared intent, not just-// against the other issues. Pure + deterministic so it's unit-testable and its-// token cost counts into the per-chunk overhead. Type-guarded (styleGuide rides-// peer sync, so a hand-edited / older-peer guide could carry a non-array `tone`-// or non-string entries). Returns '' when the guide declares no tone (the-// prompt's {{#intendedVoice}} section then renders nothing and the check degrades-// to a pure cross-issue consistency scan).-export function intendedVoiceSummary(styleGuide) {- const raw = Array.isArray(styleGuide?.tone) ? styleGuide.tone : [];- const tone = raw- .filter((t) => typeof t === 'string' && t.trim())- .map((t) => t.trim());- if (!tone.length) return '';- return `Style guide — intended narrative tone/voice: ${tone.join(', ')}.`;-}--// Render each canon character's contradiction-relevant FACTS into a compact text-// block the timeline / canon-contradiction check (#1581) passes alongside the-// manuscript, so the model can reconcile the prose against the established bible:-// a character the bible records at age 16 who reads "in her 30s" on the page, a-// role/status the prose contradicts, or a description the prose breaks. Pure +-// deterministic so it's unit-testable and its token cost can be counted into the-// per-chunk overhead. Type-guarded throughout (canon rides peer sync, so a-// hand-edited / older-peer character could carry a non-string field a bare-// `.trim()` would throw on — and `age` is commonly stored as a number). Reuses-// `characterNameTokens` so name + aliases render with the same trim/de-dup the-// matcher uses. Returns '' when no character carries both a usable name AND a-// renderable fact (the prompt's `{{#canonStates}}` section then renders nothing-// and the check reasons from the prose + scene map alone).-const CANON_STATE_FACT_CHARS = 240;-export function canonCharacterStatesSummary(canon) {- const chars = Array.isArray(canon?.characters) ? canon.characters : [];- const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');- const rows = [];- for (const c of chars) {- if (!c || typeof c !== 'object') continue;- // Require a real name — an alias-only row isn't a named character (mirrors- // canonRosterNamesSummary, which skips nameless rows). characterNameTokens then- // returns the trimmed name first, followed by de-duped aliases.- if (typeof c.name !== 'string' || !c.name.trim()) continue;- const [name, ...aliases] = characterNameTokens(c);- const facts = [];- // `age` is often a number in the bible — accept a finite number or a non-empty string.- const age = typeof c.age === 'number' && Number.isFinite(c.age) ? String(c.age) : cleanStr(c.age);- if (age) facts.push(`age ${age}`);- const role = cleanStr(c.role);- if (role) facts.push(`role: ${role}`);- const status = cleanStr(c.status);- if (status) facts.push(`status: ${status}`);- // physicalDescription is the richer bible field; fall back to a generic description.- const description = (cleanStr(c.physicalDescription) || cleanStr(c.description)).slice(0, CANON_STATE_FACT_CHARS);- if (description) facts.push(`described as: ${description}`);- if (!facts.length) continue;- const who = aliases.length ? `${name} (also: ${aliases.join(', ')})` : name;- rows.push(`- ${who} — ${facts.join('; ')}`);- }- if (!rows.length) return '';- return `Canon character facts (the established bible — reconcile the prose against these):\n${rows.join('\n')}`;-}--// Render each canon character's PERSONALITY-relevant traits into a compact text-// block the character-consistency check (#1582) passes alongside the manuscript,-// so the model can flag an UNEARNED shift: a reserved character suddenly cracking-// jokes, an established fear/allergy silently contradicted, a voice that drifts-// off the authored speech pattern. Distinct from `canonCharacterStatesSummary`-// (age/role/status/described-as — the contradiction-of-FACTS grounding the-// timeline check reads) and from `characterVoiceProfiles` (speech only): this is-// the temperament/traits grounding. Pure + deterministic so it's unit-testable-// and its token cost can be counted into the per-chunk overhead. Type-guarded-// throughout (canon rides peer sync, so a hand-edited / older-peer character-// could carry a non-string field a bare `.trim()` would throw on, and-// mannerisms/likes/dislikes are commonly arrays). Reuses `characterNameTokens` so-// name + aliases render with the same trim/de-dup the matcher uses. Returns ''-// when no character carries both a usable name AND a renderable trait (the-// prompt's `{{#canonTraits}}` section then renders nothing and the check reasons-// from the prose alone).-const CANON_TRAIT_FACT_CHARS = 240;-export function canonCharacterTraitsSummary(canon) {- const chars = Array.isArray(canon?.characters) ? canon.characters : [];- const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');- // mannerisms / likes / dislikes are commonly arrays of short strings in the- // bible; render the first few as a comma list. Tolerates a plain string too.- const cleanList = (v) => {- if (typeof v === 'string') return v.trim();- if (!Array.isArray(v)) return '';- return v.map((x) => (typeof x === 'string' ? x.trim() : '')).filter(Boolean).slice(0, 5).join(', ');- };- const rows = [];- for (const c of chars) {- if (!c || typeof c !== 'object') continue;- // Require a real name — an alias-only row isn't a named character (mirrors- // canonCharacterStatesSummary). characterNameTokens returns the trimmed name- // first, followed by de-duped aliases.- if (typeof c.name !== 'string' || !c.name.trim()) continue;- const [name, ...aliases] = characterNameTokens(c);- const facts = [];- const personality = cleanStr(c.personality).slice(0, CANON_TRAIT_FACT_CHARS);- if (personality) facts.push(`personality: ${personality}`);- const specialTraits = cleanStr(c.specialTraits).slice(0, CANON_TRAIT_FACT_CHARS);- if (specialTraits) facts.push(`fixed traits: ${specialTraits}`);- const mannerisms = cleanList(c.mannerisms);- if (mannerisms) facts.push(`mannerisms: ${mannerisms}`);- const motivations = cleanStr(c.motivations).slice(0, CANON_TRAIT_FACT_CHARS);- if (motivations) facts.push(`motivations: ${motivations}`);- const likes = cleanList(c.likes);- if (likes) facts.push(`likes: ${likes}`);- const dislikes = cleanList(c.dislikes);- if (dislikes) facts.push(`dislikes: ${dislikes}`);- const speechPattern = cleanStr(c.speechPattern);- if (speechPattern) facts.push(`speech: ${speechPattern}`);- // Authored character-framework fields (CWQE Phase 10, #2175) — the Lie the- // character believes, the Want (external goal), the Need (the Truth), and- // the declared arc type. Surfacing these lets the consistency / arc checks- // reconcile the prose against the PLAN (does the character overcome the Lie,- // pursue the Want, arrive at the Need per the declared arc?) instead of- // inferring the intended arc from the prose alone.- const lie = cleanStr(c.lie).slice(0, CANON_TRAIT_FACT_CHARS);- if (lie) facts.push(`believes (Lie): ${lie}`);- const want = cleanStr(c.want).slice(0, CANON_TRAIT_FACT_CHARS);- if (want) facts.push(`wants: ${want}`);- const need = cleanStr(c.need).slice(0, CANON_TRAIT_FACT_CHARS);- if (need) facts.push(`needs (Truth): ${need}`);- const arcType = cleanStr(c.arcType);- if (arcType) facts.push(`declared arc: ${arcType}`);- if (!facts.length) continue;- const who = aliases.length ? `${name} (also: ${aliases.join(', ')})` : name;- rows.push(`- ${who} — ${facts.join('; ')}`);- }- if (!rows.length) return '';- return `Canon character traits (the established bible — a shift away from these must be earned on the page):\n${rows.join('\n')}`;-}--// Human-readable labels for the continuity-bible fact categories (#1305). Inlined-// (not imported from server/services/pipeline/continuityBible.js) to keep this-// registry PURE — that module pulls in I/O + an SSE runner. Mirrors its-// `FACT_CATEGORIES`; a category absent from this map falls back to its raw id, so-// a new bible category still renders (just without a prettied label) until it's-// added here.-const CONTINUITY_CATEGORY_LABELS = Object.freeze({- physical: 'Physical traits',- age: 'Ages & birthdays',- timeline: 'Dates & elapsed time',- location: 'Locations & geography',- possession: 'Possessions & wardrobe',- 'world-rule': 'World rules',- knowledge: 'Who knows what, when',-});--// Render the continuity-bible facts ledger (#1305) into a compact text block the-// timeline / canon-contradiction check (#1581) passes alongside the manuscript, so-// the model reconciles the prose against the established ground-truth facts the-// bible already extracted — ages/birthdays, dates & elapsed time, locations, world-// rules, who-knows-what — which the shallow per-character canon fields don't carry.-// Facts are grouped by category (in the stable category order) and tagged with the-// issue they were established in, when known, so the model can reason about WHEN a-// fact held. Pure + deterministic so it's unit-testable and its token cost can be-// counted into the per-chunk overhead. Type-guarded throughout (the ledger rides-// peer sync, so a hand-edited / older-peer fact could carry a non-string field).-// Returns '' when there are no usable facts (the prompt's `{{#continuityLedger}}`-// section then renders nothing and the check falls back to the canon fields + prose).-export function continuityLedgerSummary(facts) {- const list = Array.isArray(facts) ? facts : [];- const byCategory = new Map();- for (const f of list) {- if (!f || typeof f !== 'object') continue;- const category = typeof f.category === 'string' ? f.category.trim() : '';- const subject = typeof f.subject === 'string' ? f.subject.trim() : '';- const statement = typeof f.statement === 'string' ? f.statement.trim() : '';- if (!category || !statement) continue;- const where = Number.isInteger(f.issueNumber) ? ` (Issue ${f.issueNumber})` : '';- const line = subject ? `- ${subject}: ${statement}${where}` : `- ${statement}${where}`;- if (!byCategory.has(category)) byCategory.set(category, []);- byCategory.get(category).push(line);- }- if (!byCategory.size) return '';- // Render known categories in their canonical order first, then any unknown- // category (a newer-peer addition) after, so the block is stable + complete.- const order = [...Object.keys(CONTINUITY_CATEGORY_LABELS), ...byCategory.keys()];- const seen = new Set();- const blocks = [];- for (const category of order) {- if (seen.has(category) || !byCategory.has(category)) continue;- seen.add(category);- const label = CONTINUITY_CATEGORY_LABELS[category] || category;- blocks.push(`${label}:\n${byCategory.get(category).join('\n')}`);- }- return `Continuity bible facts (established ground truth — reconcile the prose against these):\n\n${blocks.join('\n\n')}`;-}--// Stage name for the plot-structure & momentum LLM check (#1310). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 111 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the-// stitched manuscript plus the reverse-outline scene map + plotline coverage and-// the authored reader-map/arc to surface macro pathologies — passive protagonist,-// deus ex machina, idiot plot, flat/unclear stakes, sagging middle, and dropped-// subplots reconciled against the tagged plotlines.-export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';--// Stage names for the worldbuilding-doctrine LLM check pair (#2175). Both ship in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and reach existing installs via the multi-stage seed migration-// 167 (boot runs migrations but NOT setup-data, so the migration is required or-// the check throws "Stage not found" on first run). Both reconcile the prose against the-// canon world summary (`canonWorldSummary`) + the continuity-bible world-rule-// facts so an established-and-planted rule is NOT flagged:-// - unforeshadowed-solution: a plot problem solved by a rule/power the reader was-// never shown — deus ex machina's worldbuilding sibling.-// - cost-free-power: an ability used at a decisive moment with no cost/limitation-// on the page (violates "limitations > powers").-export const WORLD_UNFORESHADOWED_SOLUTION_STAGE = 'pipeline-editorial-world-unforeshadowed-solution';-export const WORLD_COST_FREE_POWER_STAGE = 'pipeline-editorial-world-cost-free-power';--// Stage name for the series-wide pacing / intensity escalation-curve LLM check-// (#1618). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration 140-// (boot runs migrations but NOT setup-data, so the migration is required). Reads-// the stitched manuscript plus the reverse-outline scene map and a deterministic-// per-issue conflict-marker density tally, and scores the per-issue dramatic-// intensity to flag a flat curve (issue 1 ≈ issue N), a front-loaded climax (the-// biggest beat lands early), or stakes that plateau / de-escalate across the arc.-// Complements plot.structure-momentum (flat stakes as one signal among many) by-// focusing the lens on the whole-series escalation shape.-export const PACING_ESCALATION_STAGE = 'pipeline-editorial-pacing-escalation-curve';--// Stage name for the timeline / canon-contradiction LLM check (#1581). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 129 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the stitched-// manuscript plus the established canon character facts, the reverse-outline scene-// ordering, and the authored per-character arcs to surface internal contradictions-// — a dead character who reappears alive, an age that contradicts the bible, or an-// impossible chronology.-export const TIMELINE_CONTRADICTION_STAGE = 'pipeline-editorial-timeline-contradiction';--// Stage name for the research / fact-accuracy LLM check (#1588). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 135 (boot runs-// migrations but NOT setup-data, so the migration is required). Reconciles the-// stitched manuscript against the author-supplied real-world fact reference-// (`series.factReference`) — a prose claim that contradicts a documented external-// fact (geography, history, physics/physiology). Opt-in and gated on the-// `series.factCritical` flag so it never fires on pure fantasy.-export const FACT_ACCURACY_STAGE = 'pipeline-editorial-fact-accuracy';--// Stage name for the character-consistency / unearned-personality-shift LLM check-// (#1582). Ships in data.reference/prompts/stages/ + stage-config.json (fresh-// installs via setup-data.js) and migrates to existing installs via migration 130-// (boot runs migrations but NOT setup-data, so the migration is required). Reads-// the stitched manuscript plus the established canon character TRAITS (personality,-// fixed traits, mannerisms, speech), the reverse-outline scene ordering, and the-// authored per-character arcs — and flags a shift the prose never earns: a reserved-// character cracking jokes with no beat, a fear/allergy silently contradicted, or-// POV knowledge that changes mid-scene with no on-page learning. Reconciles against-// the authored arcs so an intentional, earned transition is NOT flagged.-export const CHARACTER_CONSISTENCY_STAGE = 'pipeline-editorial-character-consistency';--// Stage name for the head-hopping / POV-discipline LLM check (#1311). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 112 (boot runs-// migrations but NOT setup-data, so the migration is required). Distinct from-// pov.justified (#1295, which asks whether each POV character earns an arc); this-// check polices POV *discipline* within a scene — narration that enters another-// character's head or reports what the POV character can't perceive.-export const HEAD_HOPPING_STAGE = 'pipeline-editorial-head-hopping';--// Stage name for the comic page-turn-beats LLM check (#1314). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 117 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads each issue's-// parsed comic-page layout (`comicPageTurnSummary`) plus the authored reveals /-// cliffhangers (`authoredRevealSummary`) and flags big reveals placed where the-// reader sees them early (a page the reader has already been looking at across the-// spread, rather than the first page after a turn). The deterministic sibling-// (comic.panel-rhythm) needs no stage.-export const COMIC_PAGE_TURN_STAGE = 'pipeline-editorial-comic-page-turn';--// Stage name for the theme-coherence / thematic-throughline LLM check (#1317).-// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 115 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the stitched-// manuscript plus the AUTHORED arc themes (series.arc.themes) and the reverse-outline-// scene map, and reconciles whether each declared theme is set up / complicated /-// paid off — surfacing stated-but-undramatized themes, dropped themes, a strong-// emergent theme not in the arc, and a climax that resolves plot but not theme.-export const THEME_COHERENCE_STAGE = 'pipeline-editorial-theme-coherence';--// Render the authored arc themes (#1317) into a compact text block the-// theme-coherence check passes alongside the manuscript, so the model reconciles-// whether the prose actually sets up / complicates / pays off each DECLARED theme-// (vs. stating it but never dramatizing it, or dropping it after the opening).-// Pure + deterministic so it's unit-testable and its token cost can be counted-// into the per-chunk overhead. Returns '' when no themes are authored (the-// prompt's `{{#declaredThemes}}` section then renders nothing and the check still-// runs to detect a strong emergent theme).-export function declaredThemesSummary(themes) {- const lines = (Array.isArray(themes) ? themes : [])- .map((t) => (typeof t === 'string' ? t.trim() : ''))- .filter(Boolean)- .map((t) => `- ${t}`);- if (!lines.length) return '';- return `Declared themes (authored on the story arc):\n${lines.join('\n')}`;-}--// Stage name for the climax / resolution-power LLM check (#1583). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 131 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the stitched-// manuscript plus the authored reader-map payoffs (series.arc.readerMap) and the-// declared themes (series.arc.themes) and the reverse-outline scene ordering, and-// judges whether the CLIMAX is the protagonist's hardest, most active choice (vs.-// a passive climax where an ally rescues them or events simply resolve around-// them) AND whether it resolves the story's core problem/theme (vs. a plot climax-// that lands the action but leaves the emotional/thematic core unanswered).-// Complements plot.structure-momentum (which flags a passive protagonist arc-wide;-// this one focuses the lens on the single payoff scene). The climax can only be-// judged once the whole manuscript is in view, so the run gates its verdict on the-// final part (`finalPart`); degrades to a prose-only scan when no reader-map,-// themes, or outline exist.-export const CLIMAX_AGENCY_STAGE = 'pipeline-editorial-climax-agency';--// Stage name for the emotional-beat / reaction-proportionality LLM check (#1584).-// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 132 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the stitched-// manuscript plus the reverse-outline scene map and judges whether each character's-// emotional reactions are PROPORTIONATE to the magnitude of the events that befall-// them: a high-magnitude event (trauma, death, betrayal, a major loss or win) that-// draws no on-page reaction and is never processed afterward (under-reaction), or a-// minor setback that triggers grief/rage out of all proportion (over-reaction).-// Because an unprocessed event in an early issue can stay unaddressed many issues-// later, the run carries high-magnitude events still awaiting a proportionate-// reaction across chunks (`crossChunkSetup`) so a later part can flag the missing-// payoff; degrades to a prose-only scan when no outline exists.-export const REACTION_PROPORTIONALITY_STAGE = 'pipeline-editorial-reaction-proportionality';--// Stage name for the secondary (non-POV) character-arc LLM check (#1585). Ships-// in data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 133 (boot runs-// migrations but NOT setup-data, so the migration is required). The sibling of-// pov.justified (#1295), which covers POV characters only: this check judges the-// RECURRING NON-POV cast — characters who appear in multiple scenes but never-// hold the viewpoint — and flags those who never change (a flat side character-// who is the same at the end as the start) or who regress without purpose. Reads-// the stitched manuscript plus the reverse-outline scene map (to tally which-// non-POV characters recur and weigh their presence) and the canon roster (so a-// genuinely-minor walk-on isn't held to an arc). Because a flat arc is a-// whole-story claim, the run gates its verdict on the final part (`finalPart`)-// and carries each recurring secondary character's established state forward-// across chunks (`crossChunkSetup`); degrades to a prose-only scan when no-// outline exists.-export const SECONDARY_ARC_STAGE = 'pipeline-editorial-secondary-arc';--// Stage name for the unmodeled-proper-nouns LLM check (#1412). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 116 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the stitched-// manuscript plus the canon roster (names + aliases) and asks the model to surface-// capitalized proper nouns used as apparent CHARACTER names that are absent from-// canon — the LLM-assisted half of roster economy (#1292) the deterministic-// `roster.economy` scan deliberately leaves alone (it can't tell a person from a-// place/org/brand/honorific).-export const UNMODELED_NAMES_STAGE = 'pipeline-editorial-unmodeled-names';--// Stage name for the eyeline-match continuity LLM check (#1466). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 117 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the per-issue-// storyboard shots (`ctx.storyboardScenes`, wired by #1315 — the same source the-// deterministic `visual.shot-continuity` check reads) and asks the model to flag-// eyeline-match breaks WITHIN a scene: two characters in conversation whose gaze-// directions don't reciprocate across the cut, or a described eyeline that-// contradicts the shot's screen direction. The judgment sibling the deterministic-// 180°/shot-type scan deliberately leaves to an LLM (see shotContinuity.js).-export const EYELINE_MATCH_STAGE = 'pipeline-editorial-eyeline-match';--// Stage name for the appearance/prop-continuity LLM check (#1467). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 118 (boot runs-// migrations but NOT setup-data, so the migration is required). Reads the same-// per-issue storyboard shots (`ctx.storyboardScenes`, wired by #1315) the eyeline-// sibling reads and asks the model to DIFF descriptions of the same entity across-// shots WITHIN a scene: a character's wardrobe/appearance that contradicts an-// earlier shot, a prop that appears/vanishes/transforms with nothing removing it,-// or a setting whose weather/time/layout flips with no transition. The semantic-// sibling the deterministic 180°/shot-type scan can't catch (the shot parser-// matches characters by name but never diffs their free-text descriptions).-export const APPEARANCE_CONTINUITY_STAGE = 'pipeline-editorial-appearance-continuity';--// Stage name for the comic ↔ prose synchronization LLM check (#1589). Ships in-// data.reference/prompts/stages/ + stage-config.json (fresh installs via-// setup-data.js) and migrates to existing installs via migration 136 (boot runs-// migrations but NOT setup-data, so the migration is required). For a hybrid-// comic+prose issue it pairs the issue's PROSE (its prose stage) with its-// authoritative COMIC content (description + dialogue + caption + SFX — the same-// fields the `comicScript.pacing` source carries) and asks the model to flag-// SUBSTANTIVE cross-media divergences: a plot beat the prose narrates that no-// panel shows, panel dialogue that contradicts the prose, or a chronology-// disagreement across the two media. Comics legitimately compress and cut, so the-// prompt is tuned to ignore ordinary medium-translation trims.-export const COMIC_PROSE_SYNC_STAGE = 'pipeline-editorial-comic-prose-sync';--// Render the canon roster's names + aliases (#1412) into a compact text block the-// unmodeled-names check passes alongside the manuscript, so the model knows which-// proper nouns are ALREADY modeled (and therefore must NOT be flagged) and only-// surfaces apparent character names absent from this list. Pure + deterministic so-// it's unit-testable and its token cost can be counted into the per-chunk overhead.-// Returns '' when no canon character has a usable name (the prompt's-// `{{#knownCharacters}}` section then renders nothing and EVERY named proper noun in-// the prose is a candidate — exactly right when the bible is empty). Reuses-// `characterNameTokens` so name + aliases render with the same trim/de-dup the-// deterministic matcher uses.-export function canonRosterNamesSummary(canon) {- const chars = Array.isArray(canon?.characters) ? canon.characters : [];- const lines = [];- for (const c of chars) {- // Require a real name — an alias-only row isn't a named character (mirrors- // buildRosterAppearances, which skips nameless rows). characterNameTokens then- // returns the trimmed name first, followed by de-duped aliases.- if (!c || typeof c.name !== 'string' || !c.name.trim()) continue;- const [name, ...aliases] = characterNameTokens(c);- lines.push(aliases.length ? `- ${name} (also: ${aliases.join(', ')})` : `- ${name}`);- }- if (!lines.length) return '';- return `Known characters (already in the story bible — do NOT flag these or their aliases):\n${lines.join('\n')}`;-}--// Render the established WORLD canon (#2175) — the named objects (with their-// significance) and places (with their recurring details) — into a compact text-// block the worldbuilding-doctrine checks pass alongside the manuscript so the-// model can tell a rule/power/artifact the prose ESTABLISHED (and may legitimately-// use) from one that appears out of nowhere. Objects carry the artifacts/powers a-// solution might draw on; places carry the world's physical logic. Prose-// `significance` / `description` / `recurringDetails` are the fields that state-// what a thing DOES and what it costs, so those are what get surfaced. Pure +-// deterministic (unit-testable, token-countable) and type-guarded throughout (the-// canon rides peer sync, so an older/hand-edited row could carry a non-string-// field). Returns '' when no object or place has usable content (the prompt's-// `{{#canonWorld}}` section then renders nothing and the check reasons from the-// prose alone).-export function canonWorldSummary(canon) {- const objects = Array.isArray(canon?.objects) ? canon.objects : [];- const places = Array.isArray(canon?.places) ? canon.places : [];- const trim = (v) => (typeof v === 'string' ? v.trim() : '');- const objectLines = [];- for (const o of objects) {- const name = trim(o?.name);- if (!name) continue;- const detail = trim(o?.significance) || trim(o?.description);- objectLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);- }- const placeLines = [];- for (const p of places) {- const name = trim(p?.name) || trim(p?.slugline);- if (!name) continue;- const detail = trim(p?.recurringDetails) || trim(p?.description);- placeLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);- }- if (!objectLines.length && !placeLines.length) return '';- const blocks = [];- if (objectLines.length) blocks.push(`Named artifacts / objects (with their significance):\n${objectLines.join('\n')}`);- if (placeLines.length) blocks.push(`Named places (with their recurring details):\n${placeLines.join('\n')}`);- // Neutral framing: this is the author's reference for what the world's- // mechanics ARE, so a check can judge internal consistency. It deliberately- // does NOT assert the reader has seen these — each consuming prompt sets that- // interpretation (the unforeshadowed-solution check must still flag a canon- // rule the PROSE never surfaced; the cost-free-power check reads it for the- // costs a system is supposed to carry).- return `World-bible reference (the author's record of the world's artifacts, places, and mechanics — use it to understand what a thing is and does; it is NOT the manuscript and does not prove the reader has seen any of it):\n\n${blocks.join('\n\n')}`;-}--// Render the authored reader-map cliffhangers (#1298) into a compact text block-// the chapter-ending check passes alongside the manuscript so the model-// reconciles its DETECTED endings against the issue-boundary tugs the writer-// already LOGGED — an authored cliffhanger the prose doesn't deliver, or a-// settled ending where the writer planned one. Pure + deterministic so it's-// unit-testable and its token cost can be counted into the per-chunk overhead.-// Returns '' when nothing is authored (the prompt's `{{#authoredCliffhangers}}`-// section then renders nothing). `atIssueBoundary` is the issue the cliffhanger-// caps (the cut falls between it and the next), so it's surfaced as a location hint.-export function authoredCliffhangerSummary(readerMap) {- const cliffs = Array.isArray(readerMap?.cliffhangers) ? readerMap.cliffhangers : [];- const lines = cliffs.map((c) => {- const note = typeof c?.note === 'string' ? c.note.trim() : '';- if (!note) return '';- const at = Number.isFinite(c?.atIssueBoundary) ? ` (ending issue ${c.atIssueBoundary})` : '';- return `- ${note}${at}`;- }).filter(Boolean);- if (!lines.length) return '';- return `Authored cliffhangers (issue-boundary tugs the writer planned):\n${lines.join('\n')}`;-}--// ----------------------------------------------------------------------------// Chapter-ending POV switch (#1298) — deterministic over the reverse-outline POV-// map + the authored reader-map cliffhangers. The editorial rule: in a multi-POV-// story, after a chapter ends on a cliffhanger, the NEXT chapter should cut to a-// DIFFERENT POV character (the cut sustains tension across the break). The LLM-// cliffhanger check above judges WHICH endings are cliffhangers; this check uses-// the writer's AUTHORED cliffhangers as the deterministic trigger so it never-// needs the model. No authored cliffhangers ⇒ nothing to reconcile (no-op);-// single-POV series ⇒ no-op (there's no other POV to cut to).-// -----------------------------------------------------------------------------// Group POV-tagged scenes by issue number, preserving outline (sequence) order-// within each issue and first-seen story order across issues. Scenes without an-// integer issueNumber can't be mapped to a chapter boundary and are dropped.-export function scenesByIssue(scenes) {- const byIssue = new Map();- for (const s of scenes) {- if (!s || typeof s !== 'object') continue;- const n = Number.isInteger(s.issueNumber) ? s.issueNumber : null;- if (n == null) continue;- if (!byIssue.has(n)) byIssue.set(n, []);- byIssue.get(n).push(s);- }- return byIssue;-}--// The POV holder of a scene, trimmed, or '' when untagged.-export const scenePov = (s) => (typeof s?.povCharacter === 'string' ? s.povCharacter.trim() : '');--// The last / first POV-tagged scene of an issue's scene list (sequence-ordered),-// as { name, scene }, or null when no scene in the issue carries a POV.-export function lastPovScene(list) {- for (let i = list.length - 1; i >= 0; i -= 1) {- const name = scenePov(list[i]);- if (name) return { name, scene: list[i] };- }- return null;-}-export function firstPovScene(list) {- for (const s of list) {- const name = scenePov(s);- if (name) return { name, scene: s };- }- return null;-}--// ----------------------------------------------------------------------------// Character-name dissimilarity (#1291) reads cast names + aliases and respects-// locked entries. The pure similarity primitives live in ./nameSimilarity.js;-// the helpers below turn the canon into the flat name list the check walks.-// -----------------------------------------------------------------------------// SEVERITIES is ordered high→…→low (index 0 = most severe). Escalate `base` up-// by `steps` ranks, clamped at the top — a strong collision (near-identical-// spelling, dense first-letter cluster) outranks the check's low floor.-export function escalateSeverity(base, steps) {- const i = SEVERITIES.indexOf(base);- const idx = i === -1 ? SEVERITIES.length - 1 : i;- return SEVERITIES[Math.max(0, idx - Math.max(0, steps))];-}--// The flat list of confusable name tokens for a cast: each character's `name`-// plus every alias, tagged with the owning character (id-or-index), whether that-// character is locked, and whether the token is an alias. Two tokens owned by the-// same character never pair (a name vs. its own alias isn't a reader collision).-export function castNameTokens(ctx) {- const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];- const tokens = [];- chars.forEach((c, idx) => {- if (!c || typeof c !== 'object') return;- const owner = c.id || `idx-${idx}`;- const locked = c.locked === true;- const primary = typeof c.name === 'string' ? c.name.trim() : '';- if (primary) tokens.push({ token: primary, owner, ownerName: primary, locked, isAlias: false });- const aliases = Array.isArray(c.aliases) ? c.aliases : [];- for (const a of aliases) {- const alias = typeof a === 'string' ? a.trim() : '';- if (alias) tokens.push({ token: alias, owner, ownerName: primary || alias, locked, isAlias: true });- }- });- return tokens;-}--// A name token's display label — an alias is annotated with its owning character-// so the finding text and the rename suggestion always name the source.-export const tokenLabel = (t) => (t.isAlias ? `${t.token} (alias of ${t.ownerName})` : t.token);--// How to phrase the rename suggestion given which of the two characters are-// locked — always steer the author toward renaming an UNLOCKED one (#1291).-export function renameSuggestion(a, b) {- if (a.locked && b.locked) {- return `Both ${a.ownerName} and ${b.ownerName} are locked — unlock one to rename it so readers can tell them apart.`;- }- if (a.locked) return `Rename ${b.ownerName} (${a.ownerName} is locked) so it reads less like "${tokenLabel(a)}".`;- if (b.locked) return `Rename ${a.ownerName} (${b.ownerName} is locked) so it reads less like "${tokenLabel(b)}".`;- return `Rename one of ${a.ownerName} / ${b.ownerName} so readers can tell them apart at a glance.`;-}--// ----------------------------------------------------------------------------// Shared scaffolding for the relationship-link checks (#1287). All three walk-// `canon.characters × relationshipLinks`, so the id-bearing character list,-// the id→name lookup, and the link iteration live here once.-// -----------------------------------------------------------------------------// Id-bearing characters + an id→name lookup (falling back to the id when a-// character is unnamed). The three checks index off this same pair.-export function relationshipCanon(ctx) {- const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);- return { chars, nameById: new Map(chars.map((c) => [c.id, c.name || c.id])) };-}--// Yields every relationship link that points somewhere, as { c, link, targetId }.-export function* eachRelationshipLink(chars) {- for (const c of chars) {- for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {- if (link?.targetCharacterId) yield { c, link, targetId: link.targetCharacterId };- }- }-}--// ----------------------------------------------------------------------------// Shared scaffolding for the object-attachment checks (#1288). All three walk-// `canon.objects × attachments`, resolving each attachment's `characterId`-// against the cast, so the id-bearing object/character lists, the id→character-// lookup, and the attachment iteration live here once.-// -----------------------------------------------------------------------------export function attachmentCanon(ctx) {- const objects = (ctx.canon?.objects || []).filter((o) => o && o.id);- const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);- return {- objects,- chars,- nameById: new Map(chars.map((c) => [c.id, c.name || c.id])),- charById: new Map(chars.map((c) => [c.id, c])),- };-}--// Yields every attachment that points at a character, as { o, att }.-function* eachAttachment(objects) {- for (const o of objects) {- for (const att of (Array.isArray(o.attachments) ? o.attachments : [])) {- if (att?.characterId) yield { o, att };- }- }-}--// A human-readable summary of every object + who's attached to it, fed to the-// unmotivated-interaction LLM so it knows which objects already carry an-// established stake (and which don't) before judging a prose interaction.-export function describeObjectAttachments(ctx) {- const { objects, nameById } = attachmentCanon(ctx);- const lines = [];- for (const o of objects) {- const atts = Array.isArray(o.attachments) ? o.attachments : [];- const sig = (o.significance || '').trim();- const attText = atts.length- ? atts.map((a) => {- const who = nameById.get(a.characterId) || a.characterId;- const emotion = a.emotion ? ` (${a.emotion})` : '';- const why = a.significance ? ` — ${a.significance}` : '';- return `${who}${emotion}${why}`;- }).join('; ')- : 'nobody';- lines.push(`- ${o.name || o.id}${sig ? ` — significance: ${sig}` : ''}\n attached to: ${attText}`);- }- return lines.join('\n') || '(no objects in canon)';-}--// A richer per-object weight summary for the weight-proportionality check-// (#1624). Unlike describeObjectAttachments (which the unmotivated-interaction-// check uses to know who already cares about an object), this surfaces the FULL-// recorded weight an object carries going in — the prose significance plus every-// attachment's emotion, per-bond significance, ORIGIN (the lineage/backstory),-// and ROLE archetype — so the model can weigh that recorded backstory against-// how prominent the object actually is in the manuscript. The origin/role fields-// are exactly the "rich recorded backstory for a barely used object" signal the-// over-weighted verdict depends on, which the leaner attachments summary omits.-export function describeObjectWeight(ctx) {- const { objects, nameById } = attachmentCanon(ctx);- const lines = [];- for (const o of objects) {- const atts = Array.isArray(o.attachments) ? o.attachments : [];- const sig = (o.significance || '').trim();- const head = `- ${o.name || o.id}${sig ? ` — significance: ${sig}` : ''}`;- if (!atts.length) {- lines.push(`${head}\n attachments: none`);- continue;- }- const attLines = atts.map((a) => {- const who = nameById.get(a.characterId) || a.characterId || 'unknown';- const emotion = (a.emotion || '').trim();- const significance = (a.significance || '').trim();- const origin = (a.origin || '').trim();- const role = (a.role || '').trim();- const parts = [- ` • ${who}${emotion ? ` (${emotion})` : ''}${role ? ` [${role}]` : ''}`,- ];- if (significance) parts.push(` significance: ${significance}`);- if (origin) parts.push(` origin: ${origin}`);- return parts.join('\n');- });- lines.push(`${head}\n${attLines.join('\n')}`);- }- return lines.join('\n') || '(no objects in canon)';-}--// The attachment rows whose `origin` can be checked against the attached-// character's `background` — both must be present, and the character must-// still exist (a dangling characterId is the UI/sanitizer's concern, not this-// check's). Shared by the backstory-consistency check's `gate` (cheap presence-// test) and its `run` (the actual prompt rows) so they never disagree.-export function attachmentBackstoryRows(ctx) {- const { objects, charById } = attachmentCanon(ctx);- const rows = [];- for (const { o, att } of eachAttachment(objects)) {- const origin = (att.origin || '').trim();- if (!origin) continue;- const char = charById.get(att.characterId);- if (!char) continue;- const background = (char.background || '').trim();- if (!background) continue;- rows.push({- object: o.name || o.id,- character: char.name || char.id,- emotion: (att.emotion || '').trim(),- origin,- background,- });- }- return rows;-}--// ----------------------------------------------------------------------------// Shared LLM-check helpers. Every `kind: 'llm'` check normalizes the model's-// raw findings into the manuscriptReview comment shape, and a manuscript--// consuming check additionally feeds the whole corpus to the model in-// provider-sized chunks (so a long series isn't truncated on a small/local-// provider) and merges the per-chunk findings. These collapse those repeated-// blocks so the field validation + chunk-merge live once.-// -----------------------------------------------------------------------------// Fixed per-call prompt overhead (template scaffolding + JSON-shape-// instructions) reserved on top of any check-specific static vars, so the-// chunk budget leaves room for the prompt the manuscript rides inside.-export const EDITORIAL_PROMPT_OVERHEAD_TOKENS = 1_500;--// First-wins dedup key for an editorial finding, used to merge results across-// manuscript chunks. Mirrors completenessPass.findingKey: a finding identical on-// (issue, category, anchor, problem) is kept once even if two chunks surface it.-export const editorialFindingKey = (f) => [- f.issueNumber ?? '',- f.category ?? '',- (f.anchorQuote || '').trim().toLowerCase().slice(0, 120),- (f.problem || '').trim().toLowerCase().slice(0, 120),-].join('|');--// 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;-// Only the findings BODY is capped — the fixed header and the trailing `---`-// delimiter are always added AFTER the cap (the next manuscript chunk is-// concatenated right after the digest, so the delimiter MUST survive or the-// manuscript bleeds into the "already recorded" list).-export const EDITORIAL_PRIOR_DIGEST_BODY_CHARS = 2_000;-const EDITORIAL_PRIOR_DIGEST_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';-const EDITORIAL_PRIOR_DIGEST_SEPARATOR = '\n\n---\n\n';-// Whole-digest char ceiling = fixed wrapper + capped body. The digest is only-// prepended to a chunk when it fits in that chunk's spare budget (see-// runChunkedManuscriptCheck), so it never grows a chunk past the provider window.-export const EDITORIAL_PRIOR_DIGEST_CHARS =- EDITORIAL_PRIOR_DIGEST_HEADER.length + EDITORIAL_PRIOR_DIGEST_BODY_CHARS + EDITORIAL_PRIOR_DIGEST_SEPARATOR.length;--// 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.-//-// Scope note: this carries prior FINDINGS, not clean prior setup (same as the-// completeness pass). It removes the duplicate/contradiction blind spot — a-// later chunk won't re-flag something an earlier chunk already flagged — but it-// can't tell a later chunk that an earlier chunk *cleanly* established an object's-// motivation or a tense. Carrying clean cross-chunk context would need a-// per-chunk content summary (extra LLM calls); tracked as a follow-up in #1403.-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)` : '';- // Cap the body only — the header and the trailing `---` separator are appended- // afterwards so they always survive (see EDITORIAL_PRIOR_DIGEST_BODY_CHARS).- const body = `${lines.join('\n')}${more}`.slice(0, EDITORIAL_PRIOR_DIGEST_BODY_CHARS);- return `${EDITORIAL_PRIOR_DIGEST_HEADER}${body}${EDITORIAL_PRIOR_DIGEST_SEPARATOR}`;-}--// Cross-chunk CLEAN-SETUP digest (#1403). The findings digest above carries prior-// problems forward, but it cannot tell a later chunk that an earlier chunk-// *cleanly* established context (an object's motivation, a tense/POV/rating) —-// clean setup produces no finding, so a payoff in a later chunk can be mis-flagged-// "missing setup". This digest threads a short rolling summary of established-// setup alongside the findings digest, generated by one extra summarization LLM-// call per chunk (see `runManuscriptLlmCheck`'s `crossChunkSetup` path).-//-// (When the reverse-outline (#1349) or continuity-bible (#1305) artifacts land,-// either could supply this cross-chunk context more cheaply than a per-chunk-// summary call — they already condense the manuscript. Until then this is the-// self-contained source.)-//-// Free-form run tag so /runs can filter the setup-summary calls apart from the-// named-stage editorial checks and custom-check calls.-export const EDITORIAL_SETUP_DIGEST_SOURCE = 'pipeline-editorial-setup-digest';-// Body cap for the rolling setup summary (a touch smaller than the findings-// digest — it is condensed prose, not a bounded findings list). Header + trailing-// `---` are appended AFTER the cap so the delimiter always survives truncation-// (the next manuscript chunk concatenates right after, same contract as the-// findings digest).-export const EDITORIAL_SETUP_DIGEST_BODY_CHARS = 1_500;-const EDITORIAL_SETUP_DIGEST_HEADER =- '# Setup already established in EARLIER parts of this manuscript (clean context — these are NOT problems)\n'- + 'Use this when judging the text below: do NOT flag a payoff as missing setup, or a tense/POV/rating as a '- + 'drift, if it was already established here.\n\n';-const EDITORIAL_SETUP_DIGEST_SEPARATOR = '\n\n---\n\n';-// Whole-digest char ceiling = fixed wrapper + capped body. Like the findings-// digest, the setup digest is prepended only when it fits the chunk's spare-// budget, so it never grows a chunk past the provider window.-export const EDITORIAL_SETUP_DIGEST_CHARS =- EDITORIAL_SETUP_DIGEST_HEADER.length + EDITORIAL_SETUP_DIGEST_BODY_CHARS + EDITORIAL_SETUP_DIGEST_SEPARATOR.length;--// Wrap an accumulated "setup so far" summary in the fixed header + trailing `---`-// so it rides INSIDE the next chunk's manuscript var (no prompt template change,-// mirrors editorialPriorFindingsDigest). Returns '' for an empty/non-string-// summary so the first chunk (no prior setup yet) is untouched.-export function editorialSetupDigest(summary) {- if (typeof summary !== 'string' || !summary.trim()) return '';- const body = summary.trim().slice(0, EDITORIAL_SETUP_DIGEST_BODY_CHARS);- return `${EDITORIAL_SETUP_DIGEST_HEADER}${body}${EDITORIAL_SETUP_DIGEST_SEPARATOR}`;-}--// Build the inline summarization prompt that maintains the rolling "setup so far"-// summary. Pure + deterministic so it's unit-testable and so the caller can pin a-// per-check `focus` (the objects check tracks item motivations; the style check-// tracks tense/POV/rating). Asks for terse merged setup text only — no JSON, no-// commentary — since the result rides verbatim into the next chunk's digest.-export function buildSetupDigestPrompt({ focus, priorSummary, manuscript }) {- const trackDefault = 'Items/objects introduced and any motivation or significance established for them; '- + 'the narrative tense, point-of-view person, and content rating in force.';- return [- 'You are tracking established narrative SETUP across a long manuscript reviewed in parts.',- 'Maintain a SHORT running summary of the setup so far — only the facts a later part needs to judge payoffs and continuity.',- '',- '# What to track',- String(focus || '').trim() || trackDefault,- '',- '# Setup recorded so far (from earlier parts)',- String(priorSummary || '').trim() || '(none yet)',- '',- '# New manuscript part',- String(manuscript || ''),- '',- '# How to respond',- 'Return an updated running summary that MERGES the prior setup with any new setup established in this part.',- 'Be terse: short bullet lines, no preamble, no commentary — only the established facts, dropping nothing important from the prior summary.',- 'Respond with the summary text only: no JSON, no section headers, no explanation.',- ].join('\n');-}--// 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.-//-// The digest YIELDS to manuscript coverage: it is prepended only when it fits in-// the chunk's spare budget (`usableChars - chunk length`, exposed by the runner's-// chunker). So it never displaces manuscript text and never grows a chunk past-// the provider window — a chunk packed up to the budget simply runs without a-// digest rather than dropping its tail. When the chunker doesn't report a budget-// (a fits-in-one-call provider, or a test stub), there is unbounded headroom.-//-// `summarizeChunk` (#1403) opts in the CLEAN-SETUP digest: when provided, after-// each non-final chunk it is called `(priorSummary, chunkText) => nextSummary` to-// roll forward a short "setup so far" summary, and that summary's `editorialSetupDigest`-// is prepended (alongside the findings digest, after it in the budget) to later-// chunks — also yielding to spare room. It is a no-op for a single-chunk run (no-// later chunk consumes a summary), so the common fits-in-one-call provider pays-// nothing.-//-// `reserveSetupDigest` (#1667) GUARANTEES the carried setup digest reaches the-// FINAL chunk for checks that gate a whole-story verdict to it and anchor that-// verdict on the carried snippet (arc.climax-agency #1583, emotion.reaction--// proportionality #1584). The setup digest normally yields to manuscript coverage,-// so a final chunk packed to within a few hundred chars of the window silently-// drops the digest and the final-only finding is missed. When this opt-in is set-// and the digest doesn't fit the final chunk's spare room, the manuscript TAIL is-// trimmed to reserve the digest's room (the inverse of the usual yield) so the-// verdict keeps its carried context. Scoped to the final chunk and to opt-in checks-// only — every other chunk, and every non-reserving check, keeps full manuscript-// coverage. If the digest alone is larger than the whole window it still yields-// (never prepended past the budget), preserving the no-overflow contract.-async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk, crossChunkDigest = false, summarizeChunk = null, reserveSetupDigest = false, subtypes = null }) {- const usableChars = Number.isFinite(chunks?.usableChars) ? chunks.usableChars : Infinity;- const merged = new Map();- // The presence of `summarizeChunk` (set only when the check opts into the- // clean-setup digest AND an inline LLM caller is available) is itself the gate —- // no separate flag, so the null-checks below can't drift from it.- let setupSummary = '';- for (let i = 0; i < chunks.length; i++) {- const manuscript = chunks[i];- // 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;- // `isFinal` lets a check distinguish the last part of a chunked manuscript- // from earlier ones (#1299): a whole-corpus judgment like "this setup is- // never paid off" can only be made once the final part is in view, so the- // Chekhov check defers its "planted, never fired" findings to it. A- // single-chunk run is its own final part, so the common (provider-fits-the-- // book) case judges against the whole text. Existing checks ignore the arg.- const isFinal = i === chunks.length - 1;- let text = manuscript;- if (crossChunkDigest && merged.size) {- const digest = editorialPriorFindingsDigest([...merged.values()]);- // Only prepend when the digest fits the chunk's spare room — never trim the- // manuscript (would drop review coverage) or overflow the window.- if (digest && digest.length <= usableChars - text.length) text = `${digest}${manuscript}`;- }- if (summarizeChunk && setupSummary) {- const setup = editorialSetupDigest(setupSummary);- if (setup && setup.length <= usableChars - text.length) {- // Fits into whatever spare room remains AFTER the findings digest — manuscript- // coverage and the findings digest both win over the setup digest if budget is tight.- text = `${setup}${text}`;- } else if (setup && reserveSetupDigest && isFinal && setup.length <= usableChars) {- // #1667: the digest didn't fit, but this check gates its verdict to the final- // part and anchors it on the carried snippet — so reserve the digest's room and- // fill the rest with the manuscript HEAD (trimming its tail) rather than drop- // the carried context. Rebuild from the RAW `manuscript`, NOT the- // findings-digest-prefixed `text`: slicing `text` could truncate the findings- // digest mid-block into a malformed prefix, and the findings digest's job- // (suppressing duplicate re-flags) is already covered by the first-wins merge,- // so it safely yields here. Gated on `setup.length <= usableChars` so a digest- // larger than the whole window yields instead of overflowing it — preserving- // the pre-reserve no-overflow contract on a tiny/high-overhead window.- text = `${setup}${manuscript.slice(0, usableChars - setup.length)}`;- }- }- const content = await callChunk(text, { isFinal });- for (const f of mapLlmFindings(content?.findings, {- severityDefault: ctx.severityDefault,- category,- max,- withIssueNumber: true,- subtypes,- })) {- const k = editorialFindingKey(f);- if (!merged.has(k)) merged.set(k, f);- }- // Roll the setup summary forward for the NEXT chunk — skip after the last chunk- // (nothing consumes it) and on cancellation (its result would be discarded).- // Summarize the RAW chunk, never the digest-prefixed text. A summarizer failure- // must not abort the check — keep the prior summary and continue.- if (summarizeChunk && i < chunks.length - 1 && !ctx.signal?.aborted) {- const next = await summarizeChunk(setupSummary, manuscript).catch(() => setupSummary);- // Cap the STORED summary, not just the rendered digest: a verbose/echoing- // summarizer response is fed back into the next summarization prompt as the- // prior summary, so an uncapped string would compound and could overflow the- // provider context. Trimming here bounds both the next prompt and the digest.- if (typeof next === 'string' && next.trim()) {- setupSummary = next.trim().slice(0, EDITORIAL_SETUP_DIGEST_BODY_CHARS);- }- }- }- 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-// findings first-wins (capped at the check's `maxFindings`). `buildVars(chunk, meta)`-// returns the stage vars — only the manuscript var changes per chunk; `meta.isFinal`-// is true on the last (or only) chunk so a check can gate whole-corpus judgments to-// it (the Chekhov "planted, never fired" pass). Existing checks ignore `meta`. These-// checks are all manuscript-scoped, so findings keep a model-supplied issue-// number (`withIssueNumber: true`).-//-// A check declares its per-chunk non-manuscript overhead in ONE of two ways:-//-// `context` (preferred) — a `{ varName: string }` map of the TRIMMABLE context-// blocks the check re-sends on each chunk (the scene map, character arcs, the-// style-guide expectations, …). The runner counts them as overhead AND, on a-// small/fallback window where they'd starve the manuscript chunk to '', trims-// them to guarantee the manuscript a budget floor (#1459). `buildVars` then-// receives the (possibly trimmed) blocks as its third arg — so the check feeds-// the SAME context it was budgeted for (sending the untrimmed originals would-// overflow the window the trim was sized to fit). `EDITORIAL_PROMPT_OVERHEAD_TOKENS`-// is added automatically as the fixed (non-trimmable) template/contract reserve.-//-// `overheadTokens` (legacy) — a single fixed token count for a check with no-// trimmable context (a plain whole-manuscript scan). MUST account for every-// non-manuscript prompt var, on top of EDITORIAL_PROMPT_OVERHEAD_TOKENS.-//-// `buildVars(chunk, meta, context)` returns the stage vars — only the manuscript-// var changes per chunk; `meta.isFinal` is true on the last (or only) chunk so a-// check can gate whole-corpus judgments to it (the Chekhov "planted, never fired"-// pass), and `context` is the trimmed block map (or `{}` for an `overheadTokens`-// check). Existing checks ignore the extra args. These checks are all-// manuscript-scoped, so findings keep a model-supplied issue number-// (`withIssueNumber: true`).-export async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, context = null, buildVars, crossChunkDigest = false, crossChunkSetup = false, setupFocus = '', reserveSetupDigest = false, subtypes = null }) {- const max = ctx.config?.maxFindings ?? 12;- // Chunks are planned at the full usable budget; the digest is fitted into each- // later chunk's spare room inside runChunkedManuscriptCheck (it yields to the- // manuscript), so no budget is reserved or carved out here. A `context` map is- // trimmed to keep the manuscript a budget floor; the trimmed blocks come back on- // `chunks.context` so they're what we feed the model.- const chunks = context- ? await ctx.planManuscriptChunks(stage, { context, fixedOverheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS })- : await ctx.planManuscriptChunks(stage, { overheadTokens });- // The runner returns the (possibly trimmed) context on `chunks.context`; fall back- // to the originals if it didn't echo them (a chunker that doesn't implement the- // context path), and to `{}` for an `overheadTokens` check with no context.- const fittedContext = chunks?.context || context || {};- // Clean-setup digest (#1403): roll a short "setup so far" summary forward via an- // inline summarization call. Only wired when the check opts in AND the runner- // injected the stage-scoped inline caller — absent it (unit tests of the- // findings-digest path), the check degrades to findings-only with no extra calls.- // The call is STAGE-SCOPED (not plain callInlineLLM) so the summary runs on the- // same provider the stage is pinned to — never leaking manuscript text to the- // active/cloud provider when the check's stage targets a private/local one.- const summarizeChunk = crossChunkSetup && typeof ctx.callStageScopedInlineLLM === 'function'- ? async (priorSummary, manuscript) => {- const prompt = buildSetupDigestPrompt({ focus: setupFocus, priorSummary, manuscript });- const { content } = await ctx.callStageScopedInlineLLM(stage, prompt, { source: EDITORIAL_SETUP_DIGEST_SOURCE });- return typeof content === 'string' ? content : '';- }- : null;- return runChunkedManuscriptCheck(ctx, {- chunks,- category,- max,- crossChunkDigest,- summarizeChunk,- reserveSetupDigest,- subtypes,- callChunk: async (manuscript, meta) => {- const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript, meta, fittedContext), { returnsJson: true, source: stage });- return content;- },- });-}--// Normalize raw LLM findings into partial manuscriptReview comments: validate-// severity against the allow-list (fall back to the check default), force the-// check's `category`, coerce each string field, cap the count, and drop any-// finding with no `problem`. `withIssueNumber` keeps a model-supplied issue-// number (manuscript-scoped checks) vs. forcing null (canon-scoped checks).-// `subtypes` (optional) is a per-check allow-list (#1626): when supplied, the-// model's `subtype` is validated against it and stamped on the finding (off-list-// or absent → null), letting a check sub-classify its findings (e.g. on-the-nose-// → exposition / emotion-tell / relationship-report) without a new field on every-// other check.-export function mapLlmFindings(raw, { severityDefault, category, max, withIssueNumber, subtypes = null }) {- const list = Array.isArray(raw) ? raw : [];- const allowSubtype = Array.isArray(subtypes) && subtypes.length > 0;- return list.slice(0, max).map((f) => ({- severity: SEVERITIES.includes(f?.severity) ? f.severity : severityDefault,- category,- // Optional per-check sub-classification. Only set when the check declares an- // allow-list AND the model returned a recognized value — null otherwise so a- // check with no subtypes (and an unrecognized label) carries a clean null.- subtype: allowSubtype && subtypes.includes(f?.subtype) ? f.subtype : null,- location: typeof f?.location === 'string' ? f.location : '',- problem: typeof f?.problem === 'string' ? f.problem : '',- suggestion: typeof f?.suggestion === 'string' ? f.suggestion : '',- anchorQuote: typeof f?.anchorQuote === 'string' ? f.anchorQuote : '',- issueNumber: withIssueNumber && Number.isInteger(f?.issueNumber) ? f.issueNumber : null,- })).filter((f) => f.problem);-}--// ----------------------------------------------------------------------------// User-defined (custom) LLM checks (#1346). A custom check has no shipped stage-// template — its prompt body is authored from the UI. The fixed JSON output-// contract is enforced HERE (not by the user), so an author only describes WHAT-// to look for; the response is parsed by the same `mapLlmFindings` the built-in-// stage prompts feed. Kept pure: the model caller (`ctx.callInlineLLM`) and the-// chunk planner (`ctx.planManuscriptChunks`) are injected by the runner.-// -----------------------------------------------------------------------------// Free-form tag persisted on the run record so /runs can filter custom-check-// calls apart from the named-stage editorial checks.-export const CUSTOM_CHECK_RUN_SOURCE = 'pipeline-editorial-custom';--// Wrap a user's authored instructions in the fixed findings JSON contract. Pure-// and deterministic so it's unit-testable and so `runManuscriptLlmCheckInline`-// can render it once with an empty manuscript to measure per-call overhead.-export function buildCustomCheckPrompt({ instructions, manuscript, maxFindings = CUSTOM_CHECK_MAX_FINDINGS_DEFAULT }) {- const cap = Number.isInteger(maxFindings) && maxFindings > 0 ? maxFindings : CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;- return [- 'You are an editorial reviewer analyzing a draft manuscript for one specific issue.',- '',- '# What to look for',- String(instructions || '').trim(),- '',- '# Manuscript',- String(manuscript || ''),- '',- '# How to respond',- `Return ONLY a JSON object of the form {"findings": [...]} with at most ${cap} findings.`,- 'Each finding is an object with these fields:',- '- "severity": one of "high", "medium", "low"',- '- "location": a short human-readable pointer to where the problem is (e.g. a chapter or section name)',- '- "problem": one sentence stating what is wrong (REQUIRED — omit the finding if you cannot name a concrete problem)',- '- "suggestion": one sentence on how to fix it',- '- "anchorQuote": a short verbatim quote from the manuscript at the problem location',- '- "issueNumber": the issue/chapter number the problem is in, or null',- 'If nothing matches, return {"findings": []}. Do not include any prose outside the JSON object.',- ].join('\n');-}--// Inline-prompt sibling of `runManuscriptLlmCheck` for custom checks: same-// provider-sized chunking + first-wins merge, but the prompt is the authored-// instructions wrapped by `buildCustomCheckPrompt` instead of a named stage.-// `ctx.planManuscriptChunks(null, …)` resolves the active/overridden provider's-// window (a custom check has no stage to pin), and `ctx.callInlineLLM` runs the-// built prompt. Findings keep a model-supplied issue number (manuscript-scoped).-export async function runManuscriptLlmCheckInline(ctx, { category, instructions }) {- const max = ctx.config?.maxFindings ?? CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;- // Fixed per-call overhead = the contract wrapper + the instructions (only the- // manuscript var changes per chunk). Measure it by rendering the prompt with an- // empty manuscript so the chunk budget accounts for everything riding along.- const overheadTokens = EDITORIAL_PROMPT_OVERHEAD_TOKENS- + estimateTokens(buildCustomCheckPrompt({ instructions, manuscript: '', maxFindings: max }));- const chunks = await ctx.planManuscriptChunks(null, { overheadTokens });- 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;- },- });-}--// ----------------------------------------------------------------------------// Deterministic helpers for the style-guide reading-level check (#1303). A-// self-contained Flesch–Kincaid grade-level estimate so the registry stays pure-// (no import out to the styleGuide lib). The heuristic is approximate — it only-// needs to catch "the prose reads several grades off the configured target".-// -----------------------------------------------------------------------------// Hoisted out of countSyllables so the per-word loop over a full manuscript-// doesn't recompile them on every call.-const NON_ALPHA_RE = /[^a-z]/g;-const VOWEL_GROUP_RE = /[aeiouy]+/g;-const SENTENCE_END_RE = /[.!?]+/g;-const WORD_RE = /\b[a-zA-Z]+\b/g;--function countSyllables(word) {- const w = String(word).toLowerCase().replace(NON_ALPHA_RE, '');- if (!w) return 0;- if (w.length <= 3) return 1;- // Drop a trailing silent 'e', then count vowel groups (each run of vowels is- // ~one syllable). Floor at 1 — every real word has at least one.- const groups = w.replace(/e$/, '').match(VOWEL_GROUP_RE);- return Math.max(1, groups ? groups.length : 1);-}--// Flesch–Kincaid grade level for a manuscript corpus. Returns null when there-// are no words to measure (caller skips rather than flagging a phantom grade).-export function readingGradeLevel(text) {- const clean = String(text || '');- const sentences = (clean.match(SENTENCE_END_RE) || []).length || 1;- const words = clean.match(WORD_RE) || [];- if (words.length === 0) return null;- const syllables = words.reduce((sum, w) => sum + countSyllables(w), 0);- return 0.39 * (words.length / sentences) + 11.8 * (syllables / words.length) - 15.59;-}--// Per-scene reading-grade spread (#1625). The whole-corpus grade above is a single-// number for the entire series — it averages away the legitimate modulation a-// skilled writer uses (a quiet introspective scene reads lower, an action scene-// higher) AND it hides a lone scene that swings far outside the intended band.-// Splits the manuscript into scenes via the shared `splitScenes` (markdown-// headings — including the stitcher's `# Issue N` — and centered rules like-// "***") and measures each one, so the check can surface the outliers the corpus-// average conceals. Scenes shorter than `minWords` are skipped: a brief fragment's-// FK estimate is too noisy to judge. Returns one row per measurable scene-// (`{ ordinal, grade, words, text }`), or [] when none qualify.-export function readingLevelByScene(manuscript, minWords) {- const floor = Number.isFinite(minWords) ? minWords : 120;- const rows = [];- for (const scene of splitScenes(String(manuscript || ''))) {- const words = (scene.text.match(WORD_RE) || []).length;- if (words < floor) continue;- const grade = readingGradeLevel(scene.text);- if (grade == null) continue;- rows.push({ ordinal: scene.ordinal, grade: Math.round(grade * 10) / 10, words, text: scene.text });- }- return rows;-}--// First substantive line of a scene, trimmed to a short anchor so a per-scene-// finding lands on real prose the editor can locate. Skips blank lines; falls-// back to '' for a whitespace-only scene.-export function sceneReadingAnchor(text) {- for (const line of String(text || '').split('\n')) {- const t = line.trim();- if (t) return t.length > 80 ? `${t.slice(0, 80).trim()}…` : t;- }- return '';-}--// Compact bullet list of the conformance-relevant style-guide expectations, fed-// to the conformance LLM so it knows exactly what to measure the prose against.-// Inlined (not imported from styleGuide.js) to keep this registry pure. Returns-// '' when no conformance-relevant field is set (the check's gate also tests this).-export function styleGuideExpectations(sg) {- if (!sg || typeof sg !== 'object') return '';- const lines = [];- if (sg.tense) lines.push(`- Tense: ${sg.tense}`);- if (sg.povPerson) lines.push(`- Point-of-view person: ${sg.povPerson}`);- if (sg.targetAudience) lines.push(`- Target audience: ${sg.targetAudience}`);- if (sg.contentRating && sg.contentRating !== 'custom') lines.push(`- Content rating ceiling: ${sg.contentRating}`);- if (sg.profanity) lines.push(`- Profanity allowed: ${sg.profanity}`);- return lines.join('\n');-}--// True when the style guide carries at least one field the conformance LLM can-// measure prose against. Shared by the check's gate and run so they agree.-export const hasConformanceFields = (sg) => styleGuideExpectations(sg).length > 0;--// ----------------------------------------------------------------------------// Roster economy (#1292) — character-appearance accounting over the stitched-// manuscript. Reads canon names + aliases and counts the DISTINCT issues each-// named character is mentioned in (recurrence), which issue they first appear-// in, and the named cast present in the opening issue. Pure: the per-issue-// `ctx.sections` and `ctx.canon` are injected by the runner.-//-// The match is a deterministic word-bounded name scan. A character whose name-// is a common word (Hope, Grace, Reed) can over-match prose — which biases the-// check toward UNDER-flagging throwaways (safe) at the cost of possibly-// over-counting first-issue crowding. Classifying unmodeled proper nouns as-// characters needs an LLM pass and is tracked as its own check (see the issue).-// -----------------------------------------------------------------------------// Escape a name so it rides inside a RegExp alternation literally — names carry-// regex-significant punctuation ("D'Argo", "Anne-Marie", "T.A.R.D.I.S.").-const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');--// A character's match tokens: its name plus every alias, trimmed + de-duped.-// Empty when the character has no usable name.-function characterNameTokens(c) {- const tokens = [];- const push = (v) => { const t = typeof v === 'string' ? v.trim() : ''; if (t) tokens.push(t); };- push(c?.name);- for (const a of (Array.isArray(c?.aliases) ? c.aliases : [])) push(a);- return [...new Set(tokens)];-}--// A case-insensitive, whole-token matcher for a character's tokens (built once-// per character and reused across every section so a long manuscript isn't-// re-compiling a regex per section), or null when there are no tokens.-export function characterMatcher(tokens) {- if (!tokens.length) return null;- // Longest-first so a token that's a prefix of another can't shadow it under- // leftmost-match alternation (cosmetic for .test, but keeps intent clear).- const alt = tokens.slice().sort((a, b) => b.length - a.length).map(escapeRegExp).join('|');- // Lookarounds, not \b: a token that begins or ends with punctuation ("Mr.",- // "T.A.R.D.I.S.", "J.R.") has no word char at that edge, so a leading/trailing- // \b would never match it in prose. (?<!\w)…(?!\w) enforces whole-token matching- // at any edge while still rejecting substrings (Sam ≠ "Samuel").- return new RegExp(`(?<!\\w)(?:${alt})(?!\\w)`, 'i');-}--// One row per NAMED canon character: { id, name, locked, appearedInIssues,-// firstIssueNumber }. `appearedInIssues` is the distinct issue numbers the-// character is mentioned in, in story order (sections are one-per-issue, ordered-// by arc position). Unnamed canon entries aren't a roster-economy concern.-export function buildRosterAppearances(ctx) {- const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];- const sections = Array.isArray(ctx.sections) ? ctx.sections : [];- const rows = [];- for (const c of chars) {- if (!c || typeof c !== 'object') continue;- const name = typeof c.name === 'string' ? c.name.trim() : '';- if (!name) continue;- const matcher = characterMatcher(characterNameTokens(c));- if (!matcher) continue;- const appearedInIssues = [];- // Capture the ACTUAL matched token (name OR alias) from the first issue the- // character appears in, so a finding's anchorQuote lands on real prose — an- // alias-only mention ("Bob" for canonical "Robert") must anchor on "Bob", not- // the canonical name the editor would never find. `matcher` is non-global, so- // exec starts at 0 on each section. Falls back to the name for unmatched rows.- let anchorQuote = '';- for (const s of sections) {- const m = matcher.exec(s.content || '');- if (!m) continue;- appearedInIssues.push(s.number);- if (!anchorQuote) anchorQuote = m[0];- }- rows.push({- id: c.id || name,- name,- locked: c.locked === true,- appearedInIssues,- firstIssueNumber: appearedInIssues.length ? appearedInIssues[0] : null,- anchorQuote: anchorQuote || name,- });- }- return rows;-}--// Normalized keys of every canon character that actually APPEARS in the prose-// (named at least once across the manuscript sections) — the "appearing cast"-// both the screen-time skew and the silent-major distribution signals score-// against. Pure; reuses buildRosterAppearances' per-section matcher scan.-export function buildAppearingKeys(ctx) {- return new Set(- buildRosterAppearances(ctx)- .filter((r) => r.appearedInIssues.length > 0)- .map((r) => normalizeName(r.name))- );-}--// ----------------------------------------------------------------------------// Cast representation & balance (#1312) — three coarse, computable casting-// signals over the canon + reverse-outline + stitched manuscript:-// 1) Bechdel co-presence — does ANY scene put two+ non-male characters-// together (the structural precondition for two women talking)? Computed-// from the reverse-outline's per-scene charactersPresent against-// pronoun-inferred gender. A coarse signal, not the full Bechdel test-// (we can't read whether the conversation is about a man deterministically).-// 2) Dialogue share — does one character dominate the spoken lines? Counts-// attributed dialogue paragraphs per character (attributeDialogueByOwner)-// and flags a lopsided distribution (top speaker over a configurable share).-// 3) Screen-time balance — when gender is inferable, flag a strongly skewed-// appearing cast (e.g. a near-all-male roster) as a representation nudge.-//-// All three are advisory (low/medium): representation is an authorial choice and-// these are signals, not correctness errors. Gender is inferred ONLY from the-// canon `pronouns` field — absent/ambiguous pronouns yield 'unknown', and the-// gender-dependent signals stay silent rather than guess (absent ≠ a category).-// -----------------------------------------------------------------------------// Infer a coarse gender bucket from a character's canon `pronouns` string. Only-// the unambiguous subject/object pronoun sets map; anything else (neopronouns,-// "any", blank, a sentence) is 'unknown' so a gender-dependent signal can opt-// out rather than miscategorize. Returns 'female' | 'male' | 'nonbinary' | 'unknown'.-function inferGender(pronouns) {- const p = typeof pronouns === 'string' ? pronouns.toLowerCase() : '';- if (!p) return 'unknown';- const has = (re) => re.test(p);- const she = has(/\bshe\b/) || has(/\bher\b/) || has(/\bhers\b/);- const he = has(/\bhe\b/) || has(/\bhim\b/) || has(/\bhis\b/);- const they = has(/\bthey\b/) || has(/\bthem\b/) || has(/\btheir\b/);- // A clean single set wins; a mixed string ("she/they") is ambiguous → unknown,- // except she+they / he+they which still read as a definite female/male identity- // with a secondary set. Both she AND he present is genuinely ambiguous.- if (she && he) return 'unknown';- if (she) return 'female';- if (he) return 'male';- if (they) return 'nonbinary';- return 'unknown';-}--// Coarse role-tier inference from a canon character's free-text `role` field, for-// the per-character dialogue-distribution signal (#1594). Only unambiguous keyword-// sets map to a tier; anything else (blank, a description, a role that mixes a-// major AND a minor word like "minor antagonist") is 'unknown' so the distribution-// signal opts out rather than guess — the same absent-vs-empty discipline-// inferGender() uses. Deliberately omits genuinely-ambiguous words ("supporting",-// "secondary", "recurring") that sit between lead and walk-on. Returns-// 'major' | 'minor' | 'unknown'. The two keyword sets live at module scope (vs-// inferGender's inline pronoun checks) so the regexes are compiled once, not on-// every per-character call.-const MAJOR_ROLE_RE = /\b(protagonist|deuteragonist|antagonist|villain|hero|heroine|lead|main|primary|central|principal)\b/;-const MINOR_ROLE_RE = /\b(minor|background|cameo|walk-?on|bit[- ]?part|extra|incidental|tertiary)\b/;-function inferRoleTier(role) {- const r = typeof role === 'string' ? role.toLowerCase() : '';- if (!r) return 'unknown';- const major = MAJOR_ROLE_RE.test(r);- const minor = MINOR_ROLE_RE.test(r);- if (major && minor) return 'unknown'; // contradictory ("minor antagonist") → opt out- if (major) return 'major';- if (minor) return 'minor';- return 'unknown';-}--// Normalized name → { char, gender, key } for every named canon character, plus-// the per-owner whole-token matcher reused for dialogue attribution. Built once-// per run so the dialogue scan and the co-presence scan share one identity map.-export function buildCastIdentities(ctx) {- const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];- const identities = [];- for (const c of chars) {- if (!c || typeof c !== 'object') continue;- const name = typeof c.name === 'string' ? c.name.trim() : '';- if (!name) continue;- const key = normalizeName(name);- if (!key) continue;- const matcher = characterMatcher(characterNameTokens(c));- identities.push({- key,- name,- gender: inferGender(c.pronouns),- roleTier: inferRoleTier(c.role),- matcher,- });- }- return identities;-}--// Resolve a scene's charactersPresent names to canon identity keys (so a scene-// that lists "Bob" maps to canonical "Robert"). A present name that matches no-// canon character is dropped — the co-presence signal is canon-relative.-export function sceneCastKeys(scene, identityByKey, identities) {- const present = Array.isArray(scene?.charactersPresent) ? scene.charactersPresent : [];- const keys = new Set();- for (const raw of present) {- if (typeof raw !== 'string' || !raw.trim()) continue;- const direct = identityByKey.get(normalizeName(raw));- if (direct) { keys.add(direct.key); continue; }- // Fall back to a token match (the present-name might be an alias surface form).- const hit = identities.find((id) => id.matcher && id.matcher.test(raw));- if (hit) keys.add(hit.key);- }- return keys;-}--// ----------------------------------------------------------------------------// Scene component balance (#1296) — reads the cached reverse-outline (#1286)-// scene segmentation, where each scene carries a `components` boolean signal-// { narrative, action, dialogue }. The editorial rule: a scene should mix at-// least 2 of the 3; a single-mode scene (a narration wall, talking heads with-// no action, pure action with no interiority or voice) reads flat and is flagged.-//-// A scene with NO component flagged (all three false) is treated as-// "unclassified" (an older outline, or a scene the segmenter didn't tag), not-// "zero components" — it is skipped rather than flagged as a false positive,-// per the absent-vs-empty rule.-// -----------------------------------------------------------------------------const SCENE_COMPONENT_KEYS = ['narrative', 'action', 'dialogue'];--// The present/missing component lists for a scene's `components` signal.-export function sceneComponentMix(components) {- const c = components && typeof components === 'object' ? components : {};- const present = SCENE_COMPONENT_KEYS.filter((k) => c[k] === true);- const missing = SCENE_COMPONENT_KEYS.filter((k) => c[k] !== true);- return { present, missing };-}--// A scene's display label for finding text/location — its heading, falling back-// to the summary, then a sequence-based label. Type-guarded because the reverse-// outline rides peer sync (#1348): a hand-edited / older-peer scene could carry a-// non-string heading, and a bare `.trim()` on it would throw and abort the check.-export const sceneLabel = (s) => {- const heading = typeof s?.heading === 'string' ? s.heading.trim() : '';- const summary = typeof s?.summary === 'string' ? s.summary.trim() : '';- const seq = typeof s?.sequence === 'number' ? s.sequence + 1 : '?';- return heading || summary || `scene ${seq}`;-};--// Render the reverse-outline scenes into a compact text block the scene-grounding-// LLM checks (#1309) pass alongside the manuscript so the model can attribute-// findings to scenes and reason about each scene's recorded setting / characters.-// Pure + deterministic so it's unit-testable and its token cost can be counted-// into the per-chunk overhead. Returns '' when there are no scenes (the prompt's-// `{{#sceneMap}}` section then renders nothing and the check degrades to a plain-// whole-issue manuscript scan). Type-guarded throughout — the reverse outline-// rides peer sync (#1348), so a hand-edited / older-peer scene could carry a-// non-string field that a bare `.trim()` would throw on.-export function sceneGroundingSummary(scenes) {- const list = Array.isArray(scenes) ? scenes : [];- const lines = list.map((s) => {- if (!s || typeof s !== 'object') return '';- const label = sceneLabel(s);- const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;- const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';- const setting = typeof s.setting === 'string' ? s.setting.trim() : '';- const chars = Array.isArray(s.charactersPresent)- ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())- : [];- const parts = [`- ${where}: ${label}`];- parts.push(setting ? `setting: ${setting}` : 'setting: (none recorded)');- if (chars.length) parts.push(`present: ${chars.join(', ')}`);- return parts.join(' — ');- }).filter(Boolean);- if (!lines.length) return '';- return `Scenes (from the reverse outline):\n${lines.join('\n')}`;-}--// Render the reverse-outline PLOTLINES (#1286) into a compact text block the-// plot-structure check (#1310) passes alongside the manuscript so the model can-// reconcile dropped subplots against the author's tagged plotlines — a plotline-// that opens early and is never returned to is a dropped subplot. For each-// plotline we count the scenes tagged to it (primary OR secondary) and report the-// span of issues those scenes touch, so the model sees which threads fizzle.-// Pure + deterministic so it's unit-testable and its token cost can be counted-// into the per-chunk overhead. Returns '' when there are no plotlines (the-// prompt's `{{#plotlineMap}}` section then renders nothing and the check degrades-// to reasoning about subplots from the prose alone). Type-guarded throughout —-// the reverse outline rides peer sync (#1348), so a hand-edited / older-peer-// plotline could carry a non-string field a bare `.trim()` would throw on.-export function plotlineCoverageSummary(plotlines, scenes) {- const lines = Array.isArray(plotlines) ? plotlines : [];- const sceneList = Array.isArray(scenes) ? scenes : [];- const rows = lines.map((pl) => {- if (!pl || typeof pl !== 'object') return '';- const id = typeof pl.id === 'string' ? pl.id : '';- if (!id) return '';- const label = typeof pl.label === 'string' && pl.label.trim() ? pl.label.trim() : id;- const kind = typeof pl.kind === 'string' && pl.kind.trim() ? pl.kind.trim() : 'other';- // Scenes tagged to this plotline (primary or secondary), in outline order.- const tagged = sceneList.filter((s) => s && (s.plotlineId === id || s.secondaryPlotlineId === id));- const issues = [...new Set(- tagged- .map((s) => (Number.isInteger(s.issueNumber) ? s.issueNumber : null))- .filter((n) => n != null),- )].sort((a, b) => a - b);- const span = issues.length- ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)- : 'no tagged scenes';- return `- ${label} (${kind}): ${tagged.length} scene${tagged.length === 1 ? '' : 's'}, ${span}`;- }).filter(Boolean);- if (!rows.length) return '';- return `Plotlines (from the reverse outline — reconcile dropped subplots against these):\n${rows.join('\n')}`;-}--// Curated lexicon of conflict / stakes / high-intensity markers (#1618). A-// per-issue tally of these words is a crude-but-deterministic proxy for dramatic-// intensity: the escalation-curve check can't "feel" tension, but it CAN see-// whether the density of conflict language rises, plateaus, or falls across the-// issues. The model treats the tally as a hint (not ground truth) and confirms-// the curve against the prose — so a quiet-but-tense scene the lexicon misses is-// still caught. Word-boundary matched, case-insensitive; kept deliberately small-// and high-signal (physical conflict + danger/stakes) to limit false hits.-const CONFLICT_INTENSITY_MARKERS = Object.freeze([- // physical conflict / violence- 'attack', 'attacks', 'attacked', 'fight', 'fights', 'fought', 'fighting',- 'strike', 'strikes', 'struck', 'punch', 'punched', 'stab', 'stabbed', 'shoot',- 'shoots', 'shot', 'kill', 'kills', 'killed', 'die', 'dies', 'died', 'death',- 'blood', 'bleeding', 'wound', 'wounded', 'scream', 'screams', 'screamed',- 'shout', 'shouted', 'slam', 'slammed', 'crash', 'crashed',- // danger / stakes / dread- 'danger', 'dangerous', 'threat', 'threats', 'threaten', 'threatened', 'enemy',- 'enemies', 'weapon', 'weapons', 'gun', 'guns', 'knife', 'fire', 'fired',- 'fires', 'firing', 'explode', 'exploded', 'explosion', 'fear', 'terror',- 'panic', 'desperate', 'betray',- 'betrayed', 'betrayal', 'trap', 'trapped', 'flee', 'fled', 'chase', 'chased',- 'escape', 'war', 'battle', 'dying', 'doom', 'doomed',-]);--// Tally the conflict-marker density per issue across the WHOLE stitched manuscript-// (#1618) so the escalation-curve check sees the complete intensity shape on every-// chunk. Splits on the `# Issue N` headers the manuscript stitcher emits, counts-// markers + words per issue, and reports markers-per-1k-words — normalizing out-// raw length so a long-but-quiet issue doesn't read as more intense than a short-// climactic one. Pure + deterministic so it's unit-testable and its token cost can-// be counted into the per-chunk overhead. Returns '' when there are no issue-// headers (the prompt's `{{#intensityTally}}` section then renders nothing and the-// check judges the curve from the prose + scene map alone). A header that repeats-// across the stitch (a chunk boundary mid-issue) sums into the same issue bucket.-export function conflictIntensityTally(manuscript) {- const text = typeof manuscript === 'string' ? manuscript : '';- if (!text.trim()) return '';- const headerRe = /^#+\s*Issue\s+(\d+)\b[^\n]*$/gim;- const sections = [];- let match;- let prev = null;- while ((match = headerRe.exec(text)) !== null) {- if (prev) prev.end = match.index;- prev = { issue: Number(match[1]), start: headerRe.lastIndex, end: text.length };- sections.push(prev);- }- if (!sections.length) return '';- const markerRe = new RegExp(`\\b(?:${CONFLICT_INTENSITY_MARKERS.join('|')})\\b`, 'gi');- // Sum duplicate issue numbers (a repeated header across a stitch) — keep numeric- // order so the rendered curve reads issue 1 → N for the model.- const byIssue = new Map();- for (const sec of sections) {- const body = text.slice(sec.start, sec.end);- const words = (body.match(/\b[\w']+\b/g) || []).length;- const markers = (body.match(markerRe) || []).length;- const acc = byIssue.get(sec.issue) || { words: 0, markers: 0 };- byIssue.set(sec.issue, { words: acc.words + words, markers: acc.markers + markers });- }- const rows = [...byIssue.entries()]- .sort((a, b) => a[0] - b[0])- .map(([issue, { words, markers }]) => {- const density = words > 0 ? (markers / words) * 1000 : 0;- return `- Issue ${issue}: ${markers} conflict marker${markers === 1 ? '' : 's'} across `- + `${words} word${words === 1 ? '' : 's'} (${density.toFixed(1)} per 1k)`;- });- if (!rows.length) return '';- return 'Conflict-marker density per issue (deterministic intensity proxy — a rising '- + 'number suggests escalation, a flat or falling one a plateau / de-escalation; '- + 'treat as a hint and confirm against the prose):\n' + rows.join('\n');-}--// Human-readable POV-person labels for the head-hopping check's prompt (#1311).-// Inlined (not imported from styleGuide.js) to keep this registry pure — mirrors-// the labels in server/lib/styleGuide.js so generation and the check describe a-// POV person identically. An omniscient style guide no-ops via the check's gate,-// so it's intentionally absent here.-export const POV_PERSON_LABELS = Object.freeze({- first: 'first person',- 'third-limited': 'third-person limited',- second: 'second person',-});--// Render the reverse-outline scenes into a compact POV-focused block the-// head-hopping check (#1311) passes alongside the manuscript so the model knows-// WHOSE head each limited-POV scene is anchored to — and which other characters-// are on-stage (candidate heads a head-hop would slip into). EVERY scene is-// rendered: a scene with no recorded POV character is marked "POV: (not recorded-// — infer from the prose)" rather than dropped, so a PARTIALLY-tagged outline-// doesn't silently omit scenes and let the model assume the list is exhaustive of-// POV-bearing scenes (the model still confirms each anchor against the prose).-// Pure + deterministic so it's unit-testable and its token cost can be counted-// into the per-chunk overhead. Returns '' only when there are NO scenes at all-// (the prompt's `{{#povMap}}` section then renders nothing and the check degrades-// to a plain whole-issue scan). Type-guarded throughout — the reverse outline-// rides peer sync (#1348), so a hand-edited / older-peer scene could carry a-// non-string field that a bare `.trim()` would throw on.-export function scenePovSummary(scenes) {- const list = Array.isArray(scenes) ? scenes : [];- const lines = list.map((s) => {- if (!s || typeof s !== 'object') return '';- const label = sceneLabel(s);- const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;- const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';- const pov = scenePov(s);- // Other on-stage characters are the candidate heads a head-hop slips into —- // exclude the POV holder themselves (by normalized name) so the list names- // only "other" heads. When the scene has no recorded POV holder there's no- // one to exclude, so every present character is a candidate.- const povKey = pov ? normalizeName(pov) : '';- const others = Array.isArray(s.charactersPresent)- ? s.charactersPresent- .filter((n) => typeof n === 'string' && n.trim() && normalizeName(n) !== povKey)- .map((n) => n.trim())- : [];- const povText = pov ? `POV: ${pov}` : 'POV: (not recorded — infer from the prose)';- const parts = [`- ${where}: ${label} — ${povText}`];- if (others.length) parts.push(`others present: ${others.join(', ')}`);- return parts.join(' — ');- }).filter(Boolean);- if (!lines.length) return '';- return `POV per scene (from the reverse outline):\n${lines.join('\n')}`;-}--// Render the RECURRING NON-POV cast (#1585) into a compact text block the-// secondary-arc check passes alongside the manuscript, so the model focuses on-// the side characters that actually carry weight (present across multiple scenes)-// rather than every walk-on. A "secondary" character is one who appears in-// `charactersPresent` but NEVER holds `povCharacter` in ANY scene — a character-// who ever takes the viewpoint is a POV character (covered by pov.justified). For-// each such character we count the scenes they appear in and the span of issues-// those scenes touch, keeping only those at or above `minScenes` (the recurrence-// threshold). Pure + deterministic so it's unit-testable and its token cost can-// be counted into the per-chunk overhead. Returns '' when no non-POV character-// recurs enough (the prompt's `{{#secondaryCast}}` section then renders nothing-// and the check degrades to identifying recurring side characters from the prose-// alone). Type-guarded throughout — the reverse outline rides peer sync (#1348),-// so a hand-edited / older-peer scene could carry a non-string field a bare-// `.trim()` would throw on.-export function secondaryCharacterPresenceSummary(scenes, { minScenes = 2 } = {}) {- const list = Array.isArray(scenes) ? scenes : [];- const threshold = Number.isInteger(minScenes) && minScenes > 0 ? minScenes : 2;-- // Every character who EVER holds the viewpoint, by normalized name — these are- // POV characters and are excluded from the secondary cast even in scenes where- // they happen to be present-but-not-narrating.- const povHolders = new Set();- for (const s of list) {- const pov = scenePov(s);- if (pov) povHolders.add(normalizeName(pov));- }-- // Non-POV character → { name, sceneCount, issues } keyed by normalized name so- // casing / spacing variants collapse. Preserves first-appearance order (scenes- // arrive sequence-ordered) for stable output.- const cast = new Map();- for (const s of list) {- if (!s || typeof s !== 'object') continue;- const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;- const present = Array.isArray(s.charactersPresent)- ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())- : [];- // De-dup names within a single scene so a name listed twice counts once.- const seenThisScene = new Set();- for (const name of present) {- const key = normalizeName(name);- if (!key || povHolders.has(key) || seenThisScene.has(key)) continue;- seenThisScene.add(key);- let entry = cast.get(key);- if (!entry) { entry = { name, sceneCount: 0, issues: new Set() }; cast.set(key, entry); }- entry.sceneCount += 1;- if (issueNumber != null) entry.issues.add(issueNumber);- }- }-- const rows = [];- for (const entry of cast.values()) {- if (entry.sceneCount < threshold) continue;- const issues = [...entry.issues].sort((a, b) => a - b);- const span = issues.length- ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)- : 'no tagged issues';- rows.push(`- ${entry.name}: present in ${entry.sceneCount} scene${entry.sceneCount === 1 ? '' : 's'} (${span})`);- }- if (!rows.length) return '';- return `Recurring non-POV characters (appear in ${threshold}+ scenes but never hold POV — judge whether each shows meaningful change):\n${rows.join('\n')}`;-}--// ----------------------------------------------------------------------------// Registry entries.-// -----------------------------------------------------------------------------// Split a UI text field holding a phrase list (comma- or newline-separated) into-// trimmed, non-empty phrases — used by prose.cliches' allow/extra config fields.-export function splitPhraseList(value) {- if (typeof value !== 'string' || !value.trim()) return [];- return value.split(/[,\n]/).map((p) => p.trim()).filter(Boolean);-}--// ----------------------------------------------------------------------------// Copy-edit prose-tic checks (#1306). The deterministic word-level scanners live-// in proseTics.js / repetition.js; these helpers turn raw occurrences into the-// density-scaled findings the registry emits. Density matters: one "just" is-// fine, forty is a tic — so each check measures per-1000-word frequency against-// a configurable threshold and only flags when the rate (not the raw count) is-// high. Findings anchor on the FIRST offending occurrence in each section.-// -----------------------------------------------------------------------------// Word count of a section's prose (for per-1000-word density). Cheap word-// tokenization — apostrophes kept inside words so contractions count once.-export function countWords(text) {- return (String(text || '').match(/[A-Za-z][A-Za-z']*/g) || []).length;-}--// Map a section to its issue label/number once (used by every prose-tic check).-export function sectionIssue(s) {- const number = Number.isInteger(s?.number) ? s.number : null;- return { number, location: number != null ? `Issue ${number}` : 'Manuscript' };-}--// Shared driver for the per-1000-word density checks (filter words, crutch-// words, passive voice). For each section it runs the supplied `scan`, computes-// the per-1000-word rate, and emits one finding per section whose rate is at or-// above the configured `densityPer1000` — anchored to the first occurrence.-// `opts` declares the section scan, a noun for messages, and problem/suggestion-// builders. `scan(text, cfg)` returns `[{ index, anchor }, …]` occurrences.-export function runDensityCheck(ctx, opts) {- const cfg = ctx.config || {};- const max = cfg.maxFindings ?? 20;- const density = cfg.densityPer1000 ?? 0;- const sections = Array.isArray(ctx.sections) ? ctx.sections : [];- const findings = [];- for (const s of sections) {- if (findings.length >= max) break;- const text = s?.content || '';- const words = countWords(text);- if (words === 0) continue;- const hits = opts.scan(text, cfg);- if (!hits.length) continue;- const rate = Math.round((hits.length / words) * 1000 * 10) / 10;- if (rate < density) continue;- const { number, location } = sectionIssue(s);- findings.push({- severity: ctx.severityDefault,- category: 'style',- location,- problem: opts.problem(hits.length, rate, hits[0].anchor),- suggestion: opts.suggestion,- anchorQuote: hits[0].anchor,- issueNumber: number,- });- }- return findings;-}--// ----------------------------------------------------------------------------// Comic lettering density / balloon load (#1313) — deterministic over each-// issue's parsed comic script. The pure word/balloon accounting + threshold-// evaluation lives in ./letteringDensity.js (shared with the client comic-script-// stage's inline warnings); the helpers below turn its violations into-// manuscriptReview findings and pre-flight whether any issue even has a script-// (the check's gate). Scope is 'issue' — findings carry the issue number so the-// editor groups them per issue / per page.-// -----------------------------------------------------------------------------// The AUTHORITATIVE comic pages for an issue (parser-shaped `[{ panels: [...] }]`).-// A POPULATED per-page split (`stages.comicPages.pages[]`) WINS over the generated-// markdown (`stages.comicScript.output`): once a script is split into pages, edits-// in the Comic tab persist to `comicPages.pages[].rawText/panels` and never flow-// back to `comicScript.output`, so reading the raw script would analyze stale text-// (flag balloons the user already cut, miss ones they added). The client-// comic-script stage reads the same `comicPages.pages[].panels`, so both surfaces-// judge the same edited content.-//-// We key on `pages.length`, not `Array.isArray(pages)`, on purpose: the issue-// sanitizer (`sanitizeVisualStage`) ALWAYS materializes `comicPages.pages` as `[]`,-// so an EMPTY array can't distinguish "never split" from "split then all pages-// deleted" — they are byte-identical on disk. Falling back to the still-present-// generated script when the split is empty means an UNSPLIT or IMPORTED script-// (the common pre-render case, where lettering feedback matters most) is still-// checked; the script remains the issue's authored comic text even if a prior-// split was emptied.-export function comicIssuePages(issue) {- const pages = issue?.stages?.comicPages?.pages;- if (Array.isArray(pages) && pages.length) {- return pages.filter((p) => p && typeof p === 'object');- }- const output = typeof issue?.stages?.comicScript?.output === 'string' ? issue.stages.comicScript.output : '';- return output.trim() ? parseComicScript(output).pages : [];-}--// Issues with analyzable comic content, as { number, pages }, sorted by issue-// number for a stable scan order. Shared by the lettering check's `run` AND the-// staleness runner's fingerprint (which projects the lettering-relevant fields off-// this), so the fingerprinted content is exactly what the check analyzes.-export function comicLetteringIssues(issues) {- return (Array.isArray(issues) ? issues : [])- .map((i) => ({- number: Number.isInteger(i?.number) ? i.number : null,- pages: comicIssuePages(i),- }))- .filter((i) => i.pages.length)- .sort((a, b) => (a.number ?? 0) - (b.number ?? 0));-}--// Cheap presence test for the check's gate — true when any issue has an edited-// comic-pages split OR a non-empty generated script — without paying the parse-// that `comicLetteringIssues` does.-export function hasComicContent(issues) {- return (Array.isArray(issues) ? issues : []).some((i) => {- const pages = i?.stages?.comicPages?.pages;- if (Array.isArray(pages) && pages.length) return true;- return (typeof i?.stages?.comicScript?.output === 'string' ? i.stages.comicScript.output : '').trim();- });-}--// One human-readable { problem, suggestion } per violation kind. Kept here (not-// in the pure helper) because the wording is PortOS-facing copy, while the helper-// stays a reusable counting primitive.-function comicLetteringText(v) {- const who = v.speaker ? ` (${v.speaker})` : '';- switch (v.kind) {- case 'balloon-words':- return {- problem: `A balloon${who} runs ${v.count} words — over the ~${v.threshold}-word balloon limit. A wall of text crammed into one balloon is the #1 reader gripe in comics.`,- suggestion: 'Split the balloon in two, move some of it to a caption, or trim the line.',- };- case 'caption-words':- return {- problem: `A caption box runs ${v.count} words — over the ~${v.threshold}-word limit. A dense narration box buries the art the same way an over-stuffed balloon does.`,- suggestion: 'Tighten the caption, split it across panels, or cut it down.',- };- case 'panel-words':- return {- problem: `This panel carries ${v.count} words of lettering — over the ~${v.threshold}-word panel limit, crowding the art.`,- suggestion: 'Spread the lettering across more panels, or cut copy so the art can breathe.',- };- case 'panel-balloons':- return {- problem: `This panel has ${v.count} balloons — more than the ~${v.threshold} a single panel reads cleanly with.`,- suggestion: 'Break the exchange across more panels, or merge balloons from the same speaker.',- };- case 'page-words':- default:- return {- problem: `This page carries ${v.count} words of lettering — over the ~${v.threshold}-word page ceiling; the text load would overwhelm the art.`,- suggestion: 'Move some beats to adjacent pages, or trim copy so the page is not text-heavy.',- };- }-}--// Map a lettering violation to a manuscriptReview finding for issue `number`.-// `panelNumber` is absent for page-level findings, so the location degrades to-// "Issue N · Page P" cleanly. Severity rides the violation's overflow-scaled-// value (#1313).-export function comicLetteringFinding(v, number) {- const { problem, suggestion } = comicLetteringText(v);- const where = v.panelNumber != null- ? `Page ${v.pageNumber} · Panel ${v.panelNumber}`- : `Page ${v.pageNumber}`;- return {- severity: v.severity,- category: 'lettering',- location: number != null ? `Issue ${number} · ${where}` : where,- problem,- suggestion,- anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',- issueNumber: number,- };-}--// Map a balloon-attribution violation to a manuscriptReview finding for issue-// `number`. The wording is PortOS-facing copy (kept here, not in the pure-// helper). Severity rides the violation's risk-scaled value.-export function balloonAttributionFinding(v, number) {- const where = `Page ${v.pageNumber} · Panel ${v.panelNumber}`;- const more = v.panelCount > 1 ? ` (and ${v.panelCount - 1} more panel${v.panelCount - 1 === 1 ? '' : 's'} on this page)` : '';- const target = Array.isArray(v.visibleOthers) && v.visibleOthers.length- ? ` Another character (${v.visibleOthers.slice(0, 3).join(', ')}) IS shown on the page, so the balloon will likely be tailed to the wrong character.`- : ' No one is clearly shown speaking it, so the balloon reads as orphaned.';- return {- severity: v.severity,- category: 'continuity',- location: number != null ? `Issue ${number} · ${where}` : where,- problem: `${v.speaker} speaks here${more} but is not shown anywhere on the page and the line carries no off-panel/broadcast cue.${target}`,- suggestion: `Either show ${v.speaker} in a panel on this page, or mark the line as spoken from elsewhere — e.g. ${v.speaker} (OFF-PANEL), (V.O.), (RADIO), or (SPEAKERS)/(PA) for a broadcast — so it renders as a disembodied balloon instead of being attributed to a visible character.`,- anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',- issueNumber: number,- };-}--// ----------------------------------------------------------------------------// Comic ↔ prose synchronization helpers (#1589). The cross-media check pairs each-// hybrid issue's PROSE (a manuscript section) with its authoritative COMIC content-// and feeds the pair to the model. Pure + deterministic so they're unit-testable-// in isolation (the LLM caller is injected via ctx.callStagedLLM).-// -----------------------------------------------------------------------------// Per-issue prose ceiling fed to the comic↔prose check (#1589) — so a long-// chapter can't blow a small/local provider's window. Unlike the manuscript--// corpus checks (which chunk the whole series), this check makes ONE call per-// hybrid issue with that issue's prose + comic, so the bound is per-issue. The-// comic content is the smaller, authoritative anchor; the prose is sliced to this-// ceiling and the prompt warns the model the prose may be truncated. ~24k chars-// ≈ 6k tokens, which fits alongside the comic block on every supported provider.-export const PROSE_SYNC_PROSE_CHAR_CAP = 24_000;--// Extract an issue's PROSE-stage text. Inlines arcPlanner's `stageTextOf` (output-// then input) to keep the registry import-pure (no service import). Reads the-// `prose` stage SPECIFICALLY — NOT the default manuscript precedence (comicScript ▸-// teleplay ▸ prose), which for a hybrid comic+prose issue would return the comic-// script, not the prose (the bug this check exists to avoid). Returns '' when the-// issue has no prose-stage text.-function proseStageText(issue) {- const stage = issue?.stages?.prose;- const output = typeof stage?.output === 'string' ? stage.output.trim() : '';- if (output) return output;- return typeof stage?.input === 'string' ? stage.input.trim() : '';-}--// Per-issue PROSE-stage content, as `{ number, prose }`, sorted by issue number.-// The single source of truth for "the prose half" of the comic↔prose-sync check —-// read by BOTH the check's `run` AND the runner's `prose` staleness resolver-// (mirrors `comicLetteringIssues` for the comic half), so the fingerprinted text is-// exactly what the check compares. Only issues with prose-stage text contribute.-export function proseStageIssues(issues) {- return (Array.isArray(issues) ? issues : [])- .map((i) => ({ number: Number.isInteger(i?.number) ? i.number : null, prose: proseStageText(i) }))- .filter((i) => i.prose)- .sort((a, b) => (a.number ?? 0) - (b.number ?? 0));-}--// Render an issue's parsed comic pages into a compact, model-readable block —-// page/panel headers plus each panel's visual DESCRIPTION (what the panel SHOWS),-// DIALOGUE (`speaker: line`), CAPTION, and SFX — so the model can compare what the-// comic shows and says against the prose. Mirrors the field set in-// `projectComicPacingContent` (the `comicScript.pacing` source this check-// fingerprints), so the rendered content matches what staleness tracks. Returns ''-// when no panel carries any content.-export function renderComicForProseSync(pages) {- const lines = [];- (Array.isArray(pages) ? pages : []).forEach((p, pageIdx) => {- const panels = Array.isArray(p?.panels) ? p.panels : [];- panels.forEach((panel, panelIdx) => {- const block = [];- const desc = typeof panel?.description === 'string' ? panel.description.trim() : '';- if (desc) block.push(` Shows: ${desc}`);- for (const d of (Array.isArray(panel?.dialogue) ? panel.dialogue : [])) {- // The comic-script parser keys the speaker as `character` ({ character, line }),- // the same field balloonAttribution/letteringDensity read — NOT `speaker`.- // Tolerate a `speaker` alias for robustness, but `character` is the real shape.- const rawSpeaker = typeof d?.character === 'string' ? d.character : (typeof d?.speaker === 'string' ? d.speaker : '');- const speaker = rawSpeaker.trim();- const line = typeof d?.line === 'string' ? d.line.trim() : '';- if (line) block.push(` ${speaker ? `${speaker}: ` : ''}${line}`);- }- const caption = typeof panel?.caption === 'string' ? panel.caption.trim() : '';- if (caption) block.push(` Caption: ${caption}`);- const sfx = typeof panel?.sfx === 'string' ? panel.sfx.trim() : '';- if (sfx) block.push(` SFX: ${sfx}`);- // Skip an entirely empty panel — no content to cross-check against prose.- if (block.length) {- lines.push(`Page ${pageIdx + 1} · Panel ${panelIdx + 1}`, ...block);- }- });- });- return lines.join('\n');-}-// The issues that have BOTH drafted PROSE-stage text AND comic content — the-// comparable set for the comic↔prose sync check. Returns `[{ number, prose, comic }]`-// sorted by issue number (`comicLetteringIssues` already sorts), prose sliced to-// PROSE_SYNC_PROSE_CHAR_CAP. An issue with comic but no prose (or prose but no-// comic) has nothing to cross-check and is skipped. Pure: reads ctx.issues only —-// both halves come off the already-loaded issue records (the prose STAGE, not the-// comicScript-precedence manuscript section).-export function proseSyncPairs(ctx) {- const proseByIssue = new Map();- for (const { number, prose } of proseStageIssues(ctx?.issues)) {- if (Number.isInteger(number)) proseByIssue.set(number, prose);- }- const pairs = [];- for (const { number, pages } of comicLetteringIssues(ctx?.issues)) {- if (!Number.isInteger(number)) continue;- const prose = proseByIssue.get(number);- if (!prose) continue;- const comic = renderComicForProseSync(pages);- if (!comic.trim()) continue;- pairs.push({ number, prose: prose.slice(0, PROSE_SYNC_PROSE_CHAR_CAP), comic });- }- return pairs;-}+export * from './checkInfra/externals.js';+export * from './checkInfra/taxonomy.js';+export * from './checkInfra/revealForeshadowing.js';+export * from './checkInfra/craftStages.js';+export * from './checkInfra/voiceCanon.js';+export * from './checkInfra/structureStages.js';+export * from './checkInfra/povAndNames.js';+export * from './checkInfra/canonScaffolding.js';+export * from './checkInfra/llmRunner.js';+export * from './checkInfra/readability.js';+export * from './checkInfra/rosterCast.js';+export * from './checkInfra/sceneAnalysis.js';+export * from './checkInfra/proseDensity.js';+export * from './checkInfra/comic.js';diff --git a/server/lib/editorial/checkInfra/canonScaffolding.js b/server/lib/editorial/checkInfra/canonScaffolding.jsnew file mode 100644index 0000000000..b266bd6ba9--- /dev/null+++ b/server/lib/editorial/checkInfra/canonScaffolding.js@@ -0,0 +1,140 @@+/**+ * Shared canon-walking scaffolding for the relationship-link (#1287) and+ * object-attachment (#1288) check families (#2842 split of checkInfra.js).+ */++// ---------------------------------------------------------------------------+// Shared scaffolding for the relationship-link checks (#1287). All three walk+// `canon.characters × relationshipLinks`, so the id-bearing character list,+// the id→name lookup, and the link iteration live here once.+// ---------------------------------------------------------------------------++// Id-bearing characters + an id→name lookup (falling back to the id when a+// character is unnamed). The three checks index off this same pair.+export function relationshipCanon(ctx) {+ const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);+ return { chars, nameById: new Map(chars.map((c) => [c.id, c.name || c.id])) };+}++// Yields every relationship link that points somewhere, as { c, link, targetId }.+export function* eachRelationshipLink(chars) {+ for (const c of chars) {+ for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {+ if (link?.targetCharacterId) yield { c, link, targetId: link.targetCharacterId };+ }+ }+}++// ---------------------------------------------------------------------------+// Shared scaffolding for the object-attachment checks (#1288). All three walk+// `canon.objects × attachments`, resolving each attachment's `characterId`+// against the cast, so the id-bearing object/character lists, the id→character+// lookup, and the attachment iteration live here once.+// ---------------------------------------------------------------------------++export function attachmentCanon(ctx) {+ const objects = (ctx.canon?.objects || []).filter((o) => o && o.id);+ const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);+ return {+ objects,+ chars,+ nameById: new Map(chars.map((c) => [c.id, c.name || c.id])),+ charById: new Map(chars.map((c) => [c.id, c])),+ };+}++// Yields every attachment that points at a character, as { o, att }.+function* eachAttachment(objects) {+ for (const o of objects) {+ for (const att of (Array.isArray(o.attachments) ? o.attachments : [])) {+ if (att?.characterId) yield { o, att };+ }+ }+}++// A human-readable summary of every object + who's attached to it, fed to the+// unmotivated-interaction LLM so it knows which objects already carry an+// established stake (and which don't) before judging a prose interaction.+export function describeObjectAttachments(ctx) {+ const { objects, nameById } = attachmentCanon(ctx);+ const lines = [];+ for (const o of objects) {+ const atts = Array.isArray(o.attachments) ? o.attachments : [];+ const sig = (o.significance || '').trim();+ const attText = atts.length+ ? atts.map((a) => {+ const who = nameById.get(a.characterId) || a.characterId;+ const emotion = a.emotion ? ` (${a.emotion})` : '';+ const why = a.significance ? ` — ${a.significance}` : '';+ return `${who}${emotion}${why}`;+ }).join('; ')+ : 'nobody';+ lines.push(`- ${o.name || o.id}${sig ? ` — significance: ${sig}` : ''}\n attached to: ${attText}`);+ }+ return lines.join('\n') || '(no objects in canon)';+}++// A richer per-object weight summary for the weight-proportionality check+// (#1624). Unlike describeObjectAttachments (which the unmotivated-interaction+// check uses to know who already cares about an object), this surfaces the FULL+// recorded weight an object carries going in — the prose significance plus every+// attachment's emotion, per-bond significance, ORIGIN (the lineage/backstory),+// and ROLE archetype — so the model can weigh that recorded backstory against+// how prominent the object actually is in the manuscript. The origin/role fields+// are exactly the "rich recorded backstory for a barely used object" signal the+// over-weighted verdict depends on, which the leaner attachments summary omits.+export function describeObjectWeight(ctx) {+ const { objects, nameById } = attachmentCanon(ctx);+ const lines = [];+ for (const o of objects) {+ const atts = Array.isArray(o.attachments) ? o.attachments : [];+ const sig = (o.significance || '').trim();+ const head = `- ${o.name || o.id}${sig ? ` — significance: ${sig}` : ''}`;+ if (!atts.length) {+ lines.push(`${head}\n attachments: none`);+ continue;+ }+ const attLines = atts.map((a) => {+ const who = nameById.get(a.characterId) || a.characterId || 'unknown';+ const emotion = (a.emotion || '').trim();+ const significance = (a.significance || '').trim();+ const origin = (a.origin || '').trim();+ const role = (a.role || '').trim();+ const parts = [+ ` • ${who}${emotion ? ` (${emotion})` : ''}${role ? ` [${role}]` : ''}`,+ ];+ if (significance) parts.push(` significance: ${significance}`);+ if (origin) parts.push(` origin: ${origin}`);+ return parts.join('\n');+ });+ lines.push(`${head}\n${attLines.join('\n')}`);+ }+ return lines.join('\n') || '(no objects in canon)';+}++// The attachment rows whose `origin` can be checked against the attached+// character's `background` — both must be present, and the character must+// still exist (a dangling characterId is the UI/sanitizer's concern, not this+// check's). Shared by the backstory-consistency check's `gate` (cheap presence+// test) and its `run` (the actual prompt rows) so they never disagree.+export function attachmentBackstoryRows(ctx) {+ const { objects, charById } = attachmentCanon(ctx);+ const rows = [];+ for (const { o, att } of eachAttachment(objects)) {+ const origin = (att.origin || '').trim();+ if (!origin) continue;+ const char = charById.get(att.characterId);+ if (!char) continue;+ const background = (char.background || '').trim();+ if (!background) continue;+ rows.push({+ object: o.name || o.id,+ character: char.name || char.id,+ emotion: (att.emotion || '').trim(),+ origin,+ background,+ });+ }+ return rows;+}+diff --git a/server/lib/editorial/checkInfra/comic.js b/server/lib/editorial/checkInfra/comic.jsnew file mode 100644index 0000000000..75a4493a77--- /dev/null+++ b/server/lib/editorial/checkInfra/comic.js@@ -0,0 +1,245 @@+/**+ * Comic-specific check helpers (#2842 split of checkInfra.js): lettering density+ * / balloon load accounting (#1313) and the comic↔prose synchronization pairing+ * (#1589).+ */++import { parseComicScript } from './externals.js';++// ---------------------------------------------------------------------------+// Comic lettering density / balloon load (#1313) — deterministic over each+// issue's parsed comic script. The pure word/balloon accounting + threshold+// evaluation lives in ./letteringDensity.js (shared with the client comic-script+// stage's inline warnings); the helpers below turn its violations into+// manuscriptReview findings and pre-flight whether any issue even has a script+// (the check's gate). Scope is 'issue' — findings carry the issue number so the+// editor groups them per issue / per page.+// ---------------------------------------------------------------------------++// The AUTHORITATIVE comic pages for an issue (parser-shaped `[{ panels: [...] }]`).+// A POPULATED per-page split (`stages.comicPages.pages[]`) WINS over the generated+// markdown (`stages.comicScript.output`): once a script is split into pages, edits+// in the Comic tab persist to `comicPages.pages[].rawText/panels` and never flow+// back to `comicScript.output`, so reading the raw script would analyze stale text+// (flag balloons the user already cut, miss ones they added). The client+// comic-script stage reads the same `comicPages.pages[].panels`, so both surfaces+// judge the same edited content.+//+// We key on `pages.length`, not `Array.isArray(pages)`, on purpose: the issue+// sanitizer (`sanitizeVisualStage`) ALWAYS materializes `comicPages.pages` as `[]`,+// so an EMPTY array can't distinguish "never split" from "split then all pages+// deleted" — they are byte-identical on disk. Falling back to the still-present+// generated script when the split is empty means an UNSPLIT or IMPORTED script+// (the common pre-render case, where lettering feedback matters most) is still+// checked; the script remains the issue's authored comic text even if a prior+// split was emptied.+export function comicIssuePages(issue) {+ const pages = issue?.stages?.comicPages?.pages;+ if (Array.isArray(pages) && pages.length) {+ return pages.filter((p) => p && typeof p === 'object');+ }+ const output = typeof issue?.stages?.comicScript?.output === 'string' ? issue.stages.comicScript.output : '';+ return output.trim() ? parseComicScript(output).pages : [];+}++// Issues with analyzable comic content, as { number, pages }, sorted by issue+// number for a stable scan order. Shared by the lettering check's `run` AND the+// staleness runner's fingerprint (which projects the lettering-relevant fields off+// this), so the fingerprinted content is exactly what the check analyzes.+export function comicLetteringIssues(issues) {+ return (Array.isArray(issues) ? issues : [])+ .map((i) => ({+ number: Number.isInteger(i?.number) ? i.number : null,+ pages: comicIssuePages(i),+ }))+ .filter((i) => i.pages.length)+ .sort((a, b) => (a.number ?? 0) - (b.number ?? 0));+}++// Cheap presence test for the check's gate — true when any issue has an edited+// comic-pages split OR a non-empty generated script — without paying the parse+// that `comicLetteringIssues` does.+export function hasComicContent(issues) {+ return (Array.isArray(issues) ? issues : []).some((i) => {+ const pages = i?.stages?.comicPages?.pages;+ if (Array.isArray(pages) && pages.length) return true;+ return (typeof i?.stages?.comicScript?.output === 'string' ? i.stages.comicScript.output : '').trim();+ });+}++// One human-readable { problem, suggestion } per violation kind. Kept here (not+// in the pure helper) because the wording is PortOS-facing copy, while the helper+// stays a reusable counting primitive.+function comicLetteringText(v) {+ const who = v.speaker ? ` (${v.speaker})` : '';+ switch (v.kind) {+ case 'balloon-words':+ return {+ problem: `A balloon${who} runs ${v.count} words — over the ~${v.threshold}-word balloon limit. A wall of text crammed into one balloon is the #1 reader gripe in comics.`,+ suggestion: 'Split the balloon in two, move some of it to a caption, or trim the line.',+ };+ case 'caption-words':+ return {+ problem: `A caption box runs ${v.count} words — over the ~${v.threshold}-word limit. A dense narration box buries the art the same way an over-stuffed balloon does.`,+ suggestion: 'Tighten the caption, split it across panels, or cut it down.',+ };+ case 'panel-words':+ return {+ problem: `This panel carries ${v.count} words of lettering — over the ~${v.threshold}-word panel limit, crowding the art.`,+ suggestion: 'Spread the lettering across more panels, or cut copy so the art can breathe.',+ };+ case 'panel-balloons':+ return {+ problem: `This panel has ${v.count} balloons — more than the ~${v.threshold} a single panel reads cleanly with.`,+ suggestion: 'Break the exchange across more panels, or merge balloons from the same speaker.',+ };+ case 'page-words':+ default:+ return {+ problem: `This page carries ${v.count} words of lettering — over the ~${v.threshold}-word page ceiling; the text load would overwhelm the art.`,+ suggestion: 'Move some beats to adjacent pages, or trim copy so the page is not text-heavy.',+ };+ }+}++// Map a lettering violation to a manuscriptReview finding for issue `number`.+// `panelNumber` is absent for page-level findings, so the location degrades to+// "Issue N · Page P" cleanly. Severity rides the violation's overflow-scaled+// value (#1313).+export function comicLetteringFinding(v, number) {+ const { problem, suggestion } = comicLetteringText(v);+ const where = v.panelNumber != null+ ? `Page ${v.pageNumber} · Panel ${v.panelNumber}`+ : `Page ${v.pageNumber}`;+ return {+ severity: v.severity,+ category: 'lettering',+ location: number != null ? `Issue ${number} · ${where}` : where,+ problem,+ suggestion,+ anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',+ issueNumber: number,+ };+}++// Map a balloon-attribution violation to a manuscriptReview finding for issue+// `number`. The wording is PortOS-facing copy (kept here, not in the pure+// helper). Severity rides the violation's risk-scaled value.+export function balloonAttributionFinding(v, number) {+ const where = `Page ${v.pageNumber} · Panel ${v.panelNumber}`;+ const more = v.panelCount > 1 ? ` (and ${v.panelCount - 1} more panel${v.panelCount - 1 === 1 ? '' : 's'} on this page)` : '';+ const target = Array.isArray(v.visibleOthers) && v.visibleOthers.length+ ? ` Another character (${v.visibleOthers.slice(0, 3).join(', ')}) IS shown on the page, so the balloon will likely be tailed to the wrong character.`+ : ' No one is clearly shown speaking it, so the balloon reads as orphaned.';+ return {+ severity: v.severity,+ category: 'continuity',+ location: number != null ? `Issue ${number} · ${where}` : where,+ problem: `${v.speaker} speaks here${more} but is not shown anywhere on the page and the line carries no off-panel/broadcast cue.${target}`,+ suggestion: `Either show ${v.speaker} in a panel on this page, or mark the line as spoken from elsewhere — e.g. ${v.speaker} (OFF-PANEL), (V.O.), (RADIO), or (SPEAKERS)/(PA) for a broadcast — so it renders as a disembodied balloon instead of being attributed to a visible character.`,+ anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',+ issueNumber: number,+ };+}++// ---------------------------------------------------------------------------+// Comic ↔ prose synchronization helpers (#1589). The cross-media check pairs each+// hybrid issue's PROSE (a manuscript section) with its authoritative COMIC content+// and feeds the pair to the model. Pure + deterministic so they're unit-testable+// in isolation (the LLM caller is injected via ctx.callStagedLLM).+// ---------------------------------------------------------------------------++// Per-issue prose ceiling fed to the comic↔prose check (#1589) — so a long+// chapter can't blow a small/local provider's window. Unlike the manuscript-+// corpus checks (which chunk the whole series), this check makes ONE call per+// hybrid issue with that issue's prose + comic, so the bound is per-issue. The+// comic content is the smaller, authoritative anchor; the prose is sliced to this+// ceiling and the prompt warns the model the prose may be truncated. ~24k chars+// ≈ 6k tokens, which fits alongside the comic block on every supported provider.+export const PROSE_SYNC_PROSE_CHAR_CAP = 24_000;++// Extract an issue's PROSE-stage text. Inlines arcPlanner's `stageTextOf` (output+// then input) to keep the registry import-pure (no service import). Reads the+// `prose` stage SPECIFICALLY — NOT the default manuscript precedence (comicScript ▸+// teleplay ▸ prose), which for a hybrid comic+prose issue would return the comic+// script, not the prose (the bug this check exists to avoid). Returns '' when the+// issue has no prose-stage text.+function proseStageText(issue) {+ const stage = issue?.stages?.prose;+ const output = typeof stage?.output === 'string' ? stage.output.trim() : '';+ if (output) return output;+ return typeof stage?.input === 'string' ? stage.input.trim() : '';+}++// Per-issue PROSE-stage content, as `{ number, prose }`, sorted by issue number.+// The single source of truth for "the prose half" of the comic↔prose-sync check —+// read by BOTH the check's `run` AND the runner's `prose` staleness resolver+// (mirrors `comicLetteringIssues` for the comic half), so the fingerprinted text is+// exactly what the check compares. Only issues with prose-stage text contribute.+export function proseStageIssues(issues) {+ return (Array.isArray(issues) ? issues : [])+ .map((i) => ({ number: Number.isInteger(i?.number) ? i.number : null, prose: proseStageText(i) }))+ .filter((i) => i.prose)+ .sort((a, b) => (a.number ?? 0) - (b.number ?? 0));+}++// Render an issue's parsed comic pages into a compact, model-readable block —+// page/panel headers plus each panel's visual DESCRIPTION (what the panel SHOWS),+// DIALOGUE (`speaker: line`), CAPTION, and SFX — so the model can compare what the+// comic shows and says against the prose. Mirrors the field set in+// `projectComicPacingContent` (the `comicScript.pacing` source this check+// fingerprints), so the rendered content matches what staleness tracks. Returns ''+// when no panel carries any content.+export function renderComicForProseSync(pages) {+ const lines = [];+ (Array.isArray(pages) ? pages : []).forEach((p, pageIdx) => {+ const panels = Array.isArray(p?.panels) ? p.panels : [];+ panels.forEach((panel, panelIdx) => {+ const block = [];+ const desc = typeof panel?.description === 'string' ? panel.description.trim() : '';+ if (desc) block.push(` Shows: ${desc}`);+ for (const d of (Array.isArray(panel?.dialogue) ? panel.dialogue : [])) {+ // The comic-script parser keys the speaker as `character` ({ character, line }),+ // the same field balloonAttribution/letteringDensity read — NOT `speaker`.+ // Tolerate a `speaker` alias for robustness, but `character` is the real shape.+ const rawSpeaker = typeof d?.character === 'string' ? d.character : (typeof d?.speaker === 'string' ? d.speaker : '');+ const speaker = rawSpeaker.trim();+ const line = typeof d?.line === 'string' ? d.line.trim() : '';+ if (line) block.push(` ${speaker ? `${speaker}: ` : ''}${line}`);+ }+ const caption = typeof panel?.caption === 'string' ? panel.caption.trim() : '';+ if (caption) block.push(` Caption: ${caption}`);+ const sfx = typeof panel?.sfx === 'string' ? panel.sfx.trim() : '';+ if (sfx) block.push(` SFX: ${sfx}`);+ // Skip an entirely empty panel — no content to cross-check against prose.+ if (block.length) {+ lines.push(`Page ${pageIdx + 1} · Panel ${panelIdx + 1}`, ...block);+ }+ });+ });+ return lines.join('\n');+}++// The issues that have BOTH drafted PROSE-stage text AND comic content — the+// comparable set for the comic↔prose sync check. Returns `[{ number, prose, comic }]`+// sorted by issue number (`comicLetteringIssues` already sorts), prose sliced to+// PROSE_SYNC_PROSE_CHAR_CAP. An issue with comic but no prose (or prose but no+// comic) has nothing to cross-check and is skipped. Pure: reads ctx.issues only —+// both halves come off the already-loaded issue records (the prose STAGE, not the+// comicScript-precedence manuscript section).+export function proseSyncPairs(ctx) {+ const proseByIssue = new Map();+ for (const { number, prose } of proseStageIssues(ctx?.issues)) {+ if (Number.isInteger(number)) proseByIssue.set(number, prose);+ }+ const pairs = [];+ for (const { number, pages } of comicLetteringIssues(ctx?.issues)) {+ if (!Number.isInteger(number)) continue;+ const prose = proseByIssue.get(number);+ if (!prose) continue;+ const comic = renderComicForProseSync(pages);+ if (!comic.trim()) continue;+ pairs.push({ number, prose: prose.slice(0, PROSE_SYNC_PROSE_CHAR_CAP), comic });+ }+ return pairs;+}diff --git a/server/lib/editorial/checkInfra/craftStages.js b/server/lib/editorial/checkInfra/craftStages.jsnew file mode 100644index 0000000000..c4016985de--- /dev/null+++ b/server/lib/editorial/checkInfra/craftStages.js@@ -0,0 +1,112 @@+/**+ * Line-craft stage names (#2842 split of checkInfra.js) — the prose anti-pattern,+ * adversarial-cut, sensory/white-room, arc-transition and dialogue-subtext stages+ * plus their small constant vocabularies (`CUT_TYPES`, `ON_THE_NOSE_SUBTYPES`).+ */++// Stage name for the cliché / dead-metaphor / overwriting LLM check (#1308).+// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs+// via setup-data.js) and migrates to existing installs via migration 101 (boot+// runs migrations but NOT setup-data, so the migration is required). The+// deterministic siblings (prose.cliches, prose.modifier-stacking) need no stage.+export const DEAD_METAPHOR_STAGE = 'pipeline-editorial-dead-metaphor';++// Stage names for the four LLM prose anti-pattern checks (#1300). Each prompt+// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migrations 103–106 (boot+// runs migrations but NOT setup-data, so the migration is required — see+// scripts/migrations/103-…js … 106-…js). The deterministic sibling+// (prose.italic-thoughts) needs no stage.+export const OPENING_START_STAGE = 'pipeline-editorial-opening-start';+export const MIRROR_DESCRIPTION_STAGE = 'pipeline-editorial-mirror-description';+export const DIALOGUE_PLEASANTRIES_STAGE = 'pipeline-editorial-dialogue-pleasantries';+export const KILL_YOUR_DARLINGS_STAGE = 'pipeline-editorial-kill-your-darlings';++// Stage name for the adversarial-cuts prose-tightening LLM check (#2168). Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js); new file so no migration needed. Asks a ruthless editor+// persona to cut 8–12% of the text, classifying each cut (FAT, REDUNDANT,+// OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL). Safe types (OVER-EXPLAIN, REDUNDANT)+// can be batch-applied mechanically.+export const ADVERSARIAL_CUTS_STAGE = 'pipeline-editorial-adversarial-cuts';++// The six cut types the adversarial-cuts check returns, ordered by safe-to-auto-+// apply (the first two are the "safe majority" per the design doc). The applier+// defaults to OVER-EXPLAIN + REDUNDANT only; other types require manual review.+export const CUT_TYPES = Object.freeze([+ 'OVER-EXPLAIN',+ 'REDUNDANT',+ 'FAT',+ 'GENERIC',+ 'TELL',+ 'STRUCTURAL',+]);+// The subset that can be auto-applied without manual review.+export const SAFE_CUT_TYPES = Object.freeze(['OVER-EXPLAIN', 'REDUNDANT']);++// Stage names for the two scene-grounding LLM checks (#1309): sensory balance+// (all-visual / sensory-bare scenes) and white-room (ungrounded, setting-less+// scenes). Each prompt ships in data.reference/prompts/stages/ + stage-config.json+// (fresh installs via setup-data.js) and migrates to existing installs via+// migration 107 (boot runs migrations but NOT setup-data, so the migration is+// required). Both consume the reverse-outline scene segmentation as context and+// degrade to a whole-issue manuscript scan when no outline exists.+export const SENSORY_BALANCE_STAGE = 'pipeline-editorial-sensory-balance';+export const WHITE_ROOM_STAGE = 'pipeline-editorial-white-room';++// Stage name for the interiority-balance LLM check (#1623): visually dense but+// emotionally empty scenes — heavy on description, light on POV reaction. Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 142 (boot runs+// migrations but NOT setup-data, so the migration is required). Like the two+// scene-grounding checks above it consumes the reverse-outline scene+// segmentation as context and degrades to a whole-issue manuscript scan when no+// outline exists.+export const INTERIORITY_BALANCE_STAGE = 'pipeline-editorial-interiority-balance';++// Stage name for the character-arc transition-detection LLM check (#1293). Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 109 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the+// stitched manuscript plus the reverse-outline scene map and the AUTHORED+// per-character arcs to surface genuine change moments + flat-arc warnings.+export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';++// Stage name for the character-arc regression / premature-closure LLM check+// (#1619). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration 141+// (boot runs migrations but NOT setup-data, so the migration is required). Reads+// the stitched manuscript plus the reverse-outline scene map and the AUTHORED+// per-character arcs, tracks each character's progress across the issues, and+// flags regression (growth then an unmotivated revert), a circular arc (ends+// where it began), or premature closure (an arc resolved early then flat for the+// rest of the series). Complements arc.transitions (which detects the change+// MOMENTS) by judging the SHAPE of each character's progress across the whole arc.+export const ARC_REGRESSION_STAGE = 'pipeline-editorial-arc-regression';++// Stage name for the telling-not-showing-emotion LLM check (#1306). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 110 (boot runs+// migrations but NOT setup-data, so the migration is required). The deterministic+// copy-edit siblings (prose.filter-words, prose.crutch-words, prose.adverbs,+// prose.passive-voice, prose.repeated-gestures, prose.word-echoes,+// prose.sentence-rhythm) need no stage.+export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';++// Stage names for the two dialogue-craft LLM checks (#1307): on-the-nose /+// subtext-free dialogue, and per-character voice distinctiveness. Each prompt+// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migrations 112–113 (boot+// runs migrations but NOT setup-data, so the migration is required). The+// deterministic siblings (dialogue.said-bookisms, dialogue.attribution-clarity)+// need no stage.+export const ON_THE_NOSE_STAGE = 'pipeline-editorial-on-the-nose';+export const VOICE_DISTINCTIVENESS_STAGE = 'pipeline-editorial-voice-distinctiveness';++// Finding subtypes for `dialogue.on-the-nose` (#1626) — the stage prompt classifies+// each subtext-free line into *why* it reads on-the-nose so the writer gets specific,+// actionable feedback instead of a flat "on-the-nose" label. Surfaced on the finding+// (and persisted comment) as `subtype`; the runner validates the model's value against+// this allow-list and drops anything off-list (→ null) so a stray label can't leak through.+export const ON_THE_NOSE_SUBTYPES = ['exposition', 'emotion-tell', 'relationship-report'];+diff --git a/server/lib/editorial/checkInfra/externals.js b/server/lib/editorial/checkInfra/externals.jsnew file mode 100644index 0000000000..a75d29a6ab--- /dev/null+++ b/server/lib/editorial/checkInfra/externals.js@@ -0,0 +1,115 @@+/**+ * Editorial check infra — external primitives hub (#2842 split of checkInfra.js).+ *+ * The single place `./checks/*.js` and `checkRegistry.js` reach for the pure+ * scanners in the sibling editorial libs plus `zod`/`estimateTokens`. Kept as+ * one hub so a check file imports everything from `checkInfra.js` (the barrel)+ * without fanning out to a dozen deep imports.+ */++import { z } from 'zod';+import { estimateTokens } from '../../contextBudget.js';+import { renderCharacterArcsForPrompt } from '../../seriesCharacterArc.js';+import { parseComicScript } from '../../comicScriptParser.js';+import {+ analyzeComicLettering,+ DEFAULT_LETTERING_THRESHOLDS,+} from '../letteringDensity.js';+import { analyzeBalloonAttribution } from '../balloonAttribution.js';+import { analyzeNamePair, comparisonName, findFirstLetterClusters, normalizeName } from '../nameSimilarity.js';+import { findCliches, findModifierStacking } from '../cliches.js';+import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner, findDialogueTagVariety, splitScenes } from '../dialogue.js';+import { findItalicThoughts } from '../italicThoughts.js';+import {+ findFilterWords,+ findHedgeWords,+ findCrutchWords,+ findAdverbs,+ findPassiveVoice,+ filterPassiveVoice,+ findGestures,+} from '../proseTics.js';+import {+ findWordEchoes,+ findRepeatedOpeners,+ measureSentenceRhythm,+} from '../repetition.js';+import {+ findBannedWordsTier1,+ findSuspiciousWordClusters,+ findAiTells,+ findNotJustButPatterns,+ findNotSayingPatterns,+ findNegativeAssertions,+ findTheWaySimiles,+ findTriadicShortSentences,+ findStructuralTics,+ emDashDensityPer1000,+ transitionOpenerRatio,+ paragraphLengthUniformity,+ countSectionBreaks,+ MIN_DENSITY_OCCURRENCES,+} from '../slopScore.js';+import {+ analyzePanelRhythm,+ comicPageTurnSummary,+ authoredRevealSummary,+} from '../comicPacing.js';+import { findAxisReversals, findShotTypeMonotony, summarizeStoryboardShots } from '../shotContinuity.js';+import { revealGatedCanonRows, canonHasRevealGated } from '../../storyBible.js';++// Re-exported so ./checks/*.js and ./checkRegistry.js import everything from here.+export {+ DEFAULT_LETTERING_THRESHOLDS,+ MIN_DENSITY_OCCURRENCES,+ analyzeBalloonAttribution,+ analyzeComicLettering,+ analyzeNamePair,+ analyzePanelRhythm,+ attributeDialogueByOwner,+ authoredRevealSummary,+ comicPageTurnSummary,+ comparisonName,+ countSectionBreaks,+ emDashDensityPer1000,+ estimateTokens,+ filterPassiveVoice,+ findAdverbs,+ findAiTells,+ findAxisReversals,+ findBannedWordsTier1,+ findCliches,+ findCrutchWords,+ findDialogueTagVariety,+ findFilterWords,+ findFirstLetterClusters,+ findGestures,+ findHedgeWords,+ findItalicThoughts,+ findModifierStacking,+ findNegativeAssertions,+ findNotJustButPatterns,+ findNotSayingPatterns,+ findPassiveVoice,+ findRepeatedOpeners,+ findSaidBookisms,+ findShotTypeMonotony,+ findStructuralTics,+ findSuspiciousWordClusters,+ findTheWaySimiles,+ findTriadicShortSentences,+ findUnattributedDialogueRuns,+ findWordEchoes,+ measureSentenceRhythm,+ normalizeName,+ paragraphLengthUniformity,+ parseComicScript,+ renderCharacterArcsForPrompt,+ splitScenes,+ summarizeStoryboardShots,+ transitionOpenerRatio,+ canonHasRevealGated,+ revealGatedCanonRows,+ z,+};+diff --git a/server/lib/editorial/checkInfra/llmRunner.js b/server/lib/editorial/checkInfra/llmRunner.jsnew file mode 100644index 0000000000..3eabd269d1--- /dev/null+++ b/server/lib/editorial/checkInfra/llmRunner.js@@ -0,0 +1,436 @@+/**+ * Shared LLM-check execution helpers (#2842 split of checkInfra.js): manuscript+ * chunk planning, the cross-chunk prior-findings and setup digests, the staged+ * and inline (user-defined) manuscript runners, and raw-finding normalization.+ */++import { estimateTokens } from './externals.js';+import { SEVERITIES, CUSTOM_CHECK_MAX_FINDINGS_DEFAULT } from './taxonomy.js';++// ---------------------------------------------------------------------------+// Shared LLM-check helpers. Every `kind: 'llm'` check normalizes the model's+// raw findings into the manuscriptReview comment shape, and a manuscript-+// consuming check additionally feeds the whole corpus to the model in+// provider-sized chunks (so a long series isn't truncated on a small/local+// provider) and merges the per-chunk findings. These collapse those repeated+// blocks so the field validation + chunk-merge live once.+// ---------------------------------------------------------------------------++// Fixed per-call prompt overhead (template scaffolding + JSON-shape+// instructions) reserved on top of any check-specific static vars, so the+// chunk budget leaves room for the prompt the manuscript rides inside.+export const EDITORIAL_PROMPT_OVERHEAD_TOKENS = 1_500;++// First-wins dedup key for an editorial finding, used to merge results across+// manuscript chunks. Mirrors completenessPass.findingKey: a finding identical on+// (issue, category, anchor, problem) is kept once even if two chunks surface it.+export const editorialFindingKey = (f) => [+ f.issueNumber ?? '',+ f.category ?? '',+ (f.anchorQuote || '').trim().toLowerCase().slice(0, 120),+ (f.problem || '').trim().toLowerCase().slice(0, 120),+].join('|');++// 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;+// Only the findings BODY is capped — the fixed header and the trailing `---`+// delimiter are always added AFTER the cap (the next manuscript chunk is+// concatenated right after the digest, so the delimiter MUST survive or the+// manuscript bleeds into the "already recorded" list).+export const EDITORIAL_PRIOR_DIGEST_BODY_CHARS = 2_000;+const EDITORIAL_PRIOR_DIGEST_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';+const EDITORIAL_PRIOR_DIGEST_SEPARATOR = '\n\n---\n\n';+// Whole-digest char ceiling = fixed wrapper + capped body. The digest is only+// prepended to a chunk when it fits in that chunk's spare budget (see+// runChunkedManuscriptCheck), so it never grows a chunk past the provider window.+export const EDITORIAL_PRIOR_DIGEST_CHARS =+ EDITORIAL_PRIOR_DIGEST_HEADER.length + EDITORIAL_PRIOR_DIGEST_BODY_CHARS + EDITORIAL_PRIOR_DIGEST_SEPARATOR.length;++// 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.+//+// Scope note: this carries prior FINDINGS, not clean prior setup (same as the+// completeness pass). It removes the duplicate/contradiction blind spot — a+// later chunk won't re-flag something an earlier chunk already flagged — but it+// can't tell a later chunk that an earlier chunk *cleanly* established an object's+// motivation or a tense. Carrying clean cross-chunk context would need a+// per-chunk content summary (extra LLM calls); tracked as a follow-up in #1403.+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)` : '';+ // Cap the body only — the header and the trailing `---` separator are appended+ // afterwards so they always survive (see EDITORIAL_PRIOR_DIGEST_BODY_CHARS).+ const body = `${lines.join('\n')}${more}`.slice(0, EDITORIAL_PRIOR_DIGEST_BODY_CHARS);+ return `${EDITORIAL_PRIOR_DIGEST_HEADER}${body}${EDITORIAL_PRIOR_DIGEST_SEPARATOR}`;+}++// Cross-chunk CLEAN-SETUP digest (#1403). The findings digest above carries prior+// problems forward, but it cannot tell a later chunk that an earlier chunk+// *cleanly* established context (an object's motivation, a tense/POV/rating) —+// clean setup produces no finding, so a payoff in a later chunk can be mis-flagged+// "missing setup". This digest threads a short rolling summary of established+// setup alongside the findings digest, generated by one extra summarization LLM+// call per chunk (see `runManuscriptLlmCheck`'s `crossChunkSetup` path).+//+// (When the reverse-outline (#1349) or continuity-bible (#1305) artifacts land,+// either could supply this cross-chunk context more cheaply than a per-chunk+// summary call — they already condense the manuscript. Until then this is the+// self-contained source.)+//+// Free-form run tag so /runs can filter the setup-summary calls apart from the+// named-stage editorial checks and custom-check calls.+export const EDITORIAL_SETUP_DIGEST_SOURCE = 'pipeline-editorial-setup-digest';+// Body cap for the rolling setup summary (a touch smaller than the findings+// digest — it is condensed prose, not a bounded findings list). Header + trailing+// `---` are appended AFTER the cap so the delimiter always survives truncation+// (the next manuscript chunk concatenates right after, same contract as the+// findings digest).+export const EDITORIAL_SETUP_DIGEST_BODY_CHARS = 1_500;+const EDITORIAL_SETUP_DIGEST_HEADER =+ '# Setup already established in EARLIER parts of this manuscript (clean context — these are NOT problems)\n'+ + 'Use this when judging the text below: do NOT flag a payoff as missing setup, or a tense/POV/rating as a '+ + 'drift, if it was already established here.\n\n';+const EDITORIAL_SETUP_DIGEST_SEPARATOR = '\n\n---\n\n';+// Whole-digest char ceiling = fixed wrapper + capped body. Like the findings+// digest, the setup digest is prepended only when it fits the chunk's spare+// budget, so it never grows a chunk past the provider window.+export const EDITORIAL_SETUP_DIGEST_CHARS =+ EDITORIAL_SETUP_DIGEST_HEADER.length + EDITORIAL_SETUP_DIGEST_BODY_CHARS + EDITORIAL_SETUP_DIGEST_SEPARATOR.length;++// Wrap an accumulated "setup so far" summary in the fixed header + trailing `---`+// so it rides INSIDE the next chunk's manuscript var (no prompt template change,+// mirrors editorialPriorFindingsDigest). Returns '' for an empty/non-string+// summary so the first chunk (no prior setup yet) is untouched.+export function editorialSetupDigest(summary) {+ if (typeof summary !== 'string' || !summary.trim()) return '';+ const body = summary.trim().slice(0, EDITORIAL_SETUP_DIGEST_BODY_CHARS);+ return `${EDITORIAL_SETUP_DIGEST_HEADER}${body}${EDITORIAL_SETUP_DIGEST_SEPARATOR}`;+}++// Build the inline summarization prompt that maintains the rolling "setup so far"+// summary. Pure + deterministic so it's unit-testable and so the caller can pin a+// per-check `focus` (the objects check tracks item motivations; the style check+// tracks tense/POV/rating). Asks for terse merged setup text only — no JSON, no+// commentary — since the result rides verbatim into the next chunk's digest.+export function buildSetupDigestPrompt({ focus, priorSummary, manuscript }) {+ const trackDefault = 'Items/objects introduced and any motivation or significance established for them; '+ + 'the narrative tense, point-of-view person, and content rating in force.';+ return [+ 'You are tracking established narrative SETUP across a long manuscript reviewed in parts.',+ 'Maintain a SHORT running summary of the setup so far — only the facts a later part needs to judge payoffs and continuity.',+ '',+ '# What to track',+ String(focus || '').trim() || trackDefault,+ '',+ '# Setup recorded so far (from earlier parts)',+ String(priorSummary || '').trim() || '(none yet)',+ '',+ '# New manuscript part',+ String(manuscript || ''),+ '',+ '# How to respond',+ 'Return an updated running summary that MERGES the prior setup with any new setup established in this part.',+ 'Be terse: short bullet lines, no preamble, no commentary — only the established facts, dropping nothing important from the prior summary.',+ 'Respond with the summary text only: no JSON, no section headers, no explanation.',+ ].join('\n');+}++// 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.+//+// The digest YIELDS to manuscript coverage: it is prepended only when it fits in+// the chunk's spare budget (`usableChars - chunk length`, exposed by the runner's+// chunker). So it never displaces manuscript text and never grows a chunk past+// the provider window — a chunk packed up to the budget simply runs without a+// digest rather than dropping its tail. When the chunker doesn't report a budget+// (a fits-in-one-call provider, or a test stub), there is unbounded headroom.+//+// `summarizeChunk` (#1403) opts in the CLEAN-SETUP digest: when provided, after+// each non-final chunk it is called `(priorSummary, chunkText) => nextSummary` to+// roll forward a short "setup so far" summary, and that summary's `editorialSetupDigest`+// is prepended (alongside the findings digest, after it in the budget) to later+// chunks — also yielding to spare room. It is a no-op for a single-chunk run (no+// later chunk consumes a summary), so the common fits-in-one-call provider pays+// nothing.+//+// `reserveSetupDigest` (#1667) GUARANTEES the carried setup digest reaches the+// FINAL chunk for checks that gate a whole-story verdict to it and anchor that+// verdict on the carried snippet (arc.climax-agency #1583, emotion.reaction-+// proportionality #1584). The setup digest normally yields to manuscript coverage,+// so a final chunk packed to within a few hundred chars of the window silently+// drops the digest and the final-only finding is missed. When this opt-in is set+// and the digest doesn't fit the final chunk's spare room, the manuscript TAIL is+// trimmed to reserve the digest's room (the inverse of the usual yield) so the+// verdict keeps its carried context. Scoped to the final chunk and to opt-in checks+// only — every other chunk, and every non-reserving check, keeps full manuscript+// coverage. If the digest alone is larger than the whole window it still yields+// (never prepended past the budget), preserving the no-overflow contract.+async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk, crossChunkDigest = false, summarizeChunk = null, reserveSetupDigest = false, subtypes = null }) {+ const usableChars = Number.isFinite(chunks?.usableChars) ? chunks.usableChars : Infinity;+ const merged = new Map();+ // The presence of `summarizeChunk` (set only when the check opts into the+ // clean-setup digest AND an inline LLM caller is available) is itself the gate —+ // no separate flag, so the null-checks below can't drift from it.+ let setupSummary = '';+ for (let i = 0; i < chunks.length; i++) {+ const manuscript = chunks[i];+ // 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;+ // `isFinal` lets a check distinguish the last part of a chunked manuscript+ // from earlier ones (#1299): a whole-corpus judgment like "this setup is+ // never paid off" can only be made once the final part is in view, so the+ // Chekhov check defers its "planted, never fired" findings to it. A+ // single-chunk run is its own final part, so the common (provider-fits-the-+ // book) case judges against the whole text. Existing checks ignore the arg.+ const isFinal = i === chunks.length - 1;+ let text = manuscript;+ if (crossChunkDigest && merged.size) {+ const digest = editorialPriorFindingsDigest([...merged.values()]);+ // Only prepend when the digest fits the chunk's spare room — never trim the+ // manuscript (would drop review coverage) or overflow the window.+ if (digest && digest.length <= usableChars - text.length) text = `${digest}${manuscript}`;+ }+ if (summarizeChunk && setupSummary) {+ const setup = editorialSetupDigest(setupSummary);+ if (setup && setup.length <= usableChars - text.length) {+ // Fits into whatever spare room remains AFTER the findings digest — manuscript+ // coverage and the findings digest both win over the setup digest if budget is tight.+ text = `${setup}${text}`;+ } else if (setup && reserveSetupDigest && isFinal && setup.length <= usableChars) {+ // #1667: the digest didn't fit, but this check gates its verdict to the final+ // part and anchors it on the carried snippet — so reserve the digest's room and+ // fill the rest with the manuscript HEAD (trimming its tail) rather than drop+ // the carried context. Rebuild from the RAW `manuscript`, NOT the+ // findings-digest-prefixed `text`: slicing `text` could truncate the findings+ // digest mid-block into a malformed prefix, and the findings digest's job+ // (suppressing duplicate re-flags) is already covered by the first-wins merge,+ // so it safely yields here. Gated on `setup.length <= usableChars` so a digest+ // larger than the whole window yields instead of overflowing it — preserving+ // the pre-reserve no-overflow contract on a tiny/high-overhead window.+ text = `${setup}${manuscript.slice(0, usableChars - setup.length)}`;+ }+ }+ const content = await callChunk(text, { isFinal });+ for (const f of mapLlmFindings(content?.findings, {+ severityDefault: ctx.severityDefault,+ category,+ max,+ withIssueNumber: true,+ subtypes,+ })) {+ const k = editorialFindingKey(f);+ if (!merged.has(k)) merged.set(k, f);+ }+ // Roll the setup summary forward for the NEXT chunk — skip after the last chunk+ // (nothing consumes it) and on cancellation (its result would be discarded).+ // Summarize the RAW chunk, never the digest-prefixed text. A summarizer failure+ // must not abort the check — keep the prior summary and continue.+ if (summarizeChunk && i < chunks.length - 1 && !ctx.signal?.aborted) {+ const next = await summarizeChunk(setupSummary, manuscript).catch(() => setupSummary);+ // Cap the STORED summary, not just the rendered digest: a verbose/echoing+ // summarizer response is fed back into the next summarization prompt as the+ // prior summary, so an uncapped string would compound and could overflow the+ // provider context. Trimming here bounds both the next prompt and the digest.+ if (typeof next === 'string' && next.trim()) {+ setupSummary = next.trim().slice(0, EDITORIAL_SETUP_DIGEST_BODY_CHARS);+ }+ }+ }+ 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+// findings first-wins (capped at the check's `maxFindings`). `buildVars(chunk, meta)`+// returns the stage vars — only the manuscript var changes per chunk; `meta.isFinal`+// is true on the last (or only) chunk so a check can gate whole-corpus judgments to+// it (the Chekhov "planted, never fired" pass). Existing checks ignore `meta`. These+// checks are all manuscript-scoped, so findings keep a model-supplied issue+// number (`withIssueNumber: true`).+//+// A check declares its per-chunk non-manuscript overhead in ONE of two ways:+//+// `context` (preferred) — a `{ varName: string }` map of the TRIMMABLE context+// blocks the check re-sends on each chunk (the scene map, character arcs, the+// style-guide expectations, …). The runner counts them as overhead AND, on a+// small/fallback window where they'd starve the manuscript chunk to '', trims+// them to guarantee the manuscript a budget floor (#1459). `buildVars` then+// receives the (possibly trimmed) blocks as its third arg — so the check feeds+// the SAME context it was budgeted for (sending the untrimmed originals would+// overflow the window the trim was sized to fit). `EDITORIAL_PROMPT_OVERHEAD_TOKENS`+// is added automatically as the fixed (non-trimmable) template/contract reserve.+//+// `overheadTokens` (legacy) — a single fixed token count for a check with no+// trimmable context (a plain whole-manuscript scan). MUST account for every+// non-manuscript prompt var, on top of EDITORIAL_PROMPT_OVERHEAD_TOKENS.+//+// `buildVars(chunk, meta, context)` returns the stage vars — only the manuscript+// var changes per chunk; `meta.isFinal` is true on the last (or only) chunk so a+// check can gate whole-corpus judgments to it (the Chekhov "planted, never fired"+// pass), and `context` is the trimmed block map (or `{}` for an `overheadTokens`+// check). Existing checks ignore the extra args. These checks are all+// manuscript-scoped, so findings keep a model-supplied issue number+// (`withIssueNumber: true`).+export async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, context = null, buildVars, crossChunkDigest = false, crossChunkSetup = false, setupFocus = '', reserveSetupDigest = false, subtypes = null }) {+ const max = ctx.config?.maxFindings ?? 12;+ // Chunks are planned at the full usable budget; the digest is fitted into each+ // later chunk's spare room inside runChunkedManuscriptCheck (it yields to the+ // manuscript), so no budget is reserved or carved out here. A `context` map is+ // trimmed to keep the manuscript a budget floor; the trimmed blocks come back on+ // `chunks.context` so they're what we feed the model.+ const chunks = context+ ? await ctx.planManuscriptChunks(stage, { context, fixedOverheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS })+ : await ctx.planManuscriptChunks(stage, { overheadTokens });+ // The runner returns the (possibly trimmed) context on `chunks.context`; fall back+ // to the originals if it didn't echo them (a chunker that doesn't implement the+ // context path), and to `{}` for an `overheadTokens` check with no context.+ const fittedContext = chunks?.context || context || {};+ // Clean-setup digest (#1403): roll a short "setup so far" summary forward via an+ // inline summarization call. Only wired when the check opts in AND the runner+ // injected the stage-scoped inline caller — absent it (unit tests of the+ // findings-digest path), the check degrades to findings-only with no extra calls.+ // The call is STAGE-SCOPED (not plain callInlineLLM) so the summary runs on the+ // same provider the stage is pinned to — never leaking manuscript text to the+ // active/cloud provider when the check's stage targets a private/local one.+ const summarizeChunk = crossChunkSetup && typeof ctx.callStageScopedInlineLLM === 'function'+ ? async (priorSummary, manuscript) => {+ const prompt = buildSetupDigestPrompt({ focus: setupFocus, priorSummary, manuscript });+ const { content } = await ctx.callStageScopedInlineLLM(stage, prompt, { source: EDITORIAL_SETUP_DIGEST_SOURCE });+ return typeof content === 'string' ? content : '';+ }+ : null;+ return runChunkedManuscriptCheck(ctx, {+ chunks,+ category,+ max,+ crossChunkDigest,+ summarizeChunk,+ reserveSetupDigest,+ subtypes,+ callChunk: async (manuscript, meta) => {+ const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript, meta, fittedContext), { returnsJson: true, source: stage });+ return content;+ },+ });+}++// Normalize raw LLM findings into partial manuscriptReview comments: validate+// severity against the allow-list (fall back to the check default), force the+// check's `category`, coerce each string field, cap the count, and drop any+// finding with no `problem`. `withIssueNumber` keeps a model-supplied issue+// number (manuscript-scoped checks) vs. forcing null (canon-scoped checks).+// `subtypes` (optional) is a per-check allow-list (#1626): when supplied, the+// model's `subtype` is validated against it and stamped on the finding (off-list+// or absent → null), letting a check sub-classify its findings (e.g. on-the-nose+// → exposition / emotion-tell / relationship-report) without a new field on every+// other check.+export function mapLlmFindings(raw, { severityDefault, category, max, withIssueNumber, subtypes = null }) {+ const list = Array.isArray(raw) ? raw : [];+ const allowSubtype = Array.isArray(subtypes) && subtypes.length > 0;+ return list.slice(0, max).map((f) => ({+ severity: SEVERITIES.includes(f?.severity) ? f.severity : severityDefault,+ category,+ // Optional per-check sub-classification. Only set when the check declares an+ // allow-list AND the model returned a recognized value — null otherwise so a+ // check with no subtypes (and an unrecognized label) carries a clean null.+ subtype: allowSubtype && subtypes.includes(f?.subtype) ? f.subtype : null,+ location: typeof f?.location === 'string' ? f.location : '',+ problem: typeof f?.problem === 'string' ? f.problem : '',+ suggestion: typeof f?.suggestion === 'string' ? f.suggestion : '',+ anchorQuote: typeof f?.anchorQuote === 'string' ? f.anchorQuote : '',+ issueNumber: withIssueNumber && Number.isInteger(f?.issueNumber) ? f.issueNumber : null,+ })).filter((f) => f.problem);+}++// ---------------------------------------------------------------------------+// User-defined (custom) LLM checks (#1346). A custom check has no shipped stage+// template — its prompt body is authored from the UI. The fixed JSON output+// contract is enforced HERE (not by the user), so an author only describes WHAT+// to look for; the response is parsed by the same `mapLlmFindings` the built-in+// stage prompts feed. Kept pure: the model caller (`ctx.callInlineLLM`) and the+// chunk planner (`ctx.planManuscriptChunks`) are injected by the runner.+// ---------------------------------------------------------------------------++// Free-form tag persisted on the run record so /runs can filter custom-check+// calls apart from the named-stage editorial checks.+export const CUSTOM_CHECK_RUN_SOURCE = 'pipeline-editorial-custom';++// Wrap a user's authored instructions in the fixed findings JSON contract. Pure+// and deterministic so it's unit-testable and so `runManuscriptLlmCheckInline`+// can render it once with an empty manuscript to measure per-call overhead.+export function buildCustomCheckPrompt({ instructions, manuscript, maxFindings = CUSTOM_CHECK_MAX_FINDINGS_DEFAULT }) {+ const cap = Number.isInteger(maxFindings) && maxFindings > 0 ? maxFindings : CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;+ return [+ 'You are an editorial reviewer analyzing a draft manuscript for one specific issue.',+ '',+ '# What to look for',+ String(instructions || '').trim(),+ '',+ '# Manuscript',+ String(manuscript || ''),+ '',+ '# How to respond',+ `Return ONLY a JSON object of the form {"findings": [...]} with at most ${cap} findings.`,+ 'Each finding is an object with these fields:',+ '- "severity": one of "high", "medium", "low"',+ '- "location": a short human-readable pointer to where the problem is (e.g. a chapter or section name)',+ '- "problem": one sentence stating what is wrong (REQUIRED — omit the finding if you cannot name a concrete problem)',+ '- "suggestion": one sentence on how to fix it',+ '- "anchorQuote": a short verbatim quote from the manuscript at the problem location',+ '- "issueNumber": the issue/chapter number the problem is in, or null',+ 'If nothing matches, return {"findings": []}. Do not include any prose outside the JSON object.',+ ].join('\n');+}++// Inline-prompt sibling of `runManuscriptLlmCheck` for custom checks: same+// provider-sized chunking + first-wins merge, but the prompt is the authored+// instructions wrapped by `buildCustomCheckPrompt` instead of a named stage.+// `ctx.planManuscriptChunks(null, …)` resolves the active/overridden provider's+// window (a custom check has no stage to pin), and `ctx.callInlineLLM` runs the+// built prompt. Findings keep a model-supplied issue number (manuscript-scoped).+export async function runManuscriptLlmCheckInline(ctx, { category, instructions }) {+ const max = ctx.config?.maxFindings ?? CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;+ // Fixed per-call overhead = the contract wrapper + the instructions (only the+ // manuscript var changes per chunk). Measure it by rendering the prompt with an+ // empty manuscript so the chunk budget accounts for everything riding along.+ const overheadTokens = EDITORIAL_PROMPT_OVERHEAD_TOKENS+ + estimateTokens(buildCustomCheckPrompt({ instructions, manuscript: '', maxFindings: max }));+ const chunks = await ctx.planManuscriptChunks(null, { overheadTokens });+ 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;+ },+ });+}+diff --git a/server/lib/editorial/checkInfra/povAndNames.js b/server/lib/editorial/checkInfra/povAndNames.jsnew file mode 100644index 0000000000..eec409b3f6--- /dev/null+++ b/server/lib/editorial/checkInfra/povAndNames.js@@ -0,0 +1,105 @@+/**+ * POV-continuity scene grouping + character-name dissimilarity scaffolding+ * (#2842 split of checkInfra.js).+ */++import { SEVERITIES } from './taxonomy.js';++// ---------------------------------------------------------------------------+// Chapter-ending POV switch (#1298) — deterministic over the reverse-outline POV+// map + the authored reader-map cliffhangers. The editorial rule: in a multi-POV+// story, after a chapter ends on a cliffhanger, the NEXT chapter should cut to a+// DIFFERENT POV character (the cut sustains tension across the break). The LLM+// cliffhanger check above judges WHICH endings are cliffhangers; this check uses+// the writer's AUTHORED cliffhangers as the deterministic trigger so it never+// needs the model. No authored cliffhangers ⇒ nothing to reconcile (no-op);+// single-POV series ⇒ no-op (there's no other POV to cut to).+// ---------------------------------------------------------------------------++// Group POV-tagged scenes by issue number, preserving outline (sequence) order+// within each issue and first-seen story order across issues. Scenes without an+// integer issueNumber can't be mapped to a chapter boundary and are dropped.+export function scenesByIssue(scenes) {+ const byIssue = new Map();+ for (const s of scenes) {+ if (!s || typeof s !== 'object') continue;+ const n = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ if (n == null) continue;+ if (!byIssue.has(n)) byIssue.set(n, []);+ byIssue.get(n).push(s);+ }+ return byIssue;+}++// The POV holder of a scene, trimmed, or '' when untagged.+export const scenePov = (s) => (typeof s?.povCharacter === 'string' ? s.povCharacter.trim() : '');++// The last / first POV-tagged scene of an issue's scene list (sequence-ordered),+// as { name, scene }, or null when no scene in the issue carries a POV.+export function lastPovScene(list) {+ for (let i = list.length - 1; i >= 0; i -= 1) {+ const name = scenePov(list[i]);+ if (name) return { name, scene: list[i] };+ }+ return null;+}+export function firstPovScene(list) {+ for (const s of list) {+ const name = scenePov(s);+ if (name) return { name, scene: s };+ }+ return null;+}++// ---------------------------------------------------------------------------+// Character-name dissimilarity (#1291) reads cast names + aliases and respects+// locked entries. The pure similarity primitives live in ./nameSimilarity.js;+// the helpers below turn the canon into the flat name list the check walks.+// ---------------------------------------------------------------------------++// SEVERITIES is ordered high→…→low (index 0 = most severe). Escalate `base` up+// by `steps` ranks, clamped at the top — a strong collision (near-identical+// spelling, dense first-letter cluster) outranks the check's low floor.+export function escalateSeverity(base, steps) {+ const i = SEVERITIES.indexOf(base);+ const idx = i === -1 ? SEVERITIES.length - 1 : i;+ return SEVERITIES[Math.max(0, idx - Math.max(0, steps))];+}++// The flat list of confusable name tokens for a cast: each character's `name`+// plus every alias, tagged with the owning character (id-or-index), whether that+// character is locked, and whether the token is an alias. Two tokens owned by the+// same character never pair (a name vs. its own alias isn't a reader collision).+export function castNameTokens(ctx) {+ const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];+ const tokens = [];+ chars.forEach((c, idx) => {+ if (!c || typeof c !== 'object') return;+ const owner = c.id || `idx-${idx}`;+ const locked = c.locked === true;+ const primary = typeof c.name === 'string' ? c.name.trim() : '';+ if (primary) tokens.push({ token: primary, owner, ownerName: primary, locked, isAlias: false });+ const aliases = Array.isArray(c.aliases) ? c.aliases : [];+ for (const a of aliases) {+ const alias = typeof a === 'string' ? a.trim() : '';+ if (alias) tokens.push({ token: alias, owner, ownerName: primary || alias, locked, isAlias: true });+ }+ });+ return tokens;+}++// A name token's display label — an alias is annotated with its owning character+// so the finding text and the rename suggestion always name the source.+export const tokenLabel = (t) => (t.isAlias ? `${t.token} (alias of ${t.ownerName})` : t.token);++// How to phrase the rename suggestion given which of the two characters are+// locked — always steer the author toward renaming an UNLOCKED one (#1291).+export function renameSuggestion(a, b) {+ if (a.locked && b.locked) {+ return `Both ${a.ownerName} and ${b.ownerName} are locked — unlock one to rename it so readers can tell them apart.`;+ }+ if (a.locked) return `Rename ${b.ownerName} (${a.ownerName} is locked) so it reads less like "${tokenLabel(a)}".`;+ if (b.locked) return `Rename ${a.ownerName} (${b.ownerName} is locked) so it reads less like "${tokenLabel(b)}".`;+ return `Rename one of ${a.ownerName} / ${b.ownerName} so readers can tell them apart at a glance.`;+}+diff --git a/server/lib/editorial/checkInfra/proseDensity.js b/server/lib/editorial/checkInfra/proseDensity.jsnew file mode 100644index 0000000000..a6e80c8766--- /dev/null+++ b/server/lib/editorial/checkInfra/proseDensity.js@@ -0,0 +1,71 @@+/**+ * Density-scaled prose-tic finding helpers (#1306) (#2842 split of checkInfra.js).+ */++// ---------------------------------------------------------------------------+// Registry entries.+// ---------------------------------------------------------------------------++// Split a UI text field holding a phrase list (comma- or newline-separated) into+// trimmed, non-empty phrases — used by prose.cliches' allow/extra config fields.+export function splitPhraseList(value) {+ if (typeof value !== 'string' || !value.trim()) return [];+ return value.split(/[,\n]/).map((p) => p.trim()).filter(Boolean);+}++// ---------------------------------------------------------------------------+// Copy-edit prose-tic checks (#1306). The deterministic word-level scanners live+// in proseTics.js / repetition.js; these helpers turn raw occurrences into the+// density-scaled findings the registry emits. Density matters: one "just" is+// fine, forty is a tic — so each check measures per-1000-word frequency against+// a configurable threshold and only flags when the rate (not the raw count) is+// high. Findings anchor on the FIRST offending occurrence in each section.+// ---------------------------------------------------------------------------++// Word count of a section's prose (for per-1000-word density). Cheap word+// tokenization — apostrophes kept inside words so contractions count once.+export function countWords(text) {+ return (String(text || '').match(/[A-Za-z][A-Za-z']*/g) || []).length;+}++// Map a section to its issue label/number once (used by every prose-tic check).+export function sectionIssue(s) {+ const number = Number.isInteger(s?.number) ? s.number : null;+ return { number, location: number != null ? `Issue ${number}` : 'Manuscript' };+}++// Shared driver for the per-1000-word density checks (filter words, crutch+// words, passive voice). For each section it runs the supplied `scan`, computes+// the per-1000-word rate, and emits one finding per section whose rate is at or+// above the configured `densityPer1000` — anchored to the first occurrence.+// `opts` declares the section scan, a noun for messages, and problem/suggestion+// builders. `scan(text, cfg)` returns `[{ index, anchor }, …]` occurrences.+export function runDensityCheck(ctx, opts) {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const density = cfg.densityPer1000 ?? 0;+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const words = countWords(text);+ if (words === 0) continue;+ const hits = opts.scan(text, cfg);+ if (!hits.length) continue;+ const rate = Math.round((hits.length / words) * 1000 * 10) / 10;+ if (rate < density) continue;+ const { number, location } = sectionIssue(s);+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: opts.problem(hits.length, rate, hits[0].anchor),+ suggestion: opts.suggestion,+ anchorQuote: hits[0].anchor,+ issueNumber: number,+ });+ }+ return findings;+}+diff --git a/server/lib/editorial/checkInfra/readability.js b/server/lib/editorial/checkInfra/readability.jsnew file mode 100644index 0000000000..cdc3893dd1--- /dev/null+++ b/server/lib/editorial/checkInfra/readability.js@@ -0,0 +1,95 @@+/**+ * Deterministic reading-level helpers for the style-guide conformance check+ * (#1303) (#2842 split of checkInfra.js).+ */++import { splitScenes } from './externals.js';++// ---------------------------------------------------------------------------+// Deterministic helpers for the style-guide reading-level check (#1303). A+// self-contained Flesch–Kincaid grade-level estimate so the registry stays pure+// (no import out to the styleGuide lib). The heuristic is approximate — it only+// needs to catch "the prose reads several grades off the configured target".+// ---------------------------------------------------------------------------++// Hoisted out of countSyllables so the per-word loop over a full manuscript+// doesn't recompile them on every call.+const NON_ALPHA_RE = /[^a-z]/g;+const VOWEL_GROUP_RE = /[aeiouy]+/g;+const SENTENCE_END_RE = /[.!?]+/g;+const WORD_RE = /\b[a-zA-Z]+\b/g;++function countSyllables(word) {+ const w = String(word).toLowerCase().replace(NON_ALPHA_RE, '');+ if (!w) return 0;+ if (w.length <= 3) return 1;+ // Drop a trailing silent 'e', then count vowel groups (each run of vowels is+ // ~one syllable). Floor at 1 — every real word has at least one.+ const groups = w.replace(/e$/, '').match(VOWEL_GROUP_RE);+ return Math.max(1, groups ? groups.length : 1);+}++// Flesch–Kincaid grade level for a manuscript corpus. Returns null when there+// are no words to measure (caller skips rather than flagging a phantom grade).+export function readingGradeLevel(text) {+ const clean = String(text || '');+ const sentences = (clean.match(SENTENCE_END_RE) || []).length || 1;+ const words = clean.match(WORD_RE) || [];+ if (words.length === 0) return null;+ const syllables = words.reduce((sum, w) => sum + countSyllables(w), 0);+ return 0.39 * (words.length / sentences) + 11.8 * (syllables / words.length) - 15.59;+}++// Per-scene reading-grade spread (#1625). The whole-corpus grade above is a single+// number for the entire series — it averages away the legitimate modulation a+// skilled writer uses (a quiet introspective scene reads lower, an action scene+// higher) AND it hides a lone scene that swings far outside the intended band.+// Splits the manuscript into scenes via the shared `splitScenes` (markdown+// headings — including the stitcher's `# Issue N` — and centered rules like+// "***") and measures each one, so the check can surface the outliers the corpus+// average conceals. Scenes shorter than `minWords` are skipped: a brief fragment's+// FK estimate is too noisy to judge. Returns one row per measurable scene+// (`{ ordinal, grade, words, text }`), or [] when none qualify.+export function readingLevelByScene(manuscript, minWords) {+ const floor = Number.isFinite(minWords) ? minWords : 120;+ const rows = [];+ for (const scene of splitScenes(String(manuscript || ''))) {+ const words = (scene.text.match(WORD_RE) || []).length;+ if (words < floor) continue;+ const grade = readingGradeLevel(scene.text);+ if (grade == null) continue;+ rows.push({ ordinal: scene.ordinal, grade: Math.round(grade * 10) / 10, words, text: scene.text });+ }+ return rows;+}++// First substantive line of a scene, trimmed to a short anchor so a per-scene+// finding lands on real prose the editor can locate. Skips blank lines; falls+// back to '' for a whitespace-only scene.+export function sceneReadingAnchor(text) {+ for (const line of String(text || '').split('\n')) {+ const t = line.trim();+ if (t) return t.length > 80 ? `${t.slice(0, 80).trim()}…` : t;+ }+ return '';+}++// Compact bullet list of the conformance-relevant style-guide expectations, fed+// to the conformance LLM so it knows exactly what to measure the prose against.+// Inlined (not imported from styleGuide.js) to keep this registry pure. Returns+// '' when no conformance-relevant field is set (the check's gate also tests this).+export function styleGuideExpectations(sg) {+ if (!sg || typeof sg !== 'object') return '';+ const lines = [];+ if (sg.tense) lines.push(`- Tense: ${sg.tense}`);+ if (sg.povPerson) lines.push(`- Point-of-view person: ${sg.povPerson}`);+ if (sg.targetAudience) lines.push(`- Target audience: ${sg.targetAudience}`);+ if (sg.contentRating && sg.contentRating !== 'custom') lines.push(`- Content rating ceiling: ${sg.contentRating}`);+ if (sg.profanity) lines.push(`- Profanity allowed: ${sg.profanity}`);+ return lines.join('\n');+}++// True when the style guide carries at least one field the conformance LLM can+// measure prose against. Shared by the check's gate and run so they agree.+export const hasConformanceFields = (sg) => styleGuideExpectations(sg).length > 0;+diff --git a/server/lib/editorial/checkInfra/revealForeshadowing.js b/server/lib/editorial/checkInfra/revealForeshadowing.jsnew file mode 100644index 0000000000..58cf000e29--- /dev/null+++ b/server/lib/editorial/checkInfra/revealForeshadowing.js@@ -0,0 +1,202 @@+/**+ * Reveal-gating, foreshadowing and setup/payoff stages + prompt summaries+ * (#2842 split of checkInfra.js). Covers the information-economy family:+ * info-dumping, object motivation/backstory/weight, style conformance,+ * interiority, Chekhov, premature reveal, and the endings/cliffhanger stage.+ */++import { revealGatedCanonRows } from './externals.js';++// Stage name for the info-dumping LLM check. The prompt ships in+// data.reference/prompts/stages/ and its config in stage-config.json; both+// propagate to existing installs via setup-data.js (missing-file copy ++// JSON_MERGE_TARGETS stage merge), so no migration is needed for a NEW stage.+export const INFO_DUMPING_STAGE = 'pipeline-editorial-info-dumping';++// Stage names for the two object-attachment LLM checks (#1288). Like the+// info-dumping stage, each prompt ships in data.reference/prompts/stages/ and+// its config in stage-config.json; both propagate to fresh installs via+// setup-data.js and to existing installs via migration 094 (boot runs+// migrations but NOT setup-data, so the migration is required — see+// scripts/migrations/094-object-attachment-check-stages.js).+export const OBJECT_MOTIVATION_STAGE = 'pipeline-editorial-object-motivation';+export const OBJECT_BACKSTORY_STAGE = 'pipeline-editorial-object-backstory';++// Stage name for the object weight-proportionality LLM check (#1624): judges+// whether an object's narrative weight (established backstory + payoff depth)+// matches its prominence in the prose — flagging a minor object given a heavy+// backstory ("a one-line locket with a 3-issue origin") or a climactic object+// with no lineage to earn it ("a heirloom that decides the finale, never set+// up"). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration+// 143 (boot runs migrations but NOT setup-data, so the migration is required).+// Like the two object-attachment checks above it feeds the canon's per-object+// significance/attachment summary as context and reads the stitched manuscript+// to weigh prose prominence against that established weight.+export const OBJECT_WEIGHT_STAGE = 'pipeline-editorial-object-weight-proportionality';++// Stage name for the style-guide conformance LLM check (#1303). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 096 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const STYLE_CONFORMANCE_STAGE = 'pipeline-editorial-style-conformance';++// Stage name for the protagonist-interiority LLM check (#1294). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 099 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const INTERIORITY_STAGE = 'pipeline-editorial-interiority';++// Stage name for the Chekhov's-guns setup/payoff LLM check (#1299). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 100 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const CHEKHOV_STAGE = 'pipeline-editorial-chekhov';++// Stage name for the premature-reveal editorial LLM check (#2178 — CWQE Phase+// 13). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration+// 168 (boot runs migrations but NOT setup-data, so the migration is required).+export const PREMATURE_REVEAL_STAGE = 'pipeline-editorial-premature-reveal';++// Render the reveal-gated canon (#2178) into a compact text block the+// premature-reveal check passes alongside the manuscript, so the model knows+// which facts are SECRETS not yet due and when each is meant to surface. Each+// row names the entry, its reveal issue (or hard spoiler), the spoiler-free+// surface stand-in the reader IS allowed to see, and the underlying fact that+// must NOT leak early. Pure + deterministic so it's unit-testable and its token+// cost counts into the per-chunk overhead. Returns '' when no canon is+// reveal-gated (the check gates on `canonHasRevealGated` so this won't be+// called with an empty set, but the guard keeps it safe).+export function revealGatedCanonSummary(canon) {+ const rows = revealGatedCanonRows(canon);+ if (!rows.length) return '';+ const lines = rows.map((r) => {+ const when = r.spoiler+ ? 'HARD SPOILER — must not appear in ANY drafted issue'+ : `revealed in Issue ${r.revealIssue} — must not appear before then`;+ const surface = r.surfaceDescriptor+ ? ` Pre-reveal, the reader may only know: "${r.surfaceDescriptor}".`+ : '';+ const fact = r.fact ? ` The gated fact (must NOT leak early): ${r.fact}.` : '';+ return `- ${r.kind} "${r.name}" (${when}).${surface}${fact}`;+ });+ return 'Reveal-gated canon (these facts are deliberately withheld — flag any that a first-time reader would '+ + 'learn from the prose before the fact is due):\n' + lines.join('\n');+}++// Render reveal-gated canon (#2178) as AUTHORED PAYOFFS for the Chekhov check —+// a gated entry's `revealIssue` is effectively an authored payoff point (the+// issue where the withheld fact is meant to fire). Folded into the Chekhov+// `authoredSetups` block so the check can flag a reveal that arrives with zero+// prior setup (an orphaned payoff). Only NUMERIC reveal gates render — a hard+// `spoiler` has no scheduled payoff issue to reconcile against. Returns '' when+// no numeric-gated entry exists (the block renders nothing). Pure.+export function revealGatedPayoffsSummary(canon) {+ const rows = revealGatedCanonRows(canon).filter((r) => Number.isInteger(r.revealIssue));+ if (!rows.length) return '';+ const lines = rows.map((r) => {+ const what = r.fact || `the withheld fact about ${r.kind} "${r.name}"`;+ return `- ${r.kind} "${r.name}" — reveal-gated fact due to pay off in Issue ${r.revealIssue}: ${what}`;+ });+ return 'Authored reveal-gated payoffs (each gated fact is meant to be revealed — fire — in its named issue; '+ + 'flag a reveal that arrives with no prior setup):\n' + lines.join('\n');+}++// Stage name for the chapter-ending cliffhanger LLM check (#1298). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 102 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const ENDINGS_CLIFFHANGER_STAGE = 'pipeline-editorial-endings-cliffhanger';++// Render the authored reader-map hooks/payoffs (#1299) into a compact text block+// the Chekhov check passes alongside the manuscript so the model reconciles its+// DETECTED setups/payoffs against what the writer has already LOGGED — e.g. an+// authored hook with no detected payoff, or a detected payoff the writer never+// logged. Pure + deterministic so it's unit-testable and so its token cost can be+// counted into the per-chunk overhead. Returns '' when nothing is authored (the+// prompt's `{{#authoredSetups}}` section then renders nothing).+// Shared preamble for the authored-entry renderers below: an entry's+// `label — note` (or whichever is present), '' when neither is usable so+// callers can `.filter(Boolean)`.+function entryLabelNoteText(e) {+ const label = typeof e?.label === 'string' ? e.label.trim() : '';+ const note = typeof e?.note === 'string' ? e.note.trim() : '';+ return label && note ? `${label} — ${note}` : (label || note);+}++// Render one reader-map entry (hook or payoff) to a `- text (arc position N)` line.+// Shared by authoredSetupPayoffSummary + authoredPayoffsSummary. Returns '' for an+// entry with no usable label/note so callers can `.filter(Boolean)`.+function renderReaderMapEntryLine(e) {+ const text = entryLabelNoteText(e);+ if (!text) return '';+ // A coarse expected-location hint so the model can reason about WHERE an+ // authored hook should have paid off (reconciliation signal, #1299).+ const pos = Number.isFinite(e?.atArcPosition) ? ` (arc position ${e.atArcPosition})` : '';+ return `- ${text}${pos}`;+}++// Render one foreshadowing-ledger entry (#2172) to a `- text (plant issue N →+// reinforced issue M → payoff issue P)` line so the Chekhov check reconciles+// its detected plants/payoffs against the author-declared ledger instead of+// inferring every seed from scratch. Returns '' for an entry with no usable+// label/note so callers can `.filter(Boolean)`.+function renderForeshadowingEntryLine(e) {+ const text = entryLabelNoteText(e);+ if (!text) return '';+ const span = [];+ if (Number.isFinite(e?.plantIssue)) span.push(`plant issue ${e.plantIssue}`);+ if (Array.isArray(e?.reinforceIssues) && e.reinforceIssues.length) {+ span.push(`reinforced issue ${e.reinforceIssues.join(', ')}`);+ }+ if (Number.isFinite(e?.payoffIssue)) span.push(`payoff issue ${e.payoffIssue}`);+ return span.length ? `- ${text} (${span.join(' → ')})` : `- ${text}`;+}++// Build the authored-foreshadowing-ledger block (#2172). Exported for the+// Chekhov check + unit tests; returns '' when nothing is authored so the+// prompt's `{{#authoredSetups}}` section renders nothing.+export function authoredForeshadowingSummary(foreshadowing) {+ const entries = Array.isArray(foreshadowing) ? foreshadowing : [];+ const lines = entries.map(renderForeshadowingEntryLine).filter(Boolean);+ if (!lines.length) return '';+ return `Authored foreshadowing ledger (planted seeds the writer logged — plant → reinforce → payoff):\n${lines.join('\n')}`;+}++// `foreshadowing` (#2172) is the author-declared plant→reinforce→payoff ledger+// on `series.arc.foreshadowing`; it's folded into the SAME authored-setups+// block the reader-map hooks/payoffs render into, so the Chekhov prompt+// consumes it through its existing `{{#authoredSetups}}` section without a+// template change.+export function authoredSetupPayoffSummary(readerMap, foreshadowing) {+ const hooks = Array.isArray(readerMap?.hooks) ? readerMap.hooks : [];+ const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];+ const hookLines = hooks.map(renderReaderMapEntryLine).filter(Boolean);+ const payoffLines = payoffs.map(renderReaderMapEntryLine).filter(Boolean);+ const ledgerBlock = authoredForeshadowingSummary(foreshadowing);+ if (!hookLines.length && !payoffLines.length && !ledgerBlock) return '';+ const parts = [];+ if (hookLines.length) parts.push(`Authored hooks (questions the writer planted):\n${hookLines.join('\n')}`);+ if (payoffLines.length) parts.push(`Authored payoffs (resolutions the writer logged):\n${payoffLines.join('\n')}`);+ if (ledgerBlock) parts.push(ledgerBlock);+ return parts.join('\n\n');+}++// Render ONLY the authored reader-map payoffs (#1583) — the resolutions the writer+// LOGGED that the reader was promised. The climax / resolution-power check passes+// this (NOT authoredSetupPayoffSummary, which also bundles hooks) so the prompt's+// "payoffs the climax should deliver" framing stays accurate: a hook is a question+// the writer planted, not a climax obligation, so feeding hooks here would risk the+// model flagging an ordinary unanswered hook as a missing climax resolution. Pure ++// deterministic so it's unit-testable and its token cost can be counted into the+// per-chunk overhead. Returns '' when no payoff is authored (the prompt's+// `{{#authoredPayoffs}}` section then renders nothing and the check reasons from the+// prose + themes alone).+export function authoredPayoffsSummary(readerMap) {+ const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];+ const payoffLines = payoffs.map(renderReaderMapEntryLine).filter(Boolean);+ if (!payoffLines.length) return '';+ return `Authored payoffs (resolutions the writer logged — what the reader was promised):\n${payoffLines.join('\n')}`;+}+diff --git a/server/lib/editorial/checkInfra/rosterCast.js b/server/lib/editorial/checkInfra/rosterCast.jsnew file mode 100644index 0000000000..f786921993--- /dev/null+++ b/server/lib/editorial/checkInfra/rosterCast.js@@ -0,0 +1,206 @@+/**+ * Roster economy (#1292) + cast representation/balance (#1312) accounting over+ * canon names, aliases and the stitched manuscript (#2842 split of checkInfra.js).+ */++import { normalizeName } from './externals.js';++// ---------------------------------------------------------------------------+// Roster economy (#1292) — character-appearance accounting over the stitched+// manuscript. Reads canon names + aliases and counts the DISTINCT issues each+// named character is mentioned in (recurrence), which issue they first appear+// in, and the named cast present in the opening issue. Pure: the per-issue+// `ctx.sections` and `ctx.canon` are injected by the runner.+//+// The match is a deterministic word-bounded name scan. A character whose name+// is a common word (Hope, Grace, Reed) can over-match prose — which biases the+// check toward UNDER-flagging throwaways (safe) at the cost of possibly+// over-counting first-issue crowding. Classifying unmodeled proper nouns as+// characters needs an LLM pass and is tracked as its own check (see the issue).+// ---------------------------------------------------------------------------++// Escape a name so it rides inside a RegExp alternation literally — names carry+// regex-significant punctuation ("D'Argo", "Anne-Marie", "T.A.R.D.I.S.").+const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++// A character's match tokens: its name plus every alias, trimmed + de-duped.+// Empty when the character has no usable name.+export function characterNameTokens(c) {+ const tokens = [];+ const push = (v) => { const t = typeof v === 'string' ? v.trim() : ''; if (t) tokens.push(t); };+ push(c?.name);+ for (const a of (Array.isArray(c?.aliases) ? c.aliases : [])) push(a);+ return [...new Set(tokens)];+}++// A case-insensitive, whole-token matcher for a character's tokens (built once+// per character and reused across every section so a long manuscript isn't+// re-compiling a regex per section), or null when there are no tokens.+export function characterMatcher(tokens) {+ if (!tokens.length) return null;+ // Longest-first so a token that's a prefix of another can't shadow it under+ // leftmost-match alternation (cosmetic for .test, but keeps intent clear).+ const alt = tokens.slice().sort((a, b) => b.length - a.length).map(escapeRegExp).join('|');+ // Lookarounds, not \b: a token that begins or ends with punctuation ("Mr.",+ // "T.A.R.D.I.S.", "J.R.") has no word char at that edge, so a leading/trailing+ // \b would never match it in prose. (?<!\w)…(?!\w) enforces whole-token matching+ // at any edge while still rejecting substrings (Sam ≠ "Samuel").+ return new RegExp(`(?<!\\w)(?:${alt})(?!\\w)`, 'i');+}++// One row per NAMED canon character: { id, name, locked, appearedInIssues,+// firstIssueNumber }. `appearedInIssues` is the distinct issue numbers the+// character is mentioned in, in story order (sections are one-per-issue, ordered+// by arc position). Unnamed canon entries aren't a roster-economy concern.+export function buildRosterAppearances(ctx) {+ const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const rows = [];+ for (const c of chars) {+ if (!c || typeof c !== 'object') continue;+ const name = typeof c.name === 'string' ? c.name.trim() : '';+ if (!name) continue;+ const matcher = characterMatcher(characterNameTokens(c));+ if (!matcher) continue;+ const appearedInIssues = [];+ // Capture the ACTUAL matched token (name OR alias) from the first issue the+ // character appears in, so a finding's anchorQuote lands on real prose — an+ // alias-only mention ("Bob" for canonical "Robert") must anchor on "Bob", not+ // the canonical name the editor would never find. `matcher` is non-global, so+ // exec starts at 0 on each section. Falls back to the name for unmatched rows.+ let anchorQuote = '';+ for (const s of sections) {+ const m = matcher.exec(s.content || '');+ if (!m) continue;+ appearedInIssues.push(s.number);+ if (!anchorQuote) anchorQuote = m[0];+ }+ rows.push({+ id: c.id || name,+ name,+ locked: c.locked === true,+ appearedInIssues,+ firstIssueNumber: appearedInIssues.length ? appearedInIssues[0] : null,+ anchorQuote: anchorQuote || name,+ });+ }+ return rows;+}++// Normalized keys of every canon character that actually APPEARS in the prose+// (named at least once across the manuscript sections) — the "appearing cast"+// both the screen-time skew and the silent-major distribution signals score+// against. Pure; reuses buildRosterAppearances' per-section matcher scan.+export function buildAppearingKeys(ctx) {+ return new Set(+ buildRosterAppearances(ctx)+ .filter((r) => r.appearedInIssues.length > 0)+ .map((r) => normalizeName(r.name))+ );+}++// ---------------------------------------------------------------------------+// Cast representation & balance (#1312) — three coarse, computable casting+// signals over the canon + reverse-outline + stitched manuscript:+// 1) Bechdel co-presence — does ANY scene put two+ non-male characters+// together (the structural precondition for two women talking)? Computed+// from the reverse-outline's per-scene charactersPresent against+// pronoun-inferred gender. A coarse signal, not the full Bechdel test+// (we can't read whether the conversation is about a man deterministically).+// 2) Dialogue share — does one character dominate the spoken lines? Counts+// attributed dialogue paragraphs per character (attributeDialogueByOwner)+// and flags a lopsided distribution (top speaker over a configurable share).+// 3) Screen-time balance — when gender is inferable, flag a strongly skewed+// appearing cast (e.g. a near-all-male roster) as a representation nudge.+//+// All three are advisory (low/medium): representation is an authorial choice and+// these are signals, not correctness errors. Gender is inferred ONLY from the+// canon `pronouns` field — absent/ambiguous pronouns yield 'unknown', and the+// gender-dependent signals stay silent rather than guess (absent ≠ a category).+// ---------------------------------------------------------------------------++// Infer a coarse gender bucket from a character's canon `pronouns` string. Only+// the unambiguous subject/object pronoun sets map; anything else (neopronouns,+// "any", blank, a sentence) is 'unknown' so a gender-dependent signal can opt+// out rather than miscategorize. Returns 'female' | 'male' | 'nonbinary' | 'unknown'.+function inferGender(pronouns) {+ const p = typeof pronouns === 'string' ? pronouns.toLowerCase() : '';+ if (!p) return 'unknown';+ const has = (re) => re.test(p);+ const she = has(/\bshe\b/) || has(/\bher\b/) || has(/\bhers\b/);+ const he = has(/\bhe\b/) || has(/\bhim\b/) || has(/\bhis\b/);+ const they = has(/\bthey\b/) || has(/\bthem\b/) || has(/\btheir\b/);+ // A clean single set wins; a mixed string ("she/they") is ambiguous → unknown,+ // except she+they / he+they which still read as a definite female/male identity+ // with a secondary set. Both she AND he present is genuinely ambiguous.+ if (she && he) return 'unknown';+ if (she) return 'female';+ if (he) return 'male';+ if (they) return 'nonbinary';+ return 'unknown';+}++// Coarse role-tier inference from a canon character's free-text `role` field, for+// the per-character dialogue-distribution signal (#1594). Only unambiguous keyword+// sets map to a tier; anything else (blank, a description, a role that mixes a+// major AND a minor word like "minor antagonist") is 'unknown' so the distribution+// signal opts out rather than guess — the same absent-vs-empty discipline+// inferGender() uses. Deliberately omits genuinely-ambiguous words ("supporting",+// "secondary", "recurring") that sit between lead and walk-on. Returns+// 'major' | 'minor' | 'unknown'. The two keyword sets live at module scope (vs+// inferGender's inline pronoun checks) so the regexes are compiled once, not on+// every per-character call.+const MAJOR_ROLE_RE = /\b(protagonist|deuteragonist|antagonist|villain|hero|heroine|lead|main|primary|central|principal)\b/;+const MINOR_ROLE_RE = /\b(minor|background|cameo|walk-?on|bit[- ]?part|extra|incidental|tertiary)\b/;+function inferRoleTier(role) {+ const r = typeof role === 'string' ? role.toLowerCase() : '';+ if (!r) return 'unknown';+ const major = MAJOR_ROLE_RE.test(r);+ const minor = MINOR_ROLE_RE.test(r);+ if (major && minor) return 'unknown'; // contradictory ("minor antagonist") → opt out+ if (major) return 'major';+ if (minor) return 'minor';+ return 'unknown';+}++// Normalized name → { char, gender, key } for every named canon character, plus+// the per-owner whole-token matcher reused for dialogue attribution. Built once+// per run so the dialogue scan and the co-presence scan share one identity map.+export function buildCastIdentities(ctx) {+ const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];+ const identities = [];+ for (const c of chars) {+ if (!c || typeof c !== 'object') continue;+ const name = typeof c.name === 'string' ? c.name.trim() : '';+ if (!name) continue;+ const key = normalizeName(name);+ if (!key) continue;+ const matcher = characterMatcher(characterNameTokens(c));+ identities.push({+ key,+ name,+ gender: inferGender(c.pronouns),+ roleTier: inferRoleTier(c.role),+ matcher,+ });+ }+ return identities;+}++// Resolve a scene's charactersPresent names to canon identity keys (so a scene+// that lists "Bob" maps to canonical "Robert"). A present name that matches no+// canon character is dropped — the co-presence signal is canon-relative.+export function sceneCastKeys(scene, identityByKey, identities) {+ const present = Array.isArray(scene?.charactersPresent) ? scene.charactersPresent : [];+ const keys = new Set();+ for (const raw of present) {+ if (typeof raw !== 'string' || !raw.trim()) continue;+ const direct = identityByKey.get(normalizeName(raw));+ if (direct) { keys.add(direct.key); continue; }+ // Fall back to a token match (the present-name might be an alias surface form).+ const hit = identities.find((id) => id.matcher && id.matcher.test(raw));+ if (hit) keys.add(hit.key);+ }+ return keys;+}+diff --git a/server/lib/editorial/checkInfra/sceneAnalysis.js b/server/lib/editorial/checkInfra/sceneAnalysis.jsnew file mode 100644index 0000000000..f5663be3ce--- /dev/null+++ b/server/lib/editorial/checkInfra/sceneAnalysis.js@@ -0,0 +1,296 @@+/**+ * Reverse-outline scene analytics (#2842 split of checkInfra.js): component mix,+ * grounding, plotline coverage, conflict-intensity tally, POV distribution and+ * secondary-character presence.+ */++import { normalizeName } from './externals.js';+import { scenePov } from './povAndNames.js';++// ---------------------------------------------------------------------------+// Scene component balance (#1296) — reads the cached reverse-outline (#1286)+// scene segmentation, where each scene carries a `components` boolean signal+// { narrative, action, dialogue }. The editorial rule: a scene should mix at+// least 2 of the 3; a single-mode scene (a narration wall, talking heads with+// no action, pure action with no interiority or voice) reads flat and is flagged.+//+// A scene with NO component flagged (all three false) is treated as+// "unclassified" (an older outline, or a scene the segmenter didn't tag), not+// "zero components" — it is skipped rather than flagged as a false positive,+// per the absent-vs-empty rule.+// ---------------------------------------------------------------------------++const SCENE_COMPONENT_KEYS = ['narrative', 'action', 'dialogue'];++// The present/missing component lists for a scene's `components` signal.+export function sceneComponentMix(components) {+ const c = components && typeof components === 'object' ? components : {};+ const present = SCENE_COMPONENT_KEYS.filter((k) => c[k] === true);+ const missing = SCENE_COMPONENT_KEYS.filter((k) => c[k] !== true);+ return { present, missing };+}++// A scene's display label for finding text/location — its heading, falling back+// to the summary, then a sequence-based label. Type-guarded because the reverse+// outline rides peer sync (#1348): a hand-edited / older-peer scene could carry a+// non-string heading, and a bare `.trim()` on it would throw and abort the check.+export const sceneLabel = (s) => {+ const heading = typeof s?.heading === 'string' ? s.heading.trim() : '';+ const summary = typeof s?.summary === 'string' ? s.summary.trim() : '';+ const seq = typeof s?.sequence === 'number' ? s.sequence + 1 : '?';+ return heading || summary || `scene ${seq}`;+};++// Render the reverse-outline scenes into a compact text block the scene-grounding+// LLM checks (#1309) pass alongside the manuscript so the model can attribute+// findings to scenes and reason about each scene's recorded setting / characters.+// Pure + deterministic so it's unit-testable and its token cost can be counted+// into the per-chunk overhead. Returns '' when there are no scenes (the prompt's+// `{{#sceneMap}}` section then renders nothing and the check degrades to a plain+// whole-issue manuscript scan). Type-guarded throughout — the reverse outline+// rides peer sync (#1348), so a hand-edited / older-peer scene could carry a+// non-string field that a bare `.trim()` would throw on.+export function sceneGroundingSummary(scenes) {+ const list = Array.isArray(scenes) ? scenes : [];+ const lines = list.map((s) => {+ if (!s || typeof s !== 'object') return '';+ const label = sceneLabel(s);+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';+ const setting = typeof s.setting === 'string' ? s.setting.trim() : '';+ const chars = Array.isArray(s.charactersPresent)+ ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())+ : [];+ const parts = [`- ${where}: ${label}`];+ parts.push(setting ? `setting: ${setting}` : 'setting: (none recorded)');+ if (chars.length) parts.push(`present: ${chars.join(', ')}`);+ return parts.join(' — ');+ }).filter(Boolean);+ if (!lines.length) return '';+ return `Scenes (from the reverse outline):\n${lines.join('\n')}`;+}++// Render the reverse-outline PLOTLINES (#1286) into a compact text block the+// plot-structure check (#1310) passes alongside the manuscript so the model can+// reconcile dropped subplots against the author's tagged plotlines — a plotline+// that opens early and is never returned to is a dropped subplot. For each+// plotline we count the scenes tagged to it (primary OR secondary) and report the+// span of issues those scenes touch, so the model sees which threads fizzle.+// Pure + deterministic so it's unit-testable and its token cost can be counted+// into the per-chunk overhead. Returns '' when there are no plotlines (the+// prompt's `{{#plotlineMap}}` section then renders nothing and the check degrades+// to reasoning about subplots from the prose alone). Type-guarded throughout —+// the reverse outline rides peer sync (#1348), so a hand-edited / older-peer+// plotline could carry a non-string field a bare `.trim()` would throw on.+export function plotlineCoverageSummary(plotlines, scenes) {+ const lines = Array.isArray(plotlines) ? plotlines : [];+ const sceneList = Array.isArray(scenes) ? scenes : [];+ const rows = lines.map((pl) => {+ if (!pl || typeof pl !== 'object') return '';+ const id = typeof pl.id === 'string' ? pl.id : '';+ if (!id) return '';+ const label = typeof pl.label === 'string' && pl.label.trim() ? pl.label.trim() : id;+ const kind = typeof pl.kind === 'string' && pl.kind.trim() ? pl.kind.trim() : 'other';+ // Scenes tagged to this plotline (primary or secondary), in outline order.+ const tagged = sceneList.filter((s) => s && (s.plotlineId === id || s.secondaryPlotlineId === id));+ const issues = [...new Set(+ tagged+ .map((s) => (Number.isInteger(s.issueNumber) ? s.issueNumber : null))+ .filter((n) => n != null),+ )].sort((a, b) => a - b);+ const span = issues.length+ ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)+ : 'no tagged scenes';+ return `- ${label} (${kind}): ${tagged.length} scene${tagged.length === 1 ? '' : 's'}, ${span}`;+ }).filter(Boolean);+ if (!rows.length) return '';+ return `Plotlines (from the reverse outline — reconcile dropped subplots against these):\n${rows.join('\n')}`;+}++// Curated lexicon of conflict / stakes / high-intensity markers (#1618). A+// per-issue tally of these words is a crude-but-deterministic proxy for dramatic+// intensity: the escalation-curve check can't "feel" tension, but it CAN see+// whether the density of conflict language rises, plateaus, or falls across the+// issues. The model treats the tally as a hint (not ground truth) and confirms+// the curve against the prose — so a quiet-but-tense scene the lexicon misses is+// still caught. Word-boundary matched, case-insensitive; kept deliberately small+// and high-signal (physical conflict + danger/stakes) to limit false hits.+const CONFLICT_INTENSITY_MARKERS = Object.freeze([+ // physical conflict / violence+ 'attack', 'attacks', 'attacked', 'fight', 'fights', 'fought', 'fighting',+ 'strike', 'strikes', 'struck', 'punch', 'punched', 'stab', 'stabbed', 'shoot',+ 'shoots', 'shot', 'kill', 'kills', 'killed', 'die', 'dies', 'died', 'death',+ 'blood', 'bleeding', 'wound', 'wounded', 'scream', 'screams', 'screamed',+ 'shout', 'shouted', 'slam', 'slammed', 'crash', 'crashed',+ // danger / stakes / dread+ 'danger', 'dangerous', 'threat', 'threats', 'threaten', 'threatened', 'enemy',+ 'enemies', 'weapon', 'weapons', 'gun', 'guns', 'knife', 'fire', 'fired',+ 'fires', 'firing', 'explode', 'exploded', 'explosion', 'fear', 'terror',+ 'panic', 'desperate', 'betray',+ 'betrayed', 'betrayal', 'trap', 'trapped', 'flee', 'fled', 'chase', 'chased',+ 'escape', 'war', 'battle', 'dying', 'doom', 'doomed',+]);++// Tally the conflict-marker density per issue across the WHOLE stitched manuscript+// (#1618) so the escalation-curve check sees the complete intensity shape on every+// chunk. Splits on the `# Issue N` headers the manuscript stitcher emits, counts+// markers + words per issue, and reports markers-per-1k-words — normalizing out+// raw length so a long-but-quiet issue doesn't read as more intense than a short+// climactic one. Pure + deterministic so it's unit-testable and its token cost can+// be counted into the per-chunk overhead. Returns '' when there are no issue+// headers (the prompt's `{{#intensityTally}}` section then renders nothing and the+// check judges the curve from the prose + scene map alone). A header that repeats+// across the stitch (a chunk boundary mid-issue) sums into the same issue bucket.+export function conflictIntensityTally(manuscript) {+ const text = typeof manuscript === 'string' ? manuscript : '';+ if (!text.trim()) return '';+ const headerRe = /^#+\s*Issue\s+(\d+)\b[^\n]*$/gim;+ const sections = [];+ let match;+ let prev = null;+ while ((match = headerRe.exec(text)) !== null) {+ if (prev) prev.end = match.index;+ prev = { issue: Number(match[1]), start: headerRe.lastIndex, end: text.length };+ sections.push(prev);+ }+ if (!sections.length) return '';+ const markerRe = new RegExp(`\\b(?:${CONFLICT_INTENSITY_MARKERS.join('|')})\\b`, 'gi');+ // Sum duplicate issue numbers (a repeated header across a stitch) — keep numeric+ // order so the rendered curve reads issue 1 → N for the model.+ const byIssue = new Map();+ for (const sec of sections) {+ const body = text.slice(sec.start, sec.end);+ const words = (body.match(/\b[\w']+\b/g) || []).length;+ const markers = (body.match(markerRe) || []).length;+ const acc = byIssue.get(sec.issue) || { words: 0, markers: 0 };+ byIssue.set(sec.issue, { words: acc.words + words, markers: acc.markers + markers });+ }+ const rows = [...byIssue.entries()]+ .sort((a, b) => a[0] - b[0])+ .map(([issue, { words, markers }]) => {+ const density = words > 0 ? (markers / words) * 1000 : 0;+ return `- Issue ${issue}: ${markers} conflict marker${markers === 1 ? '' : 's'} across `+ + `${words} word${words === 1 ? '' : 's'} (${density.toFixed(1)} per 1k)`;+ });+ if (!rows.length) return '';+ return 'Conflict-marker density per issue (deterministic intensity proxy — a rising '+ + 'number suggests escalation, a flat or falling one a plateau / de-escalation; '+ + 'treat as a hint and confirm against the prose):\n' + rows.join('\n');+}++// Human-readable POV-person labels for the head-hopping check's prompt (#1311).+// Inlined (not imported from styleGuide.js) to keep this registry pure — mirrors+// the labels in server/lib/styleGuide.js so generation and the check describe a+// POV person identically. An omniscient style guide no-ops via the check's gate,+// so it's intentionally absent here.+export const POV_PERSON_LABELS = Object.freeze({+ first: 'first person',+ 'third-limited': 'third-person limited',+ second: 'second person',+});++// Render the reverse-outline scenes into a compact POV-focused block the+// head-hopping check (#1311) passes alongside the manuscript so the model knows+// WHOSE head each limited-POV scene is anchored to — and which other characters+// are on-stage (candidate heads a head-hop would slip into). EVERY scene is+// rendered: a scene with no recorded POV character is marked "POV: (not recorded+// — infer from the prose)" rather than dropped, so a PARTIALLY-tagged outline+// doesn't silently omit scenes and let the model assume the list is exhaustive of+// POV-bearing scenes (the model still confirms each anchor against the prose).+// Pure + deterministic so it's unit-testable and its token cost can be counted+// into the per-chunk overhead. Returns '' only when there are NO scenes at all+// (the prompt's `{{#povMap}}` section then renders nothing and the check degrades+// to a plain whole-issue scan). Type-guarded throughout — the reverse outline+// rides peer sync (#1348), so a hand-edited / older-peer scene could carry a+// non-string field that a bare `.trim()` would throw on.+export function scenePovSummary(scenes) {+ const list = Array.isArray(scenes) ? scenes : [];+ const lines = list.map((s) => {+ if (!s || typeof s !== 'object') return '';+ const label = sceneLabel(s);+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';+ const pov = scenePov(s);+ // Other on-stage characters are the candidate heads a head-hop slips into —+ // exclude the POV holder themselves (by normalized name) so the list names+ // only "other" heads. When the scene has no recorded POV holder there's no+ // one to exclude, so every present character is a candidate.+ const povKey = pov ? normalizeName(pov) : '';+ const others = Array.isArray(s.charactersPresent)+ ? s.charactersPresent+ .filter((n) => typeof n === 'string' && n.trim() && normalizeName(n) !== povKey)+ .map((n) => n.trim())+ : [];+ const povText = pov ? `POV: ${pov}` : 'POV: (not recorded — infer from the prose)';+ const parts = [`- ${where}: ${label} — ${povText}`];+ if (others.length) parts.push(`others present: ${others.join(', ')}`);+ return parts.join(' — ');+ }).filter(Boolean);+ if (!lines.length) return '';+ return `POV per scene (from the reverse outline):\n${lines.join('\n')}`;+}++// Render the RECURRING NON-POV cast (#1585) into a compact text block the+// secondary-arc check passes alongside the manuscript, so the model focuses on+// the side characters that actually carry weight (present across multiple scenes)+// rather than every walk-on. A "secondary" character is one who appears in+// `charactersPresent` but NEVER holds `povCharacter` in ANY scene — a character+// who ever takes the viewpoint is a POV character (covered by pov.justified). For+// each such character we count the scenes they appear in and the span of issues+// those scenes touch, keeping only those at or above `minScenes` (the recurrence+// threshold). Pure + deterministic so it's unit-testable and its token cost can+// be counted into the per-chunk overhead. Returns '' when no non-POV character+// recurs enough (the prompt's `{{#secondaryCast}}` section then renders nothing+// and the check degrades to identifying recurring side characters from the prose+// alone). Type-guarded throughout — the reverse outline rides peer sync (#1348),+// so a hand-edited / older-peer scene could carry a non-string field a bare+// `.trim()` would throw on.+export function secondaryCharacterPresenceSummary(scenes, { minScenes = 2 } = {}) {+ const list = Array.isArray(scenes) ? scenes : [];+ const threshold = Number.isInteger(minScenes) && minScenes > 0 ? minScenes : 2;++ // Every character who EVER holds the viewpoint, by normalized name — these are+ // POV characters and are excluded from the secondary cast even in scenes where+ // they happen to be present-but-not-narrating.+ const povHolders = new Set();+ for (const s of list) {+ const pov = scenePov(s);+ if (pov) povHolders.add(normalizeName(pov));+ }++ // Non-POV character → { name, sceneCount, issues } keyed by normalized name so+ // casing / spacing variants collapse. Preserves first-appearance order (scenes+ // arrive sequence-ordered) for stable output.+ const cast = new Map();+ for (const s of list) {+ if (!s || typeof s !== 'object') continue;+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const present = Array.isArray(s.charactersPresent)+ ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())+ : [];+ // De-dup names within a single scene so a name listed twice counts once.+ const seenThisScene = new Set();+ for (const name of present) {+ const key = normalizeName(name);+ if (!key || povHolders.has(key) || seenThisScene.has(key)) continue;+ seenThisScene.add(key);+ let entry = cast.get(key);+ if (!entry) { entry = { name, sceneCount: 0, issues: new Set() }; cast.set(key, entry); }+ entry.sceneCount += 1;+ if (issueNumber != null) entry.issues.add(issueNumber);+ }+ }++ const rows = [];+ for (const entry of cast.values()) {+ if (entry.sceneCount < threshold) continue;+ const issues = [...entry.issues].sort((a, b) => a - b);+ const span = issues.length+ ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)+ : 'no tagged issues';+ rows.push(`- ${entry.name}: present in ${entry.sceneCount} scene${entry.sceneCount === 1 ? '' : 's'} (${span})`);+ }+ if (!rows.length) return '';+ return `Recurring non-POV characters (appear in ${threshold}+ scenes but never hold POV — judge whether each shows meaningful change):\n${rows.join('\n')}`;+}+diff --git a/server/lib/editorial/checkInfra/structureStages.js b/server/lib/editorial/checkInfra/structureStages.jsnew file mode 100644index 0000000000..fac4f20691--- /dev/null+++ b/server/lib/editorial/checkInfra/structureStages.js@@ -0,0 +1,311 @@+/**+ * Macro-structure stage names + their prompt summaries (#2842 split of+ * checkInfra.js): plot structure, worldbuilding doctrine, pacing, timeline,+ * fact accuracy, head-hopping, theme, climax agency, roster and comic/prose sync,+ * plus the canon roster/world/theme/cliffhanger summary renderers they feed.+ */++import { characterNameTokens } from './rosterCast.js';++// Stage name for the plot-structure & momentum LLM check (#1310). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 111 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the+// stitched manuscript plus the reverse-outline scene map + plotline coverage and+// the authored reader-map/arc to surface macro pathologies — passive protagonist,+// deus ex machina, idiot plot, flat/unclear stakes, sagging middle, and dropped+// subplots reconciled against the tagged plotlines.+export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';++// Stage names for the worldbuilding-doctrine LLM check pair (#2175). Both ship in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and reach existing installs via the multi-stage seed migration+// 167 (boot runs migrations but NOT setup-data, so the migration is required or+// the check throws "Stage not found" on first run). Both reconcile the prose against the+// canon world summary (`canonWorldSummary`) + the continuity-bible world-rule+// facts so an established-and-planted rule is NOT flagged:+// - unforeshadowed-solution: a plot problem solved by a rule/power the reader was+// never shown — deus ex machina's worldbuilding sibling.+// - cost-free-power: an ability used at a decisive moment with no cost/limitation+// on the page (violates "limitations > powers").+export const WORLD_UNFORESHADOWED_SOLUTION_STAGE = 'pipeline-editorial-world-unforeshadowed-solution';+export const WORLD_COST_FREE_POWER_STAGE = 'pipeline-editorial-world-cost-free-power';++// Stage name for the series-wide pacing / intensity escalation-curve LLM check+// (#1618). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration 140+// (boot runs migrations but NOT setup-data, so the migration is required). Reads+// the stitched manuscript plus the reverse-outline scene map and a deterministic+// per-issue conflict-marker density tally, and scores the per-issue dramatic+// intensity to flag a flat curve (issue 1 ≈ issue N), a front-loaded climax (the+// biggest beat lands early), or stakes that plateau / de-escalate across the arc.+// Complements plot.structure-momentum (flat stakes as one signal among many) by+// focusing the lens on the whole-series escalation shape.+export const PACING_ESCALATION_STAGE = 'pipeline-editorial-pacing-escalation-curve';++// Stage name for the timeline / canon-contradiction LLM check (#1581). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 129 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the established canon character facts, the reverse-outline scene+// ordering, and the authored per-character arcs to surface internal contradictions+// — a dead character who reappears alive, an age that contradicts the bible, or an+// impossible chronology.+export const TIMELINE_CONTRADICTION_STAGE = 'pipeline-editorial-timeline-contradiction';++// Stage name for the research / fact-accuracy LLM check (#1588). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 135 (boot runs+// migrations but NOT setup-data, so the migration is required). Reconciles the+// stitched manuscript against the author-supplied real-world fact reference+// (`series.factReference`) — a prose claim that contradicts a documented external+// fact (geography, history, physics/physiology). Opt-in and gated on the+// `series.factCritical` flag so it never fires on pure fantasy.+export const FACT_ACCURACY_STAGE = 'pipeline-editorial-fact-accuracy';++// Stage name for the character-consistency / unearned-personality-shift LLM check+// (#1582). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration 130+// (boot runs migrations but NOT setup-data, so the migration is required). Reads+// the stitched manuscript plus the established canon character TRAITS (personality,+// fixed traits, mannerisms, speech), the reverse-outline scene ordering, and the+// authored per-character arcs — and flags a shift the prose never earns: a reserved+// character cracking jokes with no beat, a fear/allergy silently contradicted, or+// POV knowledge that changes mid-scene with no on-page learning. Reconciles against+// the authored arcs so an intentional, earned transition is NOT flagged.+export const CHARACTER_CONSISTENCY_STAGE = 'pipeline-editorial-character-consistency';++// Stage name for the head-hopping / POV-discipline LLM check (#1311). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 112 (boot runs+// migrations but NOT setup-data, so the migration is required). Distinct from+// pov.justified (#1295, which asks whether each POV character earns an arc); this+// check polices POV *discipline* within a scene — narration that enters another+// character's head or reports what the POV character can't perceive.+export const HEAD_HOPPING_STAGE = 'pipeline-editorial-head-hopping';++// Stage name for the comic page-turn-beats LLM check (#1314). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 117 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads each issue's+// parsed comic-page layout (`comicPageTurnSummary`) plus the authored reveals /+// cliffhangers (`authoredRevealSummary`) and flags big reveals placed where the+// reader sees them early (a page the reader has already been looking at across the+// spread, rather than the first page after a turn). The deterministic sibling+// (comic.panel-rhythm) needs no stage.+export const COMIC_PAGE_TURN_STAGE = 'pipeline-editorial-comic-page-turn';++// Stage name for the theme-coherence / thematic-throughline LLM check (#1317).+// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 115 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the AUTHORED arc themes (series.arc.themes) and the reverse-outline+// scene map, and reconciles whether each declared theme is set up / complicated /+// paid off — surfacing stated-but-undramatized themes, dropped themes, a strong+// emergent theme not in the arc, and a climax that resolves plot but not theme.+export const THEME_COHERENCE_STAGE = 'pipeline-editorial-theme-coherence';++// Render the authored arc themes (#1317) into a compact text block the+// theme-coherence check passes alongside the manuscript, so the model reconciles+// whether the prose actually sets up / complicates / pays off each DECLARED theme+// (vs. stating it but never dramatizing it, or dropping it after the opening).+// Pure + deterministic so it's unit-testable and its token cost can be counted+// into the per-chunk overhead. Returns '' when no themes are authored (the+// prompt's `{{#declaredThemes}}` section then renders nothing and the check still+// runs to detect a strong emergent theme).+export function declaredThemesSummary(themes) {+ const lines = (Array.isArray(themes) ? themes : [])+ .map((t) => (typeof t === 'string' ? t.trim() : ''))+ .filter(Boolean)+ .map((t) => `- ${t}`);+ if (!lines.length) return '';+ return `Declared themes (authored on the story arc):\n${lines.join('\n')}`;+}++// Stage name for the climax / resolution-power LLM check (#1583). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 131 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the authored reader-map payoffs (series.arc.readerMap) and the+// declared themes (series.arc.themes) and the reverse-outline scene ordering, and+// judges whether the CLIMAX is the protagonist's hardest, most active choice (vs.+// a passive climax where an ally rescues them or events simply resolve around+// them) AND whether it resolves the story's core problem/theme (vs. a plot climax+// that lands the action but leaves the emotional/thematic core unanswered).+// Complements plot.structure-momentum (which flags a passive protagonist arc-wide;+// this one focuses the lens on the single payoff scene). The climax can only be+// judged once the whole manuscript is in view, so the run gates its verdict on the+// final part (`finalPart`); degrades to a prose-only scan when no reader-map,+// themes, or outline exist.+export const CLIMAX_AGENCY_STAGE = 'pipeline-editorial-climax-agency';++// Stage name for the emotional-beat / reaction-proportionality LLM check (#1584).+// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 132 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the reverse-outline scene map and judges whether each character's+// emotional reactions are PROPORTIONATE to the magnitude of the events that befall+// them: a high-magnitude event (trauma, death, betrayal, a major loss or win) that+// draws no on-page reaction and is never processed afterward (under-reaction), or a+// minor setback that triggers grief/rage out of all proportion (over-reaction).+// Because an unprocessed event in an early issue can stay unaddressed many issues+// later, the run carries high-magnitude events still awaiting a proportionate+// reaction across chunks (`crossChunkSetup`) so a later part can flag the missing+// payoff; degrades to a prose-only scan when no outline exists.+export const REACTION_PROPORTIONALITY_STAGE = 'pipeline-editorial-reaction-proportionality';++// Stage name for the secondary (non-POV) character-arc LLM check (#1585). Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 133 (boot runs+// migrations but NOT setup-data, so the migration is required). The sibling of+// pov.justified (#1295), which covers POV characters only: this check judges the+// RECURRING NON-POV cast — characters who appear in multiple scenes but never+// hold the viewpoint — and flags those who never change (a flat side character+// who is the same at the end as the start) or who regress without purpose. Reads+// the stitched manuscript plus the reverse-outline scene map (to tally which+// non-POV characters recur and weigh their presence) and the canon roster (so a+// genuinely-minor walk-on isn't held to an arc). Because a flat arc is a+// whole-story claim, the run gates its verdict on the final part (`finalPart`)+// and carries each recurring secondary character's established state forward+// across chunks (`crossChunkSetup`); degrades to a prose-only scan when no+// outline exists.+export const SECONDARY_ARC_STAGE = 'pipeline-editorial-secondary-arc';++// Stage name for the unmodeled-proper-nouns LLM check (#1412). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 116 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the canon roster (names + aliases) and asks the model to surface+// capitalized proper nouns used as apparent CHARACTER names that are absent from+// canon — the LLM-assisted half of roster economy (#1292) the deterministic+// `roster.economy` scan deliberately leaves alone (it can't tell a person from a+// place/org/brand/honorific).+export const UNMODELED_NAMES_STAGE = 'pipeline-editorial-unmodeled-names';++// Stage name for the eyeline-match continuity LLM check (#1466). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 117 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the per-issue+// storyboard shots (`ctx.storyboardScenes`, wired by #1315 — the same source the+// deterministic `visual.shot-continuity` check reads) and asks the model to flag+// eyeline-match breaks WITHIN a scene: two characters in conversation whose gaze+// directions don't reciprocate across the cut, or a described eyeline that+// contradicts the shot's screen direction. The judgment sibling the deterministic+// 180°/shot-type scan deliberately leaves to an LLM (see shotContinuity.js).+export const EYELINE_MATCH_STAGE = 'pipeline-editorial-eyeline-match';++// Stage name for the appearance/prop-continuity LLM check (#1467). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 118 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the same+// per-issue storyboard shots (`ctx.storyboardScenes`, wired by #1315) the eyeline+// sibling reads and asks the model to DIFF descriptions of the same entity across+// shots WITHIN a scene: a character's wardrobe/appearance that contradicts an+// earlier shot, a prop that appears/vanishes/transforms with nothing removing it,+// or a setting whose weather/time/layout flips with no transition. The semantic+// sibling the deterministic 180°/shot-type scan can't catch (the shot parser+// matches characters by name but never diffs their free-text descriptions).+export const APPEARANCE_CONTINUITY_STAGE = 'pipeline-editorial-appearance-continuity';++// Stage name for the comic ↔ prose synchronization LLM check (#1589). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 136 (boot runs+// migrations but NOT setup-data, so the migration is required). For a hybrid+// comic+prose issue it pairs the issue's PROSE (its prose stage) with its+// authoritative COMIC content (description + dialogue + caption + SFX — the same+// fields the `comicScript.pacing` source carries) and asks the model to flag+// SUBSTANTIVE cross-media divergences: a plot beat the prose narrates that no+// panel shows, panel dialogue that contradicts the prose, or a chronology+// disagreement across the two media. Comics legitimately compress and cut, so the+// prompt is tuned to ignore ordinary medium-translation trims.+export const COMIC_PROSE_SYNC_STAGE = 'pipeline-editorial-comic-prose-sync';++// Render the canon roster's names + aliases (#1412) into a compact text block the+// unmodeled-names check passes alongside the manuscript, so the model knows which+// proper nouns are ALREADY modeled (and therefore must NOT be flagged) and only+// surfaces apparent character names absent from this list. Pure + deterministic so+// it's unit-testable and its token cost can be counted into the per-chunk overhead.+// Returns '' when no canon character has a usable name (the prompt's+// `{{#knownCharacters}}` section then renders nothing and EVERY named proper noun in+// the prose is a candidate — exactly right when the bible is empty). Reuses+// `characterNameTokens` so name + aliases render with the same trim/de-dup the+// deterministic matcher uses.+export function canonRosterNamesSummary(canon) {+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];+ const lines = [];+ for (const c of chars) {+ // Require a real name — an alias-only row isn't a named character (mirrors+ // buildRosterAppearances, which skips nameless rows). characterNameTokens then+ // returns the trimmed name first, followed by de-duped aliases.+ if (!c || typeof c.name !== 'string' || !c.name.trim()) continue;+ const [name, ...aliases] = characterNameTokens(c);+ lines.push(aliases.length ? `- ${name} (also: ${aliases.join(', ')})` : `- ${name}`);+ }+ if (!lines.length) return '';+ return `Known characters (already in the story bible — do NOT flag these or their aliases):\n${lines.join('\n')}`;+}++// Render the established WORLD canon (#2175) — the named objects (with their+// significance) and places (with their recurring details) — into a compact text+// block the worldbuilding-doctrine checks pass alongside the manuscript so the+// model can tell a rule/power/artifact the prose ESTABLISHED (and may legitimately+// use) from one that appears out of nowhere. Objects carry the artifacts/powers a+// solution might draw on; places carry the world's physical logic. Prose+// `significance` / `description` / `recurringDetails` are the fields that state+// what a thing DOES and what it costs, so those are what get surfaced. Pure ++// deterministic (unit-testable, token-countable) and type-guarded throughout (the+// canon rides peer sync, so an older/hand-edited row could carry a non-string+// field). Returns '' when no object or place has usable content (the prompt's+// `{{#canonWorld}}` section then renders nothing and the check reasons from the+// prose alone).+export function canonWorldSummary(canon) {+ const objects = Array.isArray(canon?.objects) ? canon.objects : [];+ const places = Array.isArray(canon?.places) ? canon.places : [];+ const trim = (v) => (typeof v === 'string' ? v.trim() : '');+ const objectLines = [];+ for (const o of objects) {+ const name = trim(o?.name);+ if (!name) continue;+ const detail = trim(o?.significance) || trim(o?.description);+ objectLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);+ }+ const placeLines = [];+ for (const p of places) {+ const name = trim(p?.name) || trim(p?.slugline);+ if (!name) continue;+ const detail = trim(p?.recurringDetails) || trim(p?.description);+ placeLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);+ }+ if (!objectLines.length && !placeLines.length) return '';+ const blocks = [];+ if (objectLines.length) blocks.push(`Named artifacts / objects (with their significance):\n${objectLines.join('\n')}`);+ if (placeLines.length) blocks.push(`Named places (with their recurring details):\n${placeLines.join('\n')}`);+ // Neutral framing: this is the author's reference for what the world's+ // mechanics ARE, so a check can judge internal consistency. It deliberately+ // does NOT assert the reader has seen these — each consuming prompt sets that+ // interpretation (the unforeshadowed-solution check must still flag a canon+ // rule the PROSE never surfaced; the cost-free-power check reads it for the+ // costs a system is supposed to carry).+ return `World-bible reference (the author's record of the world's artifacts, places, and mechanics — use it to understand what a thing is and does; it is NOT the manuscript and does not prove the reader has seen any of it):\n\n${blocks.join('\n\n')}`;+}++// Render the authored reader-map cliffhangers (#1298) into a compact text block+// the chapter-ending check passes alongside the manuscript so the model+// reconciles its DETECTED endings against the issue-boundary tugs the writer+// already LOGGED — an authored cliffhanger the prose doesn't deliver, or a+// settled ending where the writer planned one. Pure + deterministic so it's+// unit-testable and its token cost can be counted into the per-chunk overhead.+// Returns '' when nothing is authored (the prompt's `{{#authoredCliffhangers}}`+// section then renders nothing). `atIssueBoundary` is the issue the cliffhanger+// caps (the cut falls between it and the next), so it's surfaced as a location hint.+export function authoredCliffhangerSummary(readerMap) {+ const cliffs = Array.isArray(readerMap?.cliffhangers) ? readerMap.cliffhangers : [];+ const lines = cliffs.map((c) => {+ const note = typeof c?.note === 'string' ? c.note.trim() : '';+ if (!note) return '';+ const at = Number.isFinite(c?.atIssueBoundary) ? ` (ending issue ${c.atIssueBoundary})` : '';+ return `- ${note}${at}`;+ }).filter(Boolean);+ if (!lines.length) return '';+ return `Authored cliffhangers (issue-boundary tugs the writer planned):\n${lines.join('\n')}`;+}diff --git a/server/lib/editorial/checkInfra/taxonomy.js b/server/lib/editorial/checkInfra/taxonomy.jsnew file mode 100644index 0000000000..63ec58c8c6--- /dev/null+++ b/server/lib/editorial/checkInfra/taxonomy.js@@ -0,0 +1,157 @@+/**+ * Editorial check taxonomy (#2842 split of checkInfra.js) — the declarative+ * vocabulary every check entry is validated against: scopes, kinds, severities,+ * the staleness `sources` allow-list, and the UI field types.+ */++export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);++// A check's `scope` may be a single scope string OR an array of scopes (#1628).+// A dual-scope check is one rule meaningful at more than one granularity — e.g.+// `relationships.reciprocity` reasons series-wide but could also flag a newly+// added relationship per issue — declared `scope: ['series', 'issue']` instead of+// being split into two near-duplicate checks. These helpers normalize either form+// so every consumer (the load-time guard, the catalog grouping, the dry-run plan)+// fans a check across exactly its declared scopes.+//+// `normalizeCheckScopes` returns the declared scopes deduped and in canonical+// CHECK_SCOPES order; an unknown/empty input returns []. `primaryCheckScope`+// returns the first declared scope (canonical order) for the consumers that still+// bucket/sort by a single value — for a single-scope check it is just that scope.+export function normalizeCheckScopes(scope) {+ const raw = Array.isArray(scope) ? scope : (scope == null ? [] : [scope]);+ return CHECK_SCOPES.filter((s) => raw.includes(s));+}++export const primaryCheckScope = (scope) => normalizeCheckScopes(scope)[0] || null;++export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);+export const CHECK_SEVERITIES = Object.freeze(['high', 'medium', 'low']);+export const SEVERITIES = CHECK_SEVERITIES;++// The inputs a check can read, declared per-check via `sources` (#1387). The+// staleness runner (server/services/pipeline/editorial/checkRunner.js) fingerprints+// EXACTLY a check's declared sources, so a finding only goes stale when content+// the check actually analyzed drifts — editing the style guide no longer marks a+// naming finding stale, and editing the ticking clock no longer marks every+// canon-only finding stale. Every token here must have a matching resolver in the+// runner's `SOURCE_RESOLVERS` (a load-time guard there fails fast if they drift).+// - 'manuscript' — the stitched manuscript corpus (implies needsManuscript)+// - 'canon' — the universe/series canon (characters, relationships, objects)+// - 'continuityBible' — the series CONTINUITY-BIBLE facts ledger (#1305): the+// extracted ground-truth facts the timeline/canon-contradiction+// check (#1581) reconciles the prose against — `[{ category,+// subject, statement, issueNumber }]` across the bible's+// categories (physical, age, dates/elapsed time, location,+// possession, world rules, who-knows-what). The runner fetches+// it via `getFactsLedger` (gated on this source) and injects+// `ctx.continuityBible` (the facts array).+// - 'series.styleGuide' — the series style guide (tense/POV/rating/reading level)+// - 'series.arc.tickingClock' — the series arc's ticking clock+// - 'reverseOutline' — the cached reverse-outline scene segmentation (#1286);+// scenes carry components/povCharacter/charactersPresent.+// The runner fetches it (gated on this source) and injects+// `ctx.reverseOutline` (the scenes array).+// - 'reverseOutline.plotlines' — the cached reverse-outline's PLOTLINE list (#1286):+// `[{ id, label, kind, color }]` plus the per-scene+// `plotlineId`/`secondaryPlotlineId` tags. The runner fetches+// the outline (gated on this source) and injects+// `ctx.reverseOutlinePlotlines`. The plot-structure check (#1310)+// reconciles dropped subplots against these tagged plotlines —+// which start and then fizzle without a resolution scene.+// - 'series.arc.readerMap' — the series arc's authored reader-map (#1299): the+// writer-logged hooks (questions planted) and payoffs+// (their resolutions). The Chekhov check reconciles its+// detected setups/payoffs against these authored ones.+// - 'editorialArcs' — the detected per-character arc directions from the series+// editorial analysis aggregate (#1295). The runner fetches it+// (gated on this source) and injects `ctx.editorialArcs`+// (`[{ name, arcDirection, issueCount, isProtagonist }]`). This+// is the coarse, DETECTED arc signal — distinct from the+// AUTHORED `series.characterArcs` model below.+// - 'series.characterArcs' — the AUTHORED per-character story arcs (#1293):+// `series.characterArcs[]` (`{ characterId, characterName,+// want, need, startState, endState, transitions[] }`). The+// arc.transitions check reconciles detected change moments+// against these authored transitions + flat-arc warnings.+// - 'storyboard.shots' — the per-issue storyboard shot lists+// (`stages.storyboards.scenes[].shots[]`) the+// visual-continuity check (#1315) reasons over:+// each shot carries `shotType` / `screenDirection`+// / `continuityFromShotId` (server/lib/shotGrammar.js).+// Served off the already-loaded `ctx.issues` (no+// extra I/O); the runner injects `ctx.storyboardScenes`+// (a flat list of `{ issueNumber, scene }` for every+// issue that has storyboard scenes).+// - 'comicScript' — every issue's AUTHORITATIVE comic content, keyed by+// issue number: the edited comic-pages split+// (`stages.comicPages.pages[]`) when present, else the+// generated `stages.comicScript.output`. The+// lettering-density check (#1313) counts per-panel/per-page+// word + balloon load over it (caption/dialogue/SFX only).+// Both comic-source checks read the same parsed pages via+// `comicLetteringIssues(ctx.issues)` (`[{ number, pages }]`);+// the runner fingerprints ONLY the lettering fields for this+// token, so a visual-description edit doesn't stale a+// lettering finding.+// - 'comicScript.pacing' — the same parsed comic pages, for the page-turn-beats+// LLM check (#1314), which reads each panel's visual+// `description` (+ caption/dialogue/SFX text) for its prompt+// digest. Distinct token from 'comicScript' because that+// broader read means a description edit must stale a page-turn+// finding while the lettering token stays put (and vice-versa).+// - 'comicScript.layout' — LAYOUT ONLY (per-page panel COUNT) for the panel-rhythm+// check (#1314), which reads nothing but counts. Separate from+// 'comicScript.pacing' so a text-only edit (reword a caption /+// description without adding/removing a panel) does NOT stale a+// rhythm finding — the splash/crowding/grid verdict can't have+// changed. All three comic tokens share `ctx.issues` (no extra I/O).+export const EDITORIAL_SOURCES = Object.freeze([+ 'manuscript',+ 'canon',+ 'continuityBible',+ 'series.styleGuide',+ 'series.arc.tickingClock',+ 'series.arc.readerMap',+ // The authored foreshadowing ledger (#2172): the arc-overview-emitted+ // plant → reinforce → payoff seeds the Chekhov check reconciles its detected+ // setups/payoffs against. Lives on the already-loaded series record (no extra+ // I/O); fingerprinting it stales Chekhov findings when the author edits the ledger.+ 'series.arc.foreshadowing',+ 'series.arc.themes',+ // The author-supplied real-world fact reference the opt-in research.fact-accuracy+ // check reconciles the prose against (#1588). Lives on the already-loaded series+ // record (no extra I/O); fingerprinting it stales fact findings when the author+ // edits the reference.+ 'series.factReference',+ 'reverseOutline',+ 'reverseOutline.plotlines',+ 'editorialArcs',+ 'series.characterArcs',+ 'storyboard.shots',+ 'comicScript',+ 'comicScript.pacing',+ 'comicScript.layout',+ // Each issue's PROSE-stage text SPECIFICALLY (#1589) — NOT the default manuscript+ // precedence (comicScript ▸ teleplay ▸ prose), which for a hybrid issue returns+ // the comic script. The comic↔prose-sync check reads this to compare prose against+ // the comic; fingerprinting it separately means a prose edit stales a sync finding+ // without a comic-only edit doing so (and vice-versa, via comicScript.pacing).+ 'prose',+]);++// Default per-run finding cap for user-defined checks (#1346) — mirrors the+// built-in LLM checks' `maxFindings` default so a long manuscript can't flood+// the review. Defined up here so the custom-check prompt builder and config+// schema (both below) share one source.+export const CUSTOM_CHECK_MAX_FINDINGS_DEFAULT = 12;++// The serializable config-field types a check can declare for its UI form.+// `configSchema` (a Zod schema) stays the validation authority on the server;+// `configFields` is the wire-safe *render* descriptor the Editorial Checks UI+// reads to build the per-check config form (the Zod schema can't cross the wire).+// Keep this in lockstep with the controls EditorialCheckCard's ConfigField+// renders — only advertise a type the UI can actually draw (no 'select' until+// the <select> control + an `options` contract land).+export const CHECK_FIELD_TYPES = Object.freeze(['number', 'boolean', 'text']);+diff --git a/server/lib/editorial/checkInfra/voiceCanon.js b/server/lib/editorial/checkInfra/voiceCanon.jsnew file mode 100644index 0000000000..2ade26fea7--- /dev/null+++ b/server/lib/editorial/checkInfra/voiceCanon.js@@ -0,0 +1,236 @@+/**+ * Voice + canon-state prompt summaries (#2842 split of checkInfra.js). Renders+ * the authored voice fields, style-guide intent, character state/trait facts and+ * the continuity ledger into the compact text blocks the LLM checks pass+ * alongside the manuscript.+ */++import { characterNameTokens } from './rosterCast.js';++// Stage name for the narrator voice / tone-consistency LLM check (#1586) — the+// narration-level sibling of voice-distinctiveness (which covers per-CHARACTER+// dialogue). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration 134+// (boot runs migrations but NOT setup-data, so the migration is required).+export const VOICE_CONSISTENCY_STAGE = 'pipeline-editorial-voice-consistency';++// Render each canon character's authored voice fields into a compact text block+// the voice-distinctiveness LLM check passes alongside the manuscript, so the+// model can flag lines that contradict a character's recorded speechPattern /+// speechAccent (closing the "voice fields feed generation only" gap, #1307) and+// reason about whether characters sound distinct from one another. Pure ++// deterministic so it's unit-testable and its token cost can be counted into the+// per-chunk overhead. Returns '' when no character carries a voice field (the+// prompt's {{#voiceProfiles}} section then renders nothing and the check+// degrades to a pure interchangeability scan).+export function characterVoiceProfiles(canon) {+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];+ const lines = [];+ for (const c of chars) {+ if (!c || typeof c !== 'object') continue;+ const name = typeof c.name === 'string' ? c.name.trim() : '';+ if (!name) continue;+ const pattern = typeof c.speechPattern === 'string' ? c.speechPattern.trim() : '';+ const accent = typeof c.speechAccent === 'string' ? c.speechAccent.trim() : '';+ if (!pattern && !accent) continue;+ const parts = [`- ${name}`];+ if (pattern) parts.push(`speech pattern: ${pattern}`);+ if (accent) parts.push(`accent/dialect: ${accent}`);+ lines.push(parts.join(' — '));+ }+ if (!lines.length) return '';+ return `Authored character voices (canon speechPattern / speechAccent):\n${lines.join('\n')}`;+}++// Render the series style guide's INTENDED narrative voice — the authored `tone`+// words (e.g. "witty", "grim", "lyrical") — into a compact block the narrator+// voice-consistency check (#1586) passes alongside the manuscript, so the model+// can measure each issue's narration against the declared intent, not just+// against the other issues. Pure + deterministic so it's unit-testable and its+// token cost counts into the per-chunk overhead. Type-guarded (styleGuide rides+// peer sync, so a hand-edited / older-peer guide could carry a non-array `tone`+// or non-string entries). Returns '' when the guide declares no tone (the+// prompt's {{#intendedVoice}} section then renders nothing and the check degrades+// to a pure cross-issue consistency scan).+export function intendedVoiceSummary(styleGuide) {+ const raw = Array.isArray(styleGuide?.tone) ? styleGuide.tone : [];+ const tone = raw+ .filter((t) => typeof t === 'string' && t.trim())+ .map((t) => t.trim());+ if (!tone.length) return '';+ return `Style guide — intended narrative tone/voice: ${tone.join(', ')}.`;+}++// Render each canon character's contradiction-relevant FACTS into a compact text+// block the timeline / canon-contradiction check (#1581) passes alongside the+// manuscript, so the model can reconcile the prose against the established bible:+// a character the bible records at age 16 who reads "in her 30s" on the page, a+// role/status the prose contradicts, or a description the prose breaks. Pure ++// deterministic so it's unit-testable and its token cost can be counted into the+// per-chunk overhead. Type-guarded throughout (canon rides peer sync, so a+// hand-edited / older-peer character could carry a non-string field a bare+// `.trim()` would throw on — and `age` is commonly stored as a number). Reuses+// `characterNameTokens` so name + aliases render with the same trim/de-dup the+// matcher uses. Returns '' when no character carries both a usable name AND a+// renderable fact (the prompt's `{{#canonStates}}` section then renders nothing+// and the check reasons from the prose + scene map alone).+const CANON_STATE_FACT_CHARS = 240;+export function canonCharacterStatesSummary(canon) {+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];+ const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');+ const rows = [];+ for (const c of chars) {+ if (!c || typeof c !== 'object') continue;+ // Require a real name — an alias-only row isn't a named character (mirrors+ // canonRosterNamesSummary, which skips nameless rows). characterNameTokens then+ // returns the trimmed name first, followed by de-duped aliases.+ if (typeof c.name !== 'string' || !c.name.trim()) continue;+ const [name, ...aliases] = characterNameTokens(c);+ const facts = [];+ // `age` is often a number in the bible — accept a finite number or a non-empty string.+ const age = typeof c.age === 'number' && Number.isFinite(c.age) ? String(c.age) : cleanStr(c.age);+ if (age) facts.push(`age ${age}`);+ const role = cleanStr(c.role);+ if (role) facts.push(`role: ${role}`);+ const status = cleanStr(c.status);+ if (status) facts.push(`status: ${status}`);+ // physicalDescription is the richer bible field; fall back to a generic description.+ const description = (cleanStr(c.physicalDescription) || cleanStr(c.description)).slice(0, CANON_STATE_FACT_CHARS);+ if (description) facts.push(`described as: ${description}`);+ if (!facts.length) continue;+ const who = aliases.length ? `${name} (also: ${aliases.join(', ')})` : name;+ rows.push(`- ${who} — ${facts.join('; ')}`);+ }+ if (!rows.length) return '';+ return `Canon character facts (the established bible — reconcile the prose against these):\n${rows.join('\n')}`;+}++// Render each canon character's PERSONALITY-relevant traits into a compact text+// block the character-consistency check (#1582) passes alongside the manuscript,+// so the model can flag an UNEARNED shift: a reserved character suddenly cracking+// jokes, an established fear/allergy silently contradicted, a voice that drifts+// off the authored speech pattern. Distinct from `canonCharacterStatesSummary`+// (age/role/status/described-as — the contradiction-of-FACTS grounding the+// timeline check reads) and from `characterVoiceProfiles` (speech only): this is+// the temperament/traits grounding. Pure + deterministic so it's unit-testable+// and its token cost can be counted into the per-chunk overhead. Type-guarded+// throughout (canon rides peer sync, so a hand-edited / older-peer character+// could carry a non-string field a bare `.trim()` would throw on, and+// mannerisms/likes/dislikes are commonly arrays). Reuses `characterNameTokens` so+// name + aliases render with the same trim/de-dup the matcher uses. Returns ''+// when no character carries both a usable name AND a renderable trait (the+// prompt's `{{#canonTraits}}` section then renders nothing and the check reasons+// from the prose alone).+const CANON_TRAIT_FACT_CHARS = 240;+export function canonCharacterTraitsSummary(canon) {+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];+ const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');+ // mannerisms / likes / dislikes are commonly arrays of short strings in the+ // bible; render the first few as a comma list. Tolerates a plain string too.+ const cleanList = (v) => {+ if (typeof v === 'string') return v.trim();+ if (!Array.isArray(v)) return '';+ return v.map((x) => (typeof x === 'string' ? x.trim() : '')).filter(Boolean).slice(0, 5).join(', ');+ };+ const rows = [];+ for (const c of chars) {+ if (!c || typeof c !== 'object') continue;+ // Require a real name — an alias-only row isn't a named character (mirrors+ // canonCharacterStatesSummary). characterNameTokens returns the trimmed name+ // first, followed by de-duped aliases.+ if (typeof c.name !== 'string' || !c.name.trim()) continue;+ const [name, ...aliases] = characterNameTokens(c);+ const facts = [];+ const personality = cleanStr(c.personality).slice(0, CANON_TRAIT_FACT_CHARS);+ if (personality) facts.push(`personality: ${personality}`);+ const specialTraits = cleanStr(c.specialTraits).slice(0, CANON_TRAIT_FACT_CHARS);+ if (specialTraits) facts.push(`fixed traits: ${specialTraits}`);+ const mannerisms = cleanList(c.mannerisms);+ if (mannerisms) facts.push(`mannerisms: ${mannerisms}`);+ const motivations = cleanStr(c.motivations).slice(0, CANON_TRAIT_FACT_CHARS);+ if (motivations) facts.push(`motivations: ${motivations}`);+ const likes = cleanList(c.likes);+ if (likes) facts.push(`likes: ${likes}`);+ const dislikes = cleanList(c.dislikes);+ if (dislikes) facts.push(`dislikes: ${dislikes}`);+ const speechPattern = cleanStr(c.speechPattern);+ if (speechPattern) facts.push(`speech: ${speechPattern}`);+ // Authored character-framework fields (CWQE Phase 10, #2175) — the Lie the+ // character believes, the Want (external goal), the Need (the Truth), and+ // the declared arc type. Surfacing these lets the consistency / arc checks+ // reconcile the prose against the PLAN (does the character overcome the Lie,+ // pursue the Want, arrive at the Need per the declared arc?) instead of+ // inferring the intended arc from the prose alone.+ const lie = cleanStr(c.lie).slice(0, CANON_TRAIT_FACT_CHARS);+ if (lie) facts.push(`believes (Lie): ${lie}`);+ const want = cleanStr(c.want).slice(0, CANON_TRAIT_FACT_CHARS);+ if (want) facts.push(`wants: ${want}`);+ const need = cleanStr(c.need).slice(0, CANON_TRAIT_FACT_CHARS);+ if (need) facts.push(`needs (Truth): ${need}`);+ const arcType = cleanStr(c.arcType);+ if (arcType) facts.push(`declared arc: ${arcType}`);+ if (!facts.length) continue;+ const who = aliases.length ? `${name} (also: ${aliases.join(', ')})` : name;+ rows.push(`- ${who} — ${facts.join('; ')}`);+ }+ if (!rows.length) return '';+ return `Canon character traits (the established bible — a shift away from these must be earned on the page):\n${rows.join('\n')}`;+}++// Human-readable labels for the continuity-bible fact categories (#1305). Inlined+// (not imported from server/services/pipeline/continuityBible.js) to keep this+// registry PURE — that module pulls in I/O + an SSE runner. Mirrors its+// `FACT_CATEGORIES`; a category absent from this map falls back to its raw id, so+// a new bible category still renders (just without a prettied label) until it's+// added here.+const CONTINUITY_CATEGORY_LABELS = Object.freeze({+ physical: 'Physical traits',+ age: 'Ages & birthdays',+ timeline: 'Dates & elapsed time',+ location: 'Locations & geography',+ possession: 'Possessions & wardrobe',+ 'world-rule': 'World rules',+ knowledge: 'Who knows what, when',+});++// Render the continuity-bible facts ledger (#1305) into a compact text block the+// timeline / canon-contradiction check (#1581) passes alongside the manuscript, so+// the model reconciles the prose against the established ground-truth facts the+// bible already extracted — ages/birthdays, dates & elapsed time, locations, world+// rules, who-knows-what — which the shallow per-character canon fields don't carry.+// Facts are grouped by category (in the stable category order) and tagged with the+// issue they were established in, when known, so the model can reason about WHEN a+// fact held. Pure + deterministic so it's unit-testable and its token cost can be+// counted into the per-chunk overhead. Type-guarded throughout (the ledger rides+// peer sync, so a hand-edited / older-peer fact could carry a non-string field).+// Returns '' when there are no usable facts (the prompt's `{{#continuityLedger}}`+// section then renders nothing and the check falls back to the canon fields + prose).+export function continuityLedgerSummary(facts) {+ const list = Array.isArray(facts) ? facts : [];+ const byCategory = new Map();+ for (const f of list) {+ if (!f || typeof f !== 'object') continue;+ const category = typeof f.category === 'string' ? f.category.trim() : '';+ const subject = typeof f.subject === 'string' ? f.subject.trim() : '';+ const statement = typeof f.statement === 'string' ? f.statement.trim() : '';+ if (!category || !statement) continue;+ const where = Number.isInteger(f.issueNumber) ? ` (Issue ${f.issueNumber})` : '';+ const line = subject ? `- ${subject}: ${statement}${where}` : `- ${statement}${where}`;+ if (!byCategory.has(category)) byCategory.set(category, []);+ byCategory.get(category).push(line);+ }+ if (!byCategory.size) return '';+ // Render known categories in their canonical order first, then any unknown+ // category (a newer-peer addition) after, so the block is stable + complete.+ const order = [...Object.keys(CONTINUITY_CATEGORY_LABELS), ...byCategory.keys()];+ const seen = new Set();+ const blocks = [];+ for (const category of order) {+ if (seen.has(category) || !byCategory.has(category)) continue;+ seen.add(category);+ const label = CONTINUITY_CATEGORY_LABELS[category] || category;+ blocks.push(`${label}:\n${byCategory.get(category).join('\n')}`);+ }+ return `Continuity bible facts (established ground truth — reconcile the prose against these):\n\n${blocks.join('\n\n')}`;+}+diff --git a/server/lib/editorial/checkInfraBarrel.test.js b/server/lib/editorial/checkInfraBarrel.test.jsnew file mode 100644index 0000000000..8bacd45124--- /dev/null+++ b/server/lib/editorial/checkInfraBarrel.test.js@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++import * as barrel from './checkInfra.js';++const HERE = dirname(fileURLToPath(import.meta.url));+const BARREL_SRC = readFileSync(join(HERE, 'checkInfra.js'), 'utf8');+const MODULE_FILES = readdirSync(join(HERE, 'checkInfra'))+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))+ .sort();++// Issue #2842 split the 2,635-line checkInfra.js into ./checkInfra/* with the+// original file kept as a re-exporting barrel (the same treatment #1152 gave+// arcPlanner.js). This pins that contract: every module export must be+// reachable through the barrel AS THE SAME object, so the ~30 existing+// `from './checkInfra.js'` imports in ./checks/*, checkRegistry.js and the+// pipeline runner survive untouched.+describe('checkInfra barrel re-exports (issue #2842)', () => {+ it('re-exports every module in ./checkInfra/', () => {+ for (const f of MODULE_FILES) {+ expect(BARREL_SRC, `missing barrel re-export for checkInfra/${f}`)+ .toContain(`'./checkInfra/${f}'`);+ }+ });++ it.each(MODULE_FILES)('%s exports are reachable from the barrel as the same objects', async (f) => {+ const mod = await import(`./checkInfra/${f}`);+ const keys = Object.keys(mod);+ expect(keys.length, `${f} exports nothing`).toBeGreaterThan(0);+ for (const key of keys) {+ expect(barrel[key], `barrel re-export of '${key}' (from ${f})`).toBe(mod[key]);+ }+ });++ it('no symbol collides across the split modules (flat `export *` would be ambiguous)', async () => {+ const seen = new Map();+ const collisions = [];+ for (const f of MODULE_FILES) {+ const mod = await import(`./checkInfra/${f}`);+ for (const key of Object.keys(mod)) {+ if (seen.has(key) && seen.get(key).value !== mod[key]) {+ collisions.push(`${key}: ${seen.get(key).file} vs ${f}`);+ } else if (!seen.has(key)) {+ seen.set(key, { file: f, value: mod[key] });+ }+ }+ }+ expect(collisions).toEqual([]);+ });++ it('keeps the public surface the check files depend on', () => {+ for (const fn of [+ 'normalizeCheckScopes', 'primaryCheckScope', 'runManuscriptLlmCheck',+ 'runManuscriptLlmCheckInline', 'mapLlmFindings', 'editorialFindingKey',+ 'editorialPriorFindingsDigest', 'editorialSetupDigest', 'buildSetupDigestPrompt',+ 'buildCustomCheckPrompt', 'canonCharacterTraitsSummary', 'canonCharacterStatesSummary',+ 'continuityLedgerSummary', 'characterVoiceProfiles', 'revealGatedCanonSummary',+ 'canonRosterNamesSummary', 'canonWorldSummary', 'buildCastIdentities',+ 'buildRosterAppearances', 'scenePovSummary', 'sceneGroundingSummary',+ 'plotlineCoverageSummary', 'runDensityCheck', 'comicLetteringIssues',+ 'proseSyncPairs', 'readingGradeLevel', 'escalateSeverity', 'castNameTokens',+ 'relationshipCanon', 'attachmentCanon',+ ]) {+ expect(typeof barrel[fn], fn).toBe('function');+ }+ for (const c of [+ 'CHECK_SCOPES', 'CHECK_KINDS', 'CHECK_SEVERITIES', 'SEVERITIES',+ 'EDITORIAL_SOURCES', 'CHECK_FIELD_TYPES', 'CUT_TYPES', 'SAFE_CUT_TYPES',+ 'ON_THE_NOSE_SUBTYPES', 'POV_PERSON_LABELS',+ ]) {+ expect(barrel[c], c).toBeDefined();+ }+ // The externals hub keeps forwarding zod + the pure sibling scanners.+ expect(typeof barrel.z?.object, 'z.object').toBe('function');+ expect(typeof barrel.estimateTokens, 'estimateTokens').toBe('function');+ expect(typeof barrel.parseComicScript, 'parseComicScript').toBe('function');+ });+});diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex e8beaebf0b..9873ac8db2 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -1,5 +1,5 @@/**- * Layered Intelligence Loop — deterministic backbone.+ * Layered Intelligence Loop — deterministic backbone (re-exporting barrel).** A perpetual, per-managed-app self-improvement loop (Engine B autonomous script* job). On a schedule the handler reads each enabled app's goals + telemetry,@@ -16,2616 +16,26 @@* and unit-tested. The I/O functions (gather, forge/jira/plan filers) take injectable* deps so tests can drive them without a live LLM, `gh`, or filesystem.*- * See docs/plans/2026-07-07-layered-intelligence-loop.md for the full design.- */--import { spawn } from 'child_process';-import { join, resolve, relative, isAbsolute, dirname } from 'path';-import { fileURLToPath } from 'url';-import { readFile, writeFile, appendFile, realpath } from 'fs/promises';-import { existsSync, readFileSync } from 'fs';-import { DAY, tryReadFile, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';-import { bufferedSpawn } from '../lib/bufferedSpawn.js';-import { fetchPublicText } from '../lib/safeUrlFetch.js';-import { validateCommand } from '../lib/commandSecurity.js';-import { getSettings } from './settings.js';-import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';-import { computeWindowedStats, computeEffectiveSuccessRate, EFFECTIVE_RATE_MIN_WINDOW_SAMPLES, extractTaskType } from './taskLearning/store.js';-import { formatRejectionReasons, formatRejectionReason, REJECTION_REASONS } from './layeredIntelligenceRejections.js';-import { formatExecutionFailures, summarizeExecutionFailures, formatExecutionFailure } from './layeredIntelligenceExecutionFailures.js';--// Tracker labels + slug marker. The slug is the stable dedup key the reasoner-// chooses; it is embedded in each filed issue body so a later run (or the-// reasoner reading open issues) can self-avoid duplicates.-export const LI_LABEL = 'layered-intelligence';-export const LI_BLOCKING_LABEL = 'layered-intelligence:blocking';--// The tracker label marking an issue as work the user has COMMITTED to — the-// `plannedWork` source's filter (#2698). PortOS's own roadmap "lives entirely in-// the GitHub issue tracker" as `plan`-labeled issues, and that convention is the-// default for managed apps too.-export const PLANNED_WORK_LABEL = 'plan';--// How many planned-work items are surfaced to the reasoner. The point is to give-// it enough of the committed backlog to spot an overlap, not to reproduce the-// tracker — the count of the FULL set is always reported alongside, so a-// truncated list never reads as the whole picture.-export const PLANNED_WORK_MAX_ITEMS = 15;--// Character bound for the rendered plannedWork block, matching the other-// file-backed sources' 8000-char ceiling.-export const PLANNED_WORK_MAX_CHARS = 8000;--// The instruction buildPrompt attaches directly beneath the plannedWork block —-// the whole point of the source: turn "here is the backlog" into "so do not file-// against it".-export const PLANNED_WORK_GUIDANCE = 'Cross-reference your proposal against the user\'s actively-planned work above. If your proposal duplicates or conflicts with an active item, DO NOT file — return proposal: null. Only propose genuinely new work that does NOT overlap with what is already in scope.';--// The LI Proposal Playbook (#2763): standing, human-authored guidance distilling-// which proposals actually land vs. get rejected — scope selection, success/rejection-// pattern catalogs, task-type selection rules, and a goal-alignment check. Loaded-// once from the co-located markdown file so the prose stays reviewable-as-prose and-// buildPrompt can render it verbatim as the always-on `liPlaybook` block. It ships in-// the SOURCE tree (not seeded to data/prompts/), so it is code-versioned guidance that-// updates with the code — NOT a user-customizable stage prompt, and thus needs no-// PROMPT_VERSIONS bump or setup-data migration. Read synchronously at module load so-// the constant is ready before the first buildPrompt call; the file ships with the-// module, so a miss is a packaging bug worth surfacing loudly rather than swallowing.-export const LI_PROPOSAL_PLAYBOOK = readFileSync(- join(dirname(fileURLToPath(import.meta.url)), 'layeredIntelligence.playbook.md'),- 'utf-8'-).trim();--// The instruction that frames the playbook block: apply it as a standing constraint,-// but let a live per-app data block (liOutcomes / liProposalExecution) override a-// general rule when it has real numbers that contradict it.-export const LI_PLAYBOOK_GUIDANCE = 'This playbook is the distilled, standing rule set for choosing WHAT to propose — apply it as a hard constraint on scope, task type, and goal alignment before you commit to a proposal. Where a live report above (liOutcomes / liProposalExecution) contradicts a general rule here with real data for THIS app, the live data wins; absent that data, follow the playbook.';--// Rendered when the tracker read SUCCEEDED and the app genuinely has no committed-// backlog. Says so explicitly rather than omitting the block, so "nothing planned"-// is legible to the reasoner as a real answer rather than a missing source.-export const PLANNED_WORK_NONE = 'No actively-planned work is currently tracked for this app. (The tracker was read successfully — this is a real "nothing is planned", not a failed read.)';--// Stable opening of the failed-read marker, so `hasPlannedWorkListing` can tell a-// sentinel from a real backlog listing without re-deriving the whole sentence.-export const PLANNED_WORK_UNAVAILABLE_PREFIX = 'Planned work could NOT be read';--// Jira labels can't contain spaces, and a ':' is unsafe on some Jira versions,-// so the Jira pause label swaps the ':' for a '-'. The base LI_LABEL is already-// Jira-safe (kebab, no colon) and is reused verbatim across all trackers.-export const LI_JIRA_BLOCKING_LABEL = 'layered-intelligence-blocking';--// Closed issues carrying a matching slug suppress a re-proposal for this long,-// so the loop doesn't immediately re-file something the user just resolved.-export const CLOSED_SUPPRESSION_MS = 30 * DAY;--// Cosine-similarity floor for the semantic (embedding) near-duplicate guard that-// layers atop the exact slug/label dedup. A proposal whose embedding is at least-// this close to an existing dedup-window issue is treated as the same work worded-// differently and suppressed. Deliberately conservative — only near-identical-// intent should trip it (768-dim local embeddings put genuine near-dups ≳0.9).-export const SEMANTIC_DEDUP_THRESHOLD = 0.9;--// Cap the number of existing issues embedded per run so a repo with a large LI-// backlog can't fan out into an unbounded embedding sweep. Open dedup-window-// issues should be few (the loop files ≤1/run), so this is a generous ceiling.-export const SEMANTIC_DEDUP_MAX_CANDIDATES = 50;--// The id of the RETIRED global autonomous-job that used to drive the whole loop-// (the cross-app sweep). Layered Intelligence is now a per-app handler-backed-// scheduled task (#2322), so this constant is kept ONLY so migration 184 can find-// and tombstone the legacy `data/cos/autonomous-jobs.json` record on installs that-// still carry it. Nothing dispatches on it anymore.-export const LI_JOB_ID = 'job-layered-intelligence';--// Every proposal scope the reasoner may return. The handler enforces WHERE each-// lands (see PROPOSAL_SCOPE_TARGETS) and gates meta/self scopes to PortOS only.-export const PROPOSAL_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];--// Scopes that may only be filed when the sweeping app IS the PortOS install-// itself (they extend / improve the loop, which lives in the PortOS repo).-export const PORTOS_ONLY_SCOPES = ['loop-meta', 'portos-self'];--// The reasoner's honest effort/risk estimate for a proposal. Only a `trivial`-// proposal is ever eligible for the optional Engine-A hand-off (below); anything-// unrecognized normalizes to null (unknown → not trivial → never auto-handed-off).-export const PROPOSAL_COMPLEXITIES = ['trivial', 'moderate', 'complex'];--// The single complexity level that (with `safe: true` and hand-off enabled)-// lets the loop enqueue a coding agent instead of only filing the issue.-export const HANDOFF_COMPLEXITY = 'trivial';--// Merge rate (as a %) below which computeOutcomesReport tells the reasoner its-// proposals are landing badly and points it at the plannedWork source (#2698).-// Measured over RESOLVED proposals only — see computeOutcomesReport.-export const LOW_MERGE_RATE_THRESHOLD = 20;--// Minimum RESOLVED proposals before the low-merge-rate alarm is allowed to fire.-// 0-of-1 and 0-of-50 are both "0%", but only the second is evidence: telling the-// loop its rate is "critically low" after a single early rejection biases it-// toward filing nothing, which is self-reinforcing — it can never earn a merge if-// it stops proposing. A rate needs a sample before it means anything.-export const LOW_MERGE_RATE_MIN_SAMPLE = 4;--// LI's SCHEDULE name (taskSchedule.js SELF_IMPROVEMENT_TASK_TYPES) — also the key-// the type-failure ledger uses. NOT the key its runs are recorded under.-export const LI_SCHEDULED_TASK_TYPE = 'layered-intelligence';--// The `learning.json` byTaskType key LI's own agent runs actually land under — the-// bucket computeSelfEvalSummary reads to judge whether the LI machinery ITSELF is-// healthy (as opposed to how its proposals fare downstream once filed).-//-// DERIVED, never restated: a scheduled LI task is generated with-// `metadata.analysisType = 'layered-intelligence'` (cosTaskGenerator's-// generateSelfImprovementTaskForType), and extractTaskType's FIRST branch turns any-// task carrying an analysisType into `self-improve:<type>` — so these runs are-// recorded under `self-improve:layered-intelligence`, not the bare schedule name.-// The bare name IS correct in two OTHER stores (the schedule map and the-// type-failure ledger), which makes this an easy and silent thing to get wrong:-// guessing it would leave the execution-health signal permanently reading "no LI-// runs recorded yet". Building the key with the same function the WRITER uses means-// it cannot drift out of sync with however task types are keyed later.-export const LI_TASK_TYPE = extractTaskType({ metadata: { analysisType: LI_SCHEDULED_TASK_TYPE } });--// LI-task success rate (%) below which selfEval reports the loop's own execution-// as DEGRADED (#2700) — a separate failure mode from a low merge rate: the merge-// rate says "the user rejects what I propose", this says "my own runs are-// failing". Kept at 50 (a coin flip) rather than the merge-rate's 20: a proposal-// being rejected is normal triage, an LI run outright failing is not.-export const LI_DEGRADED_SUCCESS_THRESHOLD = 50;--// Minimum recorded LI runs before the degraded-execution signal is allowed to-// fire, for the same reason as LOW_MERGE_RATE_MIN_SAMPLE: 0-of-1 and 0-of-50 are-// both "0%", but only the second is evidence. Below the floor the rate is-// reported as-is but is NOT treated as a confidence signal either way.-export const LI_DEGRADED_MIN_SAMPLE = 4;--// LI execution health (%) below which the deterministic HARD PRE-FILING EXCLUSION-// gate (#2824) arms. Distinct from LI_DEGRADED_SUCCESS_THRESHOLD (50 — the "your-// loop is failing, hold a higher bar" ADVISORY line surfaced to the reasoner): the-// hard gate does not advise, it SUPPRESSES filing, so it opens a WIDER, more cautious-// net. Once LI's own runs dip below three-quarters success it stops FILING self--// directed work it demonstrably cannot see through, rather than merely being warned.-// Reuses the SCOPE_PREFER value (75) intentionally: the same "reliably executes" bar-// that marks a proposal DOMAIN preferable is the bar LI's own execution health must-// clear before it is trusted to file self-improvement work. The gate arms only on a-// CONFIDENT read (>= LI_DEGRADED_MIN_SAMPLE runs) — a cold loop is never locked out.-export const LI_HARD_GATE_EXECUTION_THRESHOLD = 75;--// The resolved outcomes a filed proposal can reach (the feedback loop, #2428).-// A record with a null outcome is still open/unresolved. All three are-// auto-derived from the tracker's closed state by deriveOutcome: completed →-// merged, not_planned → rejected, and any other PRESENT close reason-// (duplicate/stale/etc.) → abandoned (#2620); a reason-less close falls back-// to merged for trackers that report no stateReason.-export const PROPOSAL_OUTCOMES = ['merged', 'rejected', 'abandoned'];--// The EXECUTION outcomes an LI proposal reaches once it is handed off to a coding-// agent and that agent's run completes (#2765). Distinct from PROPOSAL_OUTCOMES-// (the FILING fate — did the issue get merged/closed): execution is "did LI's own-// coding agent successfully implement the proposal it filed". Only populated for-// proposals that took the Engine-A hand-off path (config.handoff.enabled + a-// trivial+safe proposal); a filed-but-never-handed-off proposal keeps a null-// executionOutcome. Environmental failures (rate-limit/outage) are NOT recorded —-// they say nothing about the proposal's domain (same gate as #2618).-export const PROPOSAL_EXECUTION_OUTCOMES = ['success', 'failure'];--// Minimum recorded executions before a proposal DOMAIN's success rate is trusted-// for the per-domain avoid/prefer split (#2765). Lower than SCOPE_AWARENESS_MIN_SAMPLE-// (3) because each data point here is a REAL, high-signal LI-proposal execution — not-// install-wide task-type telemetry that a proposal only loosely maps onto — and the-// hand-off path is rare, so a floor of 2 lets a genuine per-domain signal surface-// without letting a single fluke mint a list.-export const PROPOSAL_EXECUTION_MIN_SAMPLE = 2;--// Scope-awareness thresholds (#2760). LI's own execution data shows several CoS-// task-type scopes it consistently fails at (e.g. self-improve:layered-intelligence,-// branch-reconcile, accessibility all sit at 0%) while others succeed reliably-// (plan-task, test-coverage, performance at ~100%). Since an LI proposal is later-// EXECUTED as a CoS task, proposing work that maps to a chronically-failing scope is-// systematic waste. These bound a deterministic, self-clearing classifier-// (computeScopeAwareness) that surfaces the avoid/prefer split to the reasoner so it-// can steer proposals toward scopes that actually execute.-//-// A scope is "avoid" when its effective (recency-windowed-or-lifetime) success rate is-// below AVOID and it has enough completed runs to be evidence; "prefer" when at/above-// PREFER with the same sample floor. Reusing the degraded-execution boundary (50%) for-// AVOID keeps LI's two success signals — its own loop health and per-scope-// executability — on the same coin-flip line. The classification is recomputed from-// fresh metrics every run and keyed on the windowed rate (once the window clears the-// scheduler's own EFFECTIVE_RATE_MIN_WINDOW_SAMPLES floor), so an "avoid" scope-// self-clears once it recovers in-window — no persisted avoid-list to go stale (the-// issue's "dynamic adjustment" requirement). See computeScopeAwareness for why the-// windowed rate, not the near-permanent lifetime rate, is the right basis.-export const SCOPE_AVOID_SUCCESS_THRESHOLD = LI_DEGRADED_SUCCESS_THRESHOLD; // < 50% → avoid-export const SCOPE_PREFER_SUCCESS_THRESHOLD = 75; // >= 75% → prefer--// Minimum completed runs before a scope's rate is trusted for avoid/prefer, mirroring-// LI_DEGRADED_MIN_SAMPLE's rationale (0-of-1 and 0-of-50 are both "0%", only the-// second is evidence). Set to 3 per #2760 — one below the degraded floor because the-// prompt guidance is advisory (it steers the reasoner, it does not hard-suppress a-// proposal), so a slightly lower bar to surface the signal is acceptable.-export const SCOPE_AWARENESS_MIN_SAMPLE = 3;--// Prompt-size bounds for the scope-awareness block, so a long-lived install with many-// task types (mission task keys embed an unbounded mission name) can't render an-// oversized block — the raw cosMetrics source is already char-capped for the same-// reason. Cap the entries surfaced per list (the lists are sorted sharpest-first, so-// the cap keeps the most decision-relevant scopes) and truncate any single task-type-// name so one pathological key can't blow the budget.-export const SCOPE_AWARENESS_MAX_PER_LIST = 12;-export const SCOPE_AWARENESS_MAX_TYPE_LEN = 80;--/**- * The default per-app config. PortOS (isPortos) additionally gets the meta/self- * scopes so the loop can extend itself; every other app is capped at its own- * improvement + data-gap scopes. Off by default — the loop is a user-enabled- * scheduled automation (AI-provider "no cold-bootstrap" policy).- */-export function defaultLayeredIntelligenceConfig(isPortos = false) {- return {- enabled: false,- intervalMs: DAY,- providerId: null,- model: null,- sources: {- goals: true,- // The app's OWN performance metrics (a METRICS.md doc in the app repo): the- // user-success / KPI / production-telemetry signals the app tracks about- // itself. This is the PRIMARY signal for evaluating a managed app against- // its own goals and purpose, so it's on by default for every app. See the- // METRICS.md convention in docs/METRICS.md.- appMetrics: true,- // The autonomous coding-agent run stats this install records (learning.json).- // For the PortOS install these ARE its own-performance metrics; for a MANAGED- // app they describe how reliably PortOS's agents change the app (a tooling /- // interaction signal), NOT the app's own product performance — so default it- // on only for PortOS. A managed app measures itself through appMetrics/custom- // sources instead; the user can still opt this on per-app.- cosMetrics: isPortos,- healthReport: true,- planMd: true,- openIssues: true,- // The backlog the user has ALREADY committed to (#2698): `plan`-labeled- // tracker issues / the app's prioritized Jira backlog / PLAN.md's unchecked- // items. Open issues alone read as a flat list with no priority context, so- // the reasoner had no way to tell "nobody has looked at this" from "the user- // already scheduled this" — the top NOT_PLANNED rejection cause. On by- // default for every app: cross-referencing against committed work is only- // useful if it is there by default.- plannedWork: true,- // The self-feedback signal (#2428): past LI proposals + their tracker- // outcomes, fed back so the reasoner calibrates on its own merge rate.- // Default ON for the PortOS install (it improves itself), OFF for managed- // apps — the user opts in per-app via the LI config UI.- outcomes: isPortos,- // The loop's self-awareness signal (#2700): a deterministic read of LI's OWN- // record — proposal merge rate, how many of its proposals are already filed- // and suppressed, and whether its own agent runs are succeeding — folded back- // so the reasoner can judge its proposal quality BEFORE filing rather than- // only learning from rejections after. Same PortOS-only default as `outcomes`:- // it is built from LI's own history, which only the self-improving install- // accumulates meaningfully; managed apps opt in per-app.- selfEval: isPortos,- custom: []- },- rules: '',- allowedScopes: isPortos- ? ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']- : ['app-improvement', 'app-data-gap'],- // Engine-A hand-off. When enabled, a proposal the reasoner marks trivial+safe- // is ALSO enqueued as a CoS coding-agent task (approval-gated) instead of only- // being filed for later human triage. Off by default — letting an agent write- // code from the loop unattended is an extra opt-in on top of enabling the loop.- handoff: { enabled: false }- };-}--/**- * Merge an app record's stored `layeredIntelligence` over the defaults so a- * partial config (or none) still yields a complete, safe config. `sources` is- * merged one level deep so a stored `{ sources: { goals: false } }` doesn't wipe- * the other source toggles.- */-export function getEffectiveConfig(app) {- const isPortos = !!app?.isPortos;- const base = defaultLayeredIntelligenceConfig(isPortos);- const stored = (app?.layeredIntelligence && typeof app.layeredIntelligence === 'object' && !Array.isArray(app.layeredIntelligence))- ? app.layeredIntelligence- : {};- const merged = { ...base, ...stored };- merged.sources = {- ...base.sources,- ...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {})- };- // Merge handoff one level deep (like sources) so a partial `{ handoff: {} }`- // doesn't wipe the default `enabled`.- merged.handoff = {- ...base.handoff,- ...(stored.handoff && typeof stored.handoff === 'object' && !Array.isArray(stored.handoff) ? stored.handoff : {})- };- if (!Array.isArray(merged.sources.custom)) merged.sources.custom = [];- if (!Array.isArray(merged.allowedScopes)) merged.allowedScopes = base.allowedScopes;- return merged;-}--/**- * Whether a proposal scope is allowed for this app. A hallucinated or- * hand-edited scope cannot escape this gate: it must be a recognized scope, be- * in the app's `allowedScopes`, and — for meta/self scopes — the app must BE the- * PortOS install. Double-enforced regardless of what the prompt told the model.- */-export function isScopeAllowed({ scope, allowedScopes = [], isPortos = false }) {- if (!PROPOSAL_SCOPES.includes(scope)) return false;- if (PORTOS_ONLY_SCOPES.includes(scope) && !isPortos) return false;- return allowedScopes.includes(scope);-}--/** The HTML-comment slug marker embedded in a filed issue/ticket body. */-export function slugMarker(slug) {- return `<!-- lil-slug: ${slug} -->`;-}--/** Extract a `lil-slug` marker's value from a body string (null if absent). */-export function extractSlugFromBody(body) {- if (typeof body !== 'string') return null;- const m = body.match(/<!--\s*lil-slug:\s*([a-z0-9][a-z0-9-]*)\s*-->/i);- return m ? m[1].toLowerCase() : null;-}--/**- * Normalize a reasoner-chosen slug to a stable kebab id. Returns null for a- * non-string or an input that reduces to empty (so a bad slug is a no-op, never- * a mystery label).- */-export function normalizeSlug(slug) {- if (typeof slug !== 'string') return null;- const norm = slug- .toLowerCase()- .trim()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '')- .slice(0, 80);- return norm || null;-}--/**- * Whether an existing tracker issue is still within the dedup suppression window:- * OPEN, or CLOSED within CLOSED_SUPPRESSION_MS. Only a closed-long-ago issue- * falls out of the window so its work can be re-proposed. A closed issue with a- * missing/unparseable `closedAt` is PERMANENTLY in-window (suppressed): the main- * producer of that shape is a checked `- [x]` PLAN.md item (checkboxes carry no- * timestamp), and a completed plan item never needs re-proposal — treating it as- * "closed long ago" made the reasoner re-propose every done item on every run- * (#2620). A tracker row missing its close time (e.g. a jira Done ticket with no- * resolutiondate) is likewise suppressed rather than re-proposed — done work is- * never worth re-reasoning. Shared by both the slug dedup and the semantic dedup- * so the two guards agree on which issues still count.- */-export function isIssueWithinDedupWindow(issue, now = Date.now()) {- if ((issue?.state || '').toLowerCase() === 'open') return true;- const closedAt = issue?.closedAt ? Date.parse(issue.closedAt) : NaN;- if (!Number.isFinite(closedAt)) return true;- return now - closedAt <= CLOSED_SUPPRESSION_MS;-}--/**- * Deterministic dedup guard. Given the slug of the proposed item and the live- * tracker's existing issues (each `{ slug, state, closedAt }`), suppress the- * proposal when a match is open, OR closed within CLOSED_SUPPRESSION_MS.+ * This file had grown to 2,631 lines spanning constants, config, dedup, outcomes,+ * awareness reports, prompt assembly and four tracker filers. Issue #2842 split it+ * into ./layeredIntelligence/* the same way #1152 split `arcPlanner.js`; this+ * barrel re-exports everything so existing `from './layeredIntelligence.js'`+ * imports keep working. New code may import the focused module directly.*- * `slug` matching is case-insensitive on the normalized slug. `existingIssues`- * may carry either a parsed `slug` or a raw `body`/`title` we extract from.- */-export function isProposalDuplicate({ slug, existingIssues = [], now = Date.now() }) {- const target = normalizeSlug(slug);- if (!target) return false;- for (const issue of existingIssues) {- const issueSlug = issue.slug- ? normalizeSlug(issue.slug)- : extractSlugFromBody(issue.body) || extractSlugFromBody(issue.title);- if (issueSlug !== target) continue;- if (isIssueWithinDedupWindow(issue, now)) return true;- }- return false;-}--/**- * Build the text to embed for a proposal OR an existing issue — title + body,- * trimmed and length-capped so a single huge body can't blow the embedding- * model's context. Both sides go through THIS helper so the proposal and the- * candidates are embedded from the same seed shape (a fair comparison).- */-export function issueEmbedSeed({ title = '', body = '' } = {}) {- const parts = [title, body].map(s => (typeof s === 'string' ? s.trim() : '')).filter(Boolean);- return parts.join('\n\n').slice(0, 2000);-}--/** Cosine similarity of two equal-length numeric vectors. Returns 0 for a shape- * mismatch, empty vector, or a zero-magnitude vector (nothing meaningful to- * compare) rather than NaN, so a bad embedding can never trip the dedup guard. */-export function cosineSimilarity(a, b) {- if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0;- let dot = 0, na = 0, nb = 0;- for (let i = 0; i < a.length; i++) {- dot += a[i] * b[i];- na += a[i] * a[i];- nb += b[i] * b[i];- }- if (na === 0 || nb === 0) return 0;- return dot / (Math.sqrt(na) * Math.sqrt(nb));-}--/**- * Pure near-duplicate finder. Given the proposal's embedding and an array of- * candidates (each `{ slug?, number?, title?, embedding }`), return the single- * best candidate whose cosine similarity meets `threshold` (highest score wins),- * or null when none qualify / the proposal embedding is unusable. Side-effect-free- * and unit-tested; the I/O layer feeds it real embeddings.- */-export function findSemanticDuplicate({ proposalEmbedding, candidates = [], threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {- if (!Array.isArray(proposalEmbedding) || proposalEmbedding.length === 0) return null;- let best = null;- for (const c of candidates) {- if (!Array.isArray(c?.embedding) || c.embedding.length === 0) continue;- const score = cosineSimilarity(proposalEmbedding, c.embedding);- if (score >= threshold && (!best || score > best.score)) {- best = { slug: c.slug || null, number: c.number ?? null, title: c.title || '', score };- }- }- return best;-}--/**- * Whether the app is currently PARKED — i.e. has at least one OPEN blocking- * issue. When parked, the sweep skips the app entirely (no gather, no reason),- * resuming automatically once the blocking issue closes. Fully tracker-derived.- */-export function isAppParked(blockingIssues = []) {- return blockingIssues.some(i => (i.state || '').toLowerCase() === 'open');-}--/**- * Validate + normalize the reasoner's JSON. Returns- * `{ analysis, proposal, pause }` with invalid pieces dropped (never throws):- * - `proposal` kept only when it has a recognized scope + a normalizable slug- * + a non-empty title. `slug` is normalized in place.- * - `pause` kept only when it has a reason AND a resolvable target: an integer- * issue number, or `"this"` WITH a surviving proposal to block on. A- * `pause.blockOnIssue: "this"` with a null proposal is invalid → dropped.- */-export function validateReasonerResponse(parsed) {- const out = { analysis: '', proposal: null, pause: null };- if (!parsed || typeof parsed !== 'object') return out;- if (typeof parsed.analysis === 'string') out.analysis = parsed.analysis;-- const p = parsed.proposal;- if (p && typeof p === 'object' && !Array.isArray(p)) {- const slug = normalizeSlug(p.slug);- const title = typeof p.title === 'string' ? p.title.trim() : '';- if (PROPOSAL_SCOPES.includes(p.scope) && slug && title) {- out.proposal = {- scope: p.scope,- slug,- title,- body: typeof p.body === 'string' ? p.body : '',- value: typeof p.value === 'string' ? p.value : '',- // Hand-off signals. `complexity` normalizes to a known level or null- // (unknown → never trivial → never auto-handed-off); `safe` is a strict- // boolean so only an explicit `true` opens the hand-off path.- complexity: PROPOSAL_COMPLEXITIES.includes(p.complexity) ? p.complexity : null,- safe: p.safe === true- };- }- }-- const pause = parsed.pause;- if (pause && typeof pause === 'object' && !Array.isArray(pause)) {- const reason = typeof pause.reason === 'string' ? pause.reason.trim() : '';- const target = pause.blockOnIssue;- const isThis = target === 'this';- const num = Number.isInteger(target) ? target : (typeof target === 'string' && /^\d+$/.test(target) ? Number(target) : null);- // "this" requires a surviving proposal to block on; else an explicit issue number.- if (reason && ((isThis && out.proposal) || num)) {- out.pause = { blockOnIssue: isThis ? 'this' : num, reason };- }- }- return out;-}--/**- * Resolve `pause.blockOnIssue` to a concrete issue number. `"this"` maps to the- * number of the issue just filed from the proposal; an integer passes through.- * Returns null when it can't resolve (e.g. `"this"` but nothing was filed).- */-export function resolveBlockOnIssue(pause, filedIssueNumber) {- if (!pause) return null;- if (pause.blockOnIssue === 'this') return filedIssueNumber ?? null;- return Number.isInteger(pause.blockOnIssue) ? pause.blockOnIssue : null;-}--/**- * Whether a filed proposal qualifies for the optional Engine-A hand-off — i.e.- * the loop should enqueue a coding agent to implement it now, not just file it.- * Requires ALL of: hand-off enabled in the app's config, an issue actually filed- * (a concrete `filed` ref for the agent to work), and the reasoner marking the- * proposal both trivial AND safe. Any missing/false signal falls through to- * file-only. Pure — the handler feeds it the filed ref.- */-export function isHandoffEligible({ proposal, config, filed } = {}) {- if (filed == null || filed === '' || filed === false) return false;- if (!config?.handoff?.enabled) return false;- if (!proposal || typeof proposal !== 'object') return false;- return proposal.complexity === HANDOFF_COMPLEXITY && proposal.safe === true;-}--/**- * Build the CoS task payload that hands a filed proposal to an Engine-A coding- * agent. Deterministic (no I/O) so it's unit-tested; the handler passes the- * result to `addTask(..., 'internal')`. The task is APPROVAL-GATED — an agent- * writing code straight from the loop shouldn't run unattended (mirrors- * autoFixer's every code-editing task). The description leads with a stable- * `LI hand-off:` prefix so addTask's per-app dedup suppresses a re-enqueue while- * the same proposal's task is still pending/in-flight.- */-export function buildHandoffTask({ app, proposal, issueRef, recordExecution = false } = {}) {- const ref = typeof issueRef === 'number' ? `#${issueRef}` : String(issueRef ?? '').trim();- const context = [- '# Layered Intelligence hand-off',- '',- `The Layered Intelligence loop identified a TRIVIAL, SAFE improvement for **${app?.name || app?.id || 'this app'}** and filed it as ${ref}.`,- '',- '## Task',- `Implement the change described in ${ref} end-to-end: read the issue, make the fix, run the app's tests, and open a PR that closes ${ref}.`,- 'If — once you dig in — the change turns out to be non-trivial or carries any regression/data-loss risk, STOP and leave a comment on the issue explaining why instead of forcing it. Filing was the safe fallback; a half-done risky change is worse than none.',- '',- '## Proposal',- `- **Title:** ${proposal?.title || ''}`,- `- **Value:** ${proposal?.value || '(not provided)'}`,- '',- proposal?.body || ''- ].join('\n');- const task = {- description: `LI hand-off: ${proposal?.title || ref}`,- priority: 'MEDIUM',- context,- app: app?.id,- approvalRequired: true- };- // Per-proposal-domain execution tracking (#2765): stamp the proposal's identity +- // domain onto the task so, when this agent run completes, recordTaskCompletion can- // attribute the execution success/failure back to the proposal's DOMAIN (not the- // generic `internal-task` bucket this hand-off would otherwise land in). addTask- // allowlists this top-level field into `metadata.liProposal`, and registerAgent- // projects it onto `agent.metadata.taskLiProposal`. Kept a dedicated key (not any of- // the extractTaskType-recognized metadata fields) so it never reclassifies the task's- // own byTaskType bucket.- //- // Gated on `recordExecution` — the caller passes true ONLY when the outcomes source is- // on AND the tracker is outcomes-capable, the SAME gate that governs recordFiledProposal.- // Without this, a hand-off filed while outcomes-tracking is OFF would still carry the- // marker, and recordProposalExecution's missing-record fallback would create an outcome- // row — recording a proposal the source toggle says isn't tracked (codex P2). Omitting- // the marker keeps filing and execution-recording consistent with the one toggle.- if (recordExecution) {- task.liProposal = {- appId: app?.id ?? null,- slug: proposal?.slug ?? null,- scope: proposal?.scope ?? null- };- }- return task;-}--/**- * Which filing path a resolved work tracker uses. Branches the handler up front- * so a `plan` app never hits the forge-only label/issue paths.- * github / gitlab → 'forge' (gh / glab issue create + labels)- * jira → 'jira' (createTicket + description slug marker)- * plan (fallback) → 'plan' (append slug-tagged PLAN.md checklist item)- */-export function filerForTracker(resolved) {- if (resolved === 'github' || resolved === 'gitlab') return 'forge';- if (resolved === 'jira') return 'jira';- return 'plan';-}--/** Whether a resolved tracker supports pause (an issue to block on). `plan` doesn't. */-export function trackerSupportsPause(resolved) {- return filerForTracker(resolved) !== 'plan';-}--/**- * Derive a resolved outcome for a filed proposal from its live tracker issue.- * Pure — the reconciler feeds it a `{ state, stateReason, closedAt }` issue:- * - still open (or unknown state) → null (unresolved)- * - closed as "completed" → 'merged'- * - closed as "not planned" → 'rejected'- * - closed with any OTHER reason → 'abandoned' (duplicate/stale/etc. —- * counting these as merged inflated the- * merge-rate calibration signal, #2620)- * - closed with NO reason → 'merged' (graceful fallback: glab/jira- * and the plan filer report no stateReason,- * and their common close path IS a merge —- * absent ≠ other, per the sentinel rule)- * GitHub reports `stateReason` ('completed' | 'not_planned' | 'reopened' | …);- * other trackers omit it, so a bare closed issue reads as merged.- */-export function deriveOutcome(issue) {- if ((issue?.state || '').toLowerCase() !== 'closed') return null;- const reason = (issue?.stateReason || '').toLowerCase().replace(/[\s-]+/g, '_');- if (reason === 'not_planned') return 'rejected';- if (reason === '' || reason === 'completed') return 'merged';- return 'abandoned';-}--/**- * Tally a recorded-outcome list into the counts BOTH the outcomes report (#2428)- * and the self-eval summary (#2700) reason over. Pure; the single place the- * merge-rate math lives so the two blocks can never disagree about LI's record.- *- * `rawMergeRate` is measured over RESOLVED proposals only and is `null` when- * nothing has resolved yet — the sentinel rule: "no proposal has been judged" must- * not collapse into the same 0 as "every judged proposal was rejected". Callers- * round only for display (rounding before a threshold compare would let 19.6%- * read as 20% and suppress a warning that should fire).- */-export function summarizeOutcomeStats(outcomes = []) {- const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');- const total = filed.length;- const count = (name) => filed.filter(o => o.outcome === name).length;- const merged = count('merged');- const rejected = count('rejected');- const abandoned = count('abandoned');- const resolved = merged + rejected + abandoned;- return {- filed,- total,- merged,- rejected,- abandoned,- // Anything filed but not yet resolved — still awaiting triage, NOT a failure.- pending: total - resolved,- resolved,- rawMergeRate: resolved > 0 ? (merged / resolved) * 100 : null- };-}--/**- * Format the LI outcome-feedback report (#2428) from this app's recorded- * proposals + their reconciled outcomes. Pure + side-effect-free: the LI hook- * loads the outcomes and passes them here, then feeds the string into buildPrompt.- * Returns '' when there's nothing to report (no filed history) so the caller omits- * the block entirely rather than injecting an empty section.- */-export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false } = {}) {- const { filed, total, merged, rejected, abandoned, pending, resolved, rawMergeRate } =- summarizeOutcomeStats(outcomes);- if (total === 0) return '';- const pct = (n) => Math.round((n / total) * 100);-- // Per-scope merge rate — the calibration signal the reasoner acts on.- const scopes = new Map();- for (const o of filed) {- const s = o.scope || 'unknown';- const agg = scopes.get(s) || { filed: 0, merged: 0 };- agg.filed += 1;- if (o.outcome === 'merged') agg.merged += 1;- scopes.set(s, agg);- }- const scopeLines = [...scopes.entries()]- .sort((a, b) => b[1].filed - a[1].filed)- .map(([s, v]) => `- ${s}: ${v.filed} filed, ${v.merged} merged (${v.filed ? Math.round((v.merged / v.filed) * 100) : 0}%)`)- .join('\n');-- // Structured diagnosis of every non-merged proposal (#2689), replacing the raw- // tracker string this used to echo ('not_planned' merely restated the outcome).- // '' when nothing has been closed unmerged — distinct from "closed, reason- // unknown", which the line reports explicitly.- const rejectionReasons = formatRejectionReasons(filed, 5);-- // Structured diagnosis of every FAILED hand-off (#2764 §1) — the "why" behind the- // per-domain execution rate the liProposalExecution block reports (#2765). '' when- // no hand-off has failed, so the line below is omitted rather than contradicting a- // clean execution record.- const executionFailures = formatExecutionFailures(filed, 5);-- // Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED- // proposals only and is null when none have resolved — see summarizeOutcomeStats- // for the sentinel rationale (pending ≠ rejected). A null rate stays silent- // rather than alarming an app whose first proposal is simply still in flight.- // The sample floor is the same idea one step further out: 0-of-1 is not evidence.- const lowMergeWarning = (- rawMergeRate !== null- && resolved >= LOW_MERGE_RATE_MIN_SAMPLE- && rawMergeRate < LOW_MERGE_RATE_THRESHOLD- )- ? [- '',- `WARNING: your merge rate is critically low — only ${merged} of ${resolved} resolved proposals (${Math.round(rawMergeRate)}%) were merged.`,- // Only point at the plannedWork block when one was actually gathered — the- // source is per-app-toggleable and yields nothing on an unresolvable- // tracker, and citing a section that isn't in the prompt is just noise.- hasPlannedWork- ? 'Review the "plannedWork" source above: your proposals may be overlapping with work the user has already committed to. Propose only work that is clearly outside that committed backlog — and if you cannot find any, return proposal: null rather than filing something marginal.'- : 'Your proposals may be overlapping with work the user has already committed to, or missing what they actually value. Hold a higher bar: return proposal: null rather than filing something marginal.'- ]- : [];-- return [- 'Recent LI proposals (all still-open, plus outcomes resolved within ~30 days):',- `- Total filed: ${total}`,- `- Merged/implemented: ${merged} (${pct(merged)}%)`,- `- Rejected: ${rejected} (${pct(rejected)}%)`,- `- Abandoned: ${abandoned} (${pct(abandoned)}%)`,- `- Still open: ${pending} (${pct(pending)}%)`,- '',- 'By scope:',- scopeLines || '- (none)',- '',- `Why non-merged proposals were closed: ${rejectionReasons || 'nothing has been closed unmerged yet'}`,- // Only emit the execution-failure line when a hand-off has actually failed —- // an app whose proposals were never handed off (or all succeeded) shows nothing- // here rather than a misleading "no failures" line.- ...(executionFailures ? [`Why LI's own hand-offs failed when implemented: ${executionFailures}`] : []),- ...lowMergeWarning- ].join('\n');-}--// How many closed-but-still-suppressed proposals selfEval names before it-// summarizes the rest as a count. The block is a calibration aid, not a backlog-// dump — an unbounded list would crowd out the sources it exists to be weighed-// against, and past this many the reasoner has the pattern anyway.-export const SELF_EVAL_MAX_SUPPRESSED_LISTED = 8;--/**- * Recover a suppressed issue's normalized dedup slug — the key the reasoner must- * avoid re-using and the join key onto the outcome store's rejectionReason. Shapes- * vary by tracker: forge/jira rows carry `{ number, title, body }` (the slug lives- * in the body marker), while the `plan` filer yields bare `{ slug, state }`.- * Normalized both ways so the value matches the outcome record's stored slug- * (`normalizeSlug(slug)` at file time) exactly. Returns null when unrecoverable.- */-export function suppressedIssueSlug(issue) {- if (issue?.slug) return normalizeSlug(issue.slug);- return normalizeSlug(extractSlugFromBody(issue?.body) || extractSlugFromBody(issue?.title));-}--/**- * Build a `slug → rejectionReason` lookup from reconciled outcome records, so the- * self-eval "recently closed" line can tell the reasoner not just WHICH proposals- * to avoid but WHY each was closed — the feedback loop of #2689 (ask #4), closing- * the loop with the taxonomy #2735 already persists rather than any new signal.- *- * Only a RESOLVED non-merged record carries a diagnosis, and only a REAL taxonomy- * token (a member of REJECTION_REASONS) counts: a merged, unresolved, or- * still-unclassified (`rejectionReason == null`) record contributes nothing, and so- * does the `unknown-reason` SENTINEL — it means "we looked and found no signal",- * which is not an actionable failure pattern to route around, so annotating a- * suppressed proposal with "closed with no recorded reason" would add noise the- * reasoner can't act on (and would contradict the promise that undiagnosed closures- * stay unannotated). The annotation therefore appears only where a concrete reason- * explains the closure. First diagnosed record per slug wins (records arrive- * newest-filed-first). Pure.- */-export function rejectionReasonBySlug(outcomes = []) {- const map = new Map();- for (const o of Array.isArray(outcomes) ? outcomes : []) {- if (!o || (o.outcome !== 'rejected' && o.outcome !== 'abandoned')) continue;- if (!REJECTION_REASONS.includes(o.rejectionReason)) continue;- const slug = normalizeSlug(o.slug);- if (slug && !map.has(slug)) map.set(slug, o.rejectionReason);- }- return map;-}--/**- * Identify a suppressed proposal for the prompt: its slug (the actual dedup key the- * reasoner must avoid re-using) plus its title for human-readable context. Returns- * null when neither is recoverable — an unidentifiable entry is left to the count- * rather than rendered as a mystery bullet the reasoner can't act on.- *- * When `reasonBySlug` (from rejectionReasonBySlug) holds this slug's diagnosis, it- * is appended as glossed prose so the reasoner sees the specific failure pattern- * that sank the earlier proposal (#2689), not merely a slug to route around. An- * undiagnosed (null) or unmatched slug renders exactly as before.- */-export function describeSuppressedIssue(issue, reasonBySlug = null) {- const slug = suppressedIssueSlug(issue);- const title = typeof issue?.title === 'string' ? issue.title.trim() : '';- if (!slug && !title) return null;- const ref = issue?.number ? `#${issue.number} ` : '';- const reason = slug && reasonBySlug instanceof Map ? reasonBySlug.get(slug) : null;- const why = reason ? ` — previously closed: ${formatRejectionReason(reason)}` : '';- if (!slug) return `${ref}${title}${why}`.trim();- return `${ref}[${slug}]${title ? ` ${title}` : ''}${why}`.trim();-}--/**- * Format LI's self-evaluation block (#2700) — the loop's pre-filing quality check- * on its OWN reasoning. Pure + side-effect-free and NO LLM call: every line is- * derived from data the loop already has, so this never adds a provider round-trip- * (the "no cold-bootstrap LLM calls" policy). The hook loads the inputs and feeds- * the string to buildPrompt, exactly like computeOutcomesReport.- *- * Three independent self-signals, each of which is either PRESENT or explicitly- * reported ABSENT — never silently defaulted, because "I have no data about myself"- * and "the data says I am doing badly" demand opposite responses from the reasoner:- * 1. Proposal merge rate — do the user's triage decisions validate my picks?- * 2. Already-filed proposals — what have I said already that I must not repeat?- * 3. LI execution health — are my own agent runs even succeeding?- *- * Unlike computeOutcomesReport this ALWAYS returns a block when called: "you are- * reasoning with no signal about yourself, hold a higher bar" is the single most- * useful thing to tell a cold loop, so an empty-handed run is exactly when the- * block matters most.- *- * @param {Object} args- * @param {Array|null} args.outcomes - recorded proposals; `null` = NOT gathered- * (source off / outcomes-incapable tracker), `[]` = gathered and genuinely none.- * @param {Array|null} args.existingIssues - LI-labeled tracker issues; `null` = the- * tracker read FAILED or never ran, `[]` = read fine and LI has filed nothing.- * The caller MUST pass null on a failed read: readIssues returns `[]` for a blown- * read, which would otherwise read as "nothing filed" and license a re-file.- * @param {{ read: boolean, metrics: Object|null }|null} args.liTaskStats - from- * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;- * `read:true, metrics:null` = read fine and LI has simply never run a task.- * @param {number} [args.now] - clock seam for the suppression window.- * @returns {string} the liSelfEval block body.- */-/**- * Resolve LI's own EXECUTION HEALTH — the loop's reasoning-run success rate — into a- * single structured read, so every consumer (the selfEval Signal 3 line AND the hard- * exclusion gate, #2824) judges LI's health off the SAME number instead of each- * re-deriving it and risking drift. Reads the LI-task metrics bucket- * (readLiTaskMetrics) through the effective (recency-windowed-or-lifetime) success- * rate, exactly as Signal 3 did inline.- *- * @param {{ read: boolean, metrics: Object|null }|null} liTaskStats - from- * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;- * `read:true, metrics:null` = read fine and LI has simply never run a task.- * @param {{ now?: number }} [opts] - clock seam forwarded to computeEffectiveSuccessRate.- * @returns {{ rate: number|null, sample: number, source: string|null, confident: boolean }}- * `rate` is null when health is UNKNOWN (store unreadable, no runs, or no completed- * runs). `confident` is true only at >= LI_DEGRADED_MIN_SAMPLE runs — the floor- * below which a rate (0-of-1 vs 0-of-N) is not yet evidence.- */-export function computeLiExecutionHealth(liTaskStats = null, { now = Date.now() } = {}) {- if (!liTaskStats?.read || !liTaskStats.metrics) {- return { rate: null, sample: 0, source: null, confident: false };- }- const { successRate, source, windowedCompleted } = computeEffectiveSuccessRate(liTaskStats.metrics, { now });- if (successRate === null) return { rate: null, sample: 0, source: null, confident: false };- const sample = source === 'windowed' ? windowedCompleted : (liTaskStats.metrics.completed || 0);- return { rate: successRate, sample, source, confident: sample >= LI_DEGRADED_MIN_SAMPLE };-}--export function computeSelfEvalSummary({- outcomes = null,- existingIssues = null,- liTaskStats = null,- now = Date.now()-} = {}) {- const lines = [];-- // --- Signal 1: does the user actually merge what I propose? ------------------ let mergeSignal = false;- if (!Array.isArray(outcomes)) {- lines.push('- Proposal merge rate: UNAVAILABLE — no outcome history was gathered this run (the outcomes source is off, or this tracker cannot report outcomes). You cannot see how your past proposals fared; do not assume they went well.');- } else {- const { total, merged, resolved, rawMergeRate, filed } = summarizeOutcomeStats(outcomes);- if (total === 0) {- lines.push('- Proposal merge rate: no proposals filed yet for this app — you have no track record here to calibrate against.');- } else if (rawMergeRate === null) {- lines.push(`- Proposal merge rate: ${total} filed, none resolved yet — rate unknown. Awaiting triage is NOT rejection; do not read this as failure.`);- } else {- mergeSignal = resolved >= LOW_MERGE_RATE_MIN_SAMPLE;- // Same structured diagnosis as computeOutcomesReport (#2689) — one helper, so- // the two blocks can never disagree about why proposals were closed. Gated on- // the formatted string, not on `rejected`, because an `abandoned` proposal is- // also a non-merge worth explaining.- const reasons = formatRejectionReasons(filed, 3);- lines.push(- `- Proposal merge rate: ${merged} of ${resolved} resolved proposals merged (${Math.round(rawMergeRate)}%)`- + `${resolved < LOW_MERGE_RATE_MIN_SAMPLE ? ' — too small a sample to read a rate from yet' : ''}.`- + (reasons ? ` Why the rest were closed: ${reasons}.` : '')- );- }- }-- // --- Signal 2: what have I already said? (dedup awareness) ------------------- let trackerSignal = false;- if (!Array.isArray(existingIssues)) {- lines.push('- Your already-filed proposals: UNKNOWN — the tracker could not be read this run. You may be about to re-file something that already exists; hold a higher bar than usual.');- } else {- trackerSignal = true;- const open = existingIssues.filter(i => (i?.state || '').toLowerCase() === 'open');- // Closed but still inside the 30-day suppression window: re-proposing one of- // these gets deterministically dropped downstream, so spending the run on it is- // a wasted run. Surfaced so the reasoner can route around it BEFORE proposing.- const closedSuppressed = existingIssues.filter(i =>- (i?.state || '').toLowerCase() !== 'open' && isIssueWithinDedupWindow(i, now));- lines.push(- `- Your already-filed proposals: ${open.length} open`- + `${closedSuppressed.length ? `, plus ${closedSuppressed.length} closed but still within the ${Math.round(CLOSED_SUPPRESSION_MS / DAY)}-day suppression window` : ''}.`- + ` ${open.length + closedSuppressed.length- ? 'Re-proposing any of these is deterministically suppressed — the run is wasted. Propose something genuinely new.'- : 'Nothing is currently suppressed.'}`- );- // NAME the closed-but-suppressed ones. The open proposals are already listed in- // full elsewhere in the prompt, but a closed issue appears NOWHERE else — so- // without this the reasoner is told a number it cannot act on and can burn the- // whole run re-proposing something the dedup guard silently drops. Capped so a- // long tail can't crowd out the sources it is meant to be reasoning about.- if (closedSuppressed.length) {- // Join each suppressed proposal to its reconciled rejection reason (#2689),- // so the "do NOT re-propose" line also carries WHY each was closed — a- // no-extra-cost read of the outcome records selfEval already received. Empty- // when outcomes weren't gathered this run (`outcomes` not an array), leaving- // the line exactly as before.- const reasonBySlug = rejectionReasonBySlug(Array.isArray(outcomes) ? outcomes : []);- const named = closedSuppressed- .map(i => describeSuppressedIssue(i, reasonBySlug))- .filter(Boolean)- .slice(0, SELF_EVAL_MAX_SUPPRESSED_LISTED);- if (named.length) {- lines.push(- ` Recently closed (do NOT re-propose): ${named.join('; ')}`- + `${closedSuppressed.length > named.length ? ` (+${closedSuppressed.length - named.length} more)` : ''}`- );- }- }- }-- // --- Signal 3: is the LI machinery itself healthy? --------------------------- // Deliberately GLOBAL, not per-app: the learning store keys LI runs by task type- // alone, so this bucket aggregates the loop's runs across every app. That is the- // right scope for the question being asked — "is the LI machinery working?" is a- // property of the shared loop, not of the app it happens to be pointed at — and- // it mirrors the cosMetrics source, which is likewise install-wide.- let taskSignal = false;- let liDegraded = false;- if (!liTaskStats?.read) {- lines.push('- LI execution health: UNAVAILABLE — the CoS learning store could not be read.');- } else if (!liTaskStats.metrics) {- lines.push('- LI execution health: no LI runs recorded yet — this loop has no execution history.');- } else {- // Forward the clock seam via the shared helper (computeLiExecutionHealth), which- // the hard exclusion gate (#2824) reads too — so the DEGRADED line and the gate can- // never disagree about LI's own success rate. Without `now` computeEffectiveSuccessRate- // would read the real wall clock while the suppression-window branch above uses the- // injected one — the same summary reasoning against two different "nows".- const health = computeLiExecutionHealth(liTaskStats, { now });- if (health.rate === null) {- lines.push('- LI execution health: no completed LI runs recorded yet — success rate unknown.');- } else {- taskSignal = health.confident;- liDegraded = taskSignal && health.rate < LI_DEGRADED_SUCCESS_THRESHOLD;- lines.push(- `- LI execution health: ${health.rate}% of ${health.sample} ${health.source} LI runs succeeded`- + `${taskSignal ? '' : ' — too small a sample to judge'}${liDegraded ? ' — DEGRADED' : ''}.`- );- }- }-- // --- Confidence: how much do I actually know about myself? ------------------- // Purely a count of PRESENT signals — it rates the evidence available to the- // reasoner, NOT whether that evidence is flattering. A loop with a well-measured- // 0% merge rate has HIGH confidence in a bad result, which is precisely the state- // where it should act decisively rather than hedge.- const signalCount = [mergeSignal, trackerSignal, taskSignal].filter(Boolean).length;- const confidence = signalCount >= 3 ? 'high' : signalCount === 2 ? 'medium' : 'low';-- const guidance = [];- if (confidence === 'low') {- guidance.push(- '',- `GUIDANCE — low self-confidence (${signalCount} of 3 self-signals available): you are reasoning about this app with little evidence about your own track record. Do NOT compensate by proposing something speculative or sweeping. Prefer a small, concretely-grounded proposal you can justify from the gathered sources alone, and return proposal: null rather than filing a guess.`- );- }- if (liDegraded) {- guidance.push(- '',- `GUIDANCE — your own execution is degraded (LI run success is under ${LI_DEGRADED_SUCCESS_THRESHOLD}%): the problem may be THIS LOOP, not the app. Favor a narrowly-scoped, low-risk app-improvement / app-data-gap proposal that a coding agent can finish, and do not mark anything trivial+safe for hand-off while your runs are failing this often. Self-improve-scoped work (loop-meta / portos-self) is HARD-EXCLUDED while your execution health is below ${LI_HARD_GATE_EXECUTION_THRESHOLD}% (#2824): a degraded loop cannot repair itself, so that work is deferred to a human — return proposal: null rather than filing it.`- );- }-- return [- 'LI self-evaluation (deterministic — computed from this loop\'s own record, not a model\'s opinion):',- `- Reasoning confidence: ${confidence} (${signalCount} of 3 self-signals available)`,- ...lines,- ...guidance- ].join('\n');-}--/**- * Clamp a task-type / proposal-domain label so one pathological key (e.g. a mission- * task type embedding an unbounded mission name) can't blow the scope-awareness block- * budget. Shared by both avoid/prefer signals below.- */-function clampScopeLabel(label) {- return label.length > SCOPE_AWARENESS_MAX_TYPE_LEN- ? `${label.slice(0, SCOPE_AWARENESS_MAX_TYPE_LEN - 1)}…`- : label;-}--/**- * Render an avoid/prefer prompt block from pre-classified item lists — the presentation- * both scope-awareness signals share (#2760 install-wide task-type rates, #2765- * per-proposal-domain execution rates). Owns the sort (worst-first avoid, best-first- * prefer), the per-list cap + "…and N more" overflow, and the empty-guard, so a tweak- * to any of those lands in one place. Callers supply their own classified `avoid`/- * `prefer` lists, the per-item `fmt`, and the two headers — the only parts that- * legitimately differ between the two signals. Returns '' when both lists are empty.- */-function renderAvoidPreferSections({ avoid = [], prefer = [], fmt, avoidHeader, preferHeader }) {- if (!avoid.length && !prefer.length) return '';- avoid.sort((a, b) => a.rate - b.rate); // worst-first — sharpest signal at the top- prefer.sort((a, b) => b.rate - a.rate); // best-first- const section = (header, items) => {- const shown = items.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);- const more = items.length - shown.length;- const lines = shown.map(fmt);- if (more > 0) lines.push(`- …and ${more} more`);- return `${header}\n${lines.join('\n')}`;- };- const sections = [];- if (avoid.length) sections.push(section(avoidHeader, avoid));- if (prefer.length) sections.push(section(preferHeader, prefer));- return sections.join('\n\n');-}--/**- * Scope-awareness report (#2760). Classifies each CoS task TYPE by its completion rate- * into low-completion and high-completion lists, as directional context for the- * reasoner. Pure — takes the already-parsed per-type metrics map (the `summary`- * gatherSources builds from learning.byTaskType) and returns a report string, or ''- * when no type has enough runs to qualify either way.- *- * IMPORTANT (codex P1): this is per-task-TYPE, install-wide completion telemetry — NOT- * a per-proposal execution record. An LI proposal is later implemented through a- * claim/plan/handoff task whose task type does NOT carry the proposal's domain (a- * handoff becomes `internal-task`; a claimed issue runs under the claim task type), so- * these buckets are populated by independently-scheduled jobs, not by LI's own- * proposals bucketed by subject. The block is therefore framed as "work of this KIND- * tends to (not) get finished here" — useful directional context (especially LI's own- * reasoning-run type, self-improve:layered-intelligence, which IS LI's execution) — and- * deliberately NOT a claim that a given proposal maps 1:1 onto a listed type. Proper- * per-proposal-domain outcome correlation is tracked as a follow-up (#2765).- *- * `metricsByType[type] = { lifetimeSuccessRate, lifetimeCompleted, recentSuccessRate, recentCompleted, ... }`.- *- * Classification judges on the EFFECTIVE rate — the recency-windowed rate when the- * window has enough samples, else lifetime — NOT the raw lifetime rate. This matters- * for the issue's "dynamic adjustment" requirement: the lifetime rate barely decays- * (an old failure burst depresses it near-permanently), so a scope that has actually- * recovered would stay stuck on the avoid list for dozens of runs. Using the windowed- * rate lets a recovered scope leave "avoid" promptly — and, critically, this uses the- * SAME window floor as the scheduler's own skip logic- * (EFFECTIVE_RATE_MIN_WINDOW_SAMPLES, the threshold in computeEffectiveSuccessRate /- * isSkipCandidate): the window is trusted only at >= that many in-window runs, so a- * single noisy recent result can't flip a lifetime-reliable scope to avoid (or vice- * versa). Below that floor the lifetime rate governs, exactly as the scheduler does,- * so this advisory list moves in the same direction the scheduler acts on. The base- * sample floor still gates on LIFETIME completed: a scope needs enough TOTAL evidence- * to be judged at all. Each rendered rate is paired with the run count of the SAME- * basis (windowed count when the window governs, lifetime count otherwise) so the- * "N% over M runs" line never mixes a windowed rate with a lifetime count.- *- * The thresholds (50/75) are deliberately NOT the scheduler's 30% hard-skip line: this- * steering is advisory (it nudges what LI PROPOSES, it never suppresses execution), so- * a wider, more cautious net is correct here. LI still MAY propose in an avoid scope- * when it is genuinely the highest-value work — it just has to justify doing so.- */-export function computeScopeAwareness({ metricsByType = {} } = {}) {- const avoid = [];- const prefer = [];- for (const [type, m] of Object.entries(metricsByType || {})) {- const lifetimeN = m?.lifetimeCompleted || 0;- if (lifetimeN < SCOPE_AWARENESS_MIN_SAMPLE) continue; // not enough total evidence to judge- // Effective rate: trust the recency window ONLY when it carries enough samples —- // the same EFFECTIVE_RATE_MIN_WINDOW_SAMPLES floor the scheduler's- // computeEffectiveSuccessRate uses — so one noisy recent run can't flip a- // lifetime-reliable scope. Below the floor (including an empty window, where- // recentSuccessRate is null, not 0 — #2460), lifetime governs. Pair the rate with- // the count of its own basis so the rendered "N% over M runs" is truthful.- const useWindow = m?.recentCompleted >= EFFECTIVE_RATE_MIN_WINDOW_SAMPLES- && typeof m?.recentSuccessRate === 'number';- const rate = useWindow ? m.recentSuccessRate : m?.lifetimeSuccessRate;- if (typeof rate !== 'number') continue; // a never-run scope stays neutral- const n = useWindow ? m.recentCompleted : lifetimeN;- if (rate < SCOPE_AVOID_SUCCESS_THRESHOLD) avoid.push({ type, rate, n });- else if (rate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ type, rate, n });- }- // Honest framing (#2760, codex P1): these are per-task-TYPE completion rates for the- // whole install — NOT a per-proposal execution record. An LI proposal is implemented- // through a claim/plan/handoff task whose type does not carry the proposal's domain,- // so this is directional context ("work of this kind tends to (not) get finished- // here"), not a claim that a given proposal maps 1:1 onto a listed type.- return renderAvoidPreferSections({- avoid,- prefer,- fmt: ({ type, rate, n }) => `- ${clampScopeLabel(type)}: ${Math.round(rate)}% completed over ${n} runs`,- avoidHeader: `LOW-COMPLETION task types — work of this kind is finished below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time on this install:`,- preferHeader: `HIGH-COMPLETION task types — finished at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%:`- });-}--/**- * Aggregate LI proposal EXECUTION outcomes by proposal DOMAIN (scope) (#2765).- * Pure. Unlike computeScopeAwareness — which borrows install-wide CoS- * per-task-TYPE completion rates that a proposal only loosely maps onto — this is a- * TRUE per-proposal record: each data point is one of LI's OWN filed proposals that- * was handed off and executed, keyed by the domain (scope) it was proposed under.- *- * `outcomes` is the app's outcome records (from listOutcomes); only records carrying- * a resolved `executionOutcome` AND a `scope` contribute. Returns- * `{ [scope]: { completed, succeeded, successRate, failureSummary } }` (empty when- * nothing has been executed yet). The acceptance signal for #2765: after one proposal- * in domain X is executed, only X's bucket moves.- *- * `failureSummary` (#2764 §3) carries the per-domain execution-FAILURE taxonomy tally- * so a low execution rate no longer arrives without its cause: it is the shared- * `summarizeExecutionFailures` engine run over ONLY this domain's records (the engine- * itself keeps just the failures), the "filter per-domain, then reuse the existing- * summariser" join #2764 §3 asks for. Every bucket carries one — a domain with zero- * failed hand-offs simply reports `total: 0`, the honest "nothing to explain" reading.- */-export function computeExecutionByDomain(outcomes = []) {- // Group each executed record by its domain first, so the failure taxonomy can be- // tallied over that domain's OWN records rather than the install-wide set.- const recordsByScope = new Map();- for (const r of Array.isArray(outcomes) ? outcomes : []) {- if (!r || typeof r !== 'object') continue;- if (!PROPOSAL_EXECUTION_OUTCOMES.includes(r.executionOutcome)) continue;- const scope = typeof r.scope === 'string' && r.scope.trim() ? r.scope.trim() : null;- if (!scope) continue;- if (!recordsByScope.has(scope)) recordsByScope.set(scope, []);- recordsByScope.get(scope).push(r);- }- // Null prototype: `scope` is an LLM-authored free string, and a "__proto__"- // key on a plain object would silently rewrite the prototype instead of- // adding a bucket — vanishing from Object.entries while lookups read the- // prototype object.- const byDomain = Object.create(null);- for (const [scope, records] of recordsByScope) {- const completed = records.length;- const succeeded = records.filter(r => r.executionOutcome === 'success').length;- byDomain[scope] = {- completed,- succeeded,- successRate: Math.round((succeeded / completed) * 100),- // Reuse the shared taxonomy engine on this domain's slice — it discards the- // successes internally, so passing the whole slice yields this domain's own- // failure shape without a second pre-filter here.- failureSummary: summarizeExecutionFailures(records)- };- }- return byDomain;-}--/**- * Render the dominant execution-failure causes from a domain's `failureSummary`- * (#2764 §3) as a compact clause for the per-domain avoid line. Reuses the shared- * `formatExecutionFailure` gloss so the wording matches the install-wide failure line- * in computeOutcomesReport. Returns '' when the domain holds NO diagnosed failure — a- * pure-`unknown`/`unclassified` (or failure-free) domain adds no cause clause rather- * than a hollow "failed for unknown reasons" tail on every low-execution line.- */-function formatDominantFailureCause(failureSummary, limit = 2) {- const entries = Array.isArray(failureSummary?.entries) ? failureSummary.entries : [];- if (entries.length === 0) return '';- const listed = entries- .slice(0, limit)- .map(({ category, count }) => `${formatExecutionFailure(category)} (${count})`)- .join('; ');- return `failing mostly on ${listed}`;-}--/**- * Is this a proposal DOMAIN whose OWN hand-offs chronically fail — enough executed- * hand-offs to be evidence (PROPOSAL_EXECUTION_MIN_SAMPLE) AND a success rate below- * the coin-flip avoid line (SCOPE_AVOID_SUCCESS_THRESHOLD)? The single load-bearing- * definition of "on the avoid list", shared so the reasoner-facing prompt- * (computeProposalExecutionAwareness) and the deterministic hand-off gate- * (computeHandoffRouting) can NEVER disagree about which domains qualify — the- * design requires the prompt's avoid list and the gate to name the same set. Takes- * a per-domain bucket from computeExecutionByDomain (or undefined when the domain- * has no execution history → false).- */-function isAvoidDomain(bucket) {- return !!bucket- && bucket.completed >= PROPOSAL_EXECUTION_MIN_SAMPLE- && bucket.successRate < SCOPE_AVOID_SUCCESS_THRESHOLD;-}--/**- * Render the per-proposal-DOMAIN execution avoid/prefer split for the reasoning- * prompt (#2765) — the real per-proposal signal the #2760 install-wide scope block- * could only approximate. Returns '' when no domain clears the sample floor, so- * buildPrompt omits the block. Mirrors computeScopeAwareness's 50/75 thresholds and- * bounded rendering, but keys on the proposal's own scope and carries NO- * "directional context only" caveat: this IS how LI's own proposals in each domain- * fared, so the reasoner can steer toward domains it actually executes and away from- * domains where its own hand-offs fail even after the proposal was accepted.- */-export function computeProposalExecutionAwareness({ outcomes = [] } = {}) {- const byDomain = computeExecutionByDomain(outcomes);- const avoid = [];- const prefer = [];- for (const [scope, bucket] of Object.entries(byDomain)) {- // The per-domain failure CAUSE (#2764 §3) is surfaced only for domains that clear- // this floor — i.e. only where the domain is already listed as low-execution. A- // single failed hand-off below the floor is the install-wide early-signal case the- // "Why LI's own hand-offs failed" line in computeOutcomesReport already reports, so- // we do not also emit a one-sample per-domain cause here (it would read as a trend- // off n=1).- if (bucket.completed < PROPOSAL_EXECUTION_MIN_SAMPLE) continue; // not enough executions to judge this domain- if (isAvoidDomain(bucket)) avoid.push({ scope, rate: bucket.successRate, n: bucket.completed, cause: formatDominantFailureCause(bucket.failureSummary) });- else if (bucket.successRate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ scope, rate: bucket.successRate, n: bucket.completed });- }- return renderAvoidPreferSections({- avoid,- prefer,- // Only the avoid list carries a `cause`; a preferred (reliably-executed) domain has- // no failure shape worth naming, so its clause is simply absent.- fmt: ({ scope, rate, n, cause }) => `- ${clampScopeLabel(scope)}: LI implemented ${rate}% of its own ${scope} proposals successfully over ${n} executed${cause ? ` — ${cause}` : ''}`,- avoidHeader: `LOW-EXECUTION proposal domains — LI's OWN hand-offs in these domains succeed below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time; a proposal here needs a strong justification or a narrower slice:`,- preferHeader: `HIGH-EXECUTION proposal domains — LI reliably implements its own proposals here (at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%):`- });-}--// Header for the cross-reference block (#2764 §3). Names the pattern the block exists-// to surface: a domain LI PROPOSES well (its proposals earn merges) yet EXECUTES-// poorly (its own hand-offs there fail), which neither liOutcomes (merge rate alone)-// nor liProposalExecution (execution rate alone) puts side by side.-const CROSS_REFERENCE_HEADER = "Domains where LI PROPOSES well but EXECUTES poorly — the proposal earns a merge, yet LI's OWN hand-off to implement it tends to fail with the named cause. These are blind spots: you pick the right work here but can't finish it as handed off. Narrow such a proposal to a slice an agent can complete, split it, or route it to a human — don't re-file the same shape expecting a different execution result:";--/**- * Cross-reference MERGED-proposal success against EXECUTION-failure modes within the- * SAME domain (#2764 §3). Pure + side-effect-free like the sibling report functions;- * derives only from the outcome records already loaded (no new store read, no AI/tracker- * call). The unique signal it adds over liOutcomes (per-scope merge rate) and- * liProposalExecution (per-domain execution rate) is the CONTRAST between them: a domain- * whose proposals the user merges but whose hand-offs then fail is "proposes well,- * executes poorly" — the reasoner should keep proposing there but narrow the scope, not- * abandon the domain (which a low execution rate read alone might imply).- *- * A domain qualifies only when BOTH signals are present: at least one MERGED proposal- * (the "proposes well" side — otherwise the domain is just failing outright, which- * liProposalExecution already covers) AND at least one DIAGNOSED failed hand-off (the- * "executes poorly" side, with a concrete cause to name — a purely `unknown`/- * `unclassified` failure history has no actionable mode to cross-reference). Merge rate- * is measured over RESOLVED proposals only — the same denominator summarizeOutcomeStats- * uses for its rawMergeRate (pending ≠ a merge verdict), not computeOutcomesReport's- * per-scope rate, which divides by all filed. Sorted sharpest-execution-problem first;- * bounded like the avoid/prefer lists. Returns '' when no domain qualifies, so- * buildPrompt omits the block.- */-export function computeCrossReferenceAnalysis({ outcomes = [] } = {}) {- const records = Array.isArray(outcomes) ? outcomes : [];- const byDomain = computeExecutionByDomain(records); // per-domain failure taxonomy (self-guards bad records)-- // Per-domain merge stats over RESOLVED proposals (pending ≠ a merge verdict).- const mergeByScope = new Map();- for (const o of records) {- if (!o || typeof o !== 'object') continue;- const scope = typeof o.scope === 'string' && o.scope.trim() ? o.scope.trim() : null;- if (!scope) continue;- if (!PROPOSAL_OUTCOMES.includes(o.outcome)) continue; // unresolved: no verdict yet- const agg = mergeByScope.get(scope) || { merged: 0, resolved: 0 };- agg.resolved += 1;- if (o.outcome === 'merged') agg.merged += 1;- mergeByScope.set(scope, agg);- }-- const qualifying = [];- for (const [scope, exec] of Object.entries(byDomain)) {- const merge = mergeByScope.get(scope);- if (!merge || merge.merged < 1) continue; // "proposes well" side needs a merge- const { entries, diagnosed, total: failTotal } = exec.failureSummary;- if (diagnosed < 1) continue; // "executes poorly" side needs a diagnosed failed hand-off- const top = entries[0];- qualifying.push({- scope,- mergeRate: Math.round((merge.merged / merge.resolved) * 100),- merged: merge.merged,- resolved: merge.resolved,- cause: top.category,- causeCount: top.count,- failTotal,- diagnosed- });- }- if (!qualifying.length) return '';- // Sharpest execution problem first (most diagnosed failures), ties broken by the- // strongest "proposes well" contrast (highest merge rate) so the output is stable.- qualifying.sort((a, b) => b.diagnosed - a.diagnosed || b.mergeRate - a.mergeRate);- const shown = qualifying.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);- const more = qualifying.length - shown.length;- const lines = shown.map(q =>- `- ${clampScopeLabel(q.scope)}: proposals merge at ${q.mergeRate}% (${q.merged}/${q.resolved}) but hand-offs here fail on ${q.cause} (${q.causeCount} of ${q.failTotal})`- );- if (more > 0) lines.push(`- …and ${more} more`);- return `${CROSS_REFERENCE_HEADER}\n${lines.join('\n')}`;-}--/**- * Deterministic hand-off routing gate (#2764 §4). Given a proposal and the app's- * historical outcome records, decides whether a trivial+safe proposal may be- * auto-handed-off to a coding agent NOW, or must instead be filed for a human —- * because LI's OWN prior hand-offs in that domain chronically fail. This is the- * SYSTEM-side enforcement of the same signal the reasoner is merely WARNED about- * in the liProposalExecution / liCrossReference prompt blocks: even when the- * reasoner marks a proposal trivial+safe, the gate suppresses the auto-hand-off- * for a domain whose track record says the hand-off will just fail again.- *- * Pure + side-effect-free, like the sibling compute* report functions — derives- * only from the `li-outcomes` records already loaded (no new AI/tracker/store- * call). The just-filed proposal cannot skew this: computeExecutionByDomain only- * counts records carrying a resolved `executionOutcome`, which a freshly-filed- * proposal has not got yet.- *- * Shares the isAvoidDomain classifier with computeProposalExecutionAwareness so the- * gate and the reasoner-facing prompt can NEVER disagree about which domains are- * "chronically failing": a domain qualifies only when it has at least- * PROPOSAL_EXECUTION_MIN_SAMPLE executed hand-offs AND its success rate is below- * SCOPE_AVOID_SUCCESS_THRESHOLD — the SAME floor + threshold that puts a domain on- * the reasoner's avoid list.- *- * Returns:- * - `{ handoff: true, reason: null }` — allow the auto-hand-off, when the- * proposal has no scope (can't judge), the domain is below the sample floor,- * the domain has no execution history, or its rate is at/above the threshold.- * - `{ handoff: false, domain, rate, n, cause, reason }` — SUPPRESS: file for a- * human instead. `reason` names the domain, rate, sample size, and (when a- * dominant failure cause is diagnosed) the cause — reusing formatDominantFailureCause,- * which returns '' for a purely unknown/unclassified domain so the cause clause- * is simply omitted there.- *- * @param {object} args- * @param {object} args.proposal - the reasoner's proposal ({ scope, ... }).- * @param {Array} [args.outcomes] - the app's li-outcomes records.- * @returns {{ handoff: boolean, reason: string|null, domain?: string, rate?: number, n?: number, cause?: string }}- */-export function computeHandoffRouting({ proposal, outcomes = [] } = {}) {- // No scope → we can't map the proposal to a domain's track record, so we can't- // justify suppressing the hand-off. Allow, as before §4 existed.- const domain = typeof proposal?.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;- if (!domain) return { handoff: true, reason: null };-- const byDomain = computeExecutionByDomain(outcomes);- const bucket = byDomain[domain];- // Below the floor, no bucket, or at/above the threshold → no signal to suppress on,- // so allow the hand-off exactly as today. isAvoidDomain is the SAME predicate- // computeProposalExecutionAwareness uses for its avoid list, so the gate and the- // reasoner-facing prompt agree on which domains are "chronically failing".- if (!isAvoidDomain(bucket)) return { handoff: true, reason: null };-- const cause = formatDominantFailureCause(bucket.failureSummary);- const reason = `${domain} hand-offs succeed ${bucket.successRate}% over ${bucket.completed} executed — filing for human review instead of auto-hand-off${cause ? ` (${cause})` : ''}`;- return { handoff: false, domain, rate: bucket.successRate, n: bucket.completed, cause, reason };-}--// The proposal scopes treated as LI "self-improve" work by the hard exclusion gate-// (#2824): the PortOS-only meta/self scopes. These are the proposals that improve LI /-// PortOS itself and execute under self-improve:* task types — the exact execution class-// whose chronic failure motivated the gate. Reuses PORTOS_ONLY_SCOPES as the single-// definition so "self-improve scope" can never drift from "the PortOS-only scopes".-export const SELF_IMPROVE_SCOPES = PORTOS_ONLY_SCOPES;--/**- * Deterministic HARD PRE-FILING EXCLUSION gate (#2824). Given a validated proposal,- * LI's own execution-health stats, and the app's outcome records, decides whether the- * proposal must be SUPPRESSED before it is ever filed — because LI's own execution is- * degraded and the proposal maps to work LI cannot see through. This is the SYSTEM-side- * enforcement of the exclusion the reasoner is merely WARNED about in the prompt notice- * (computeHardExclusionNotice): even when the reasoner "wants" to file, this gate drops- * the proposal to null.- *- * Pure + side-effect-free like the sibling compute* gates. Two independent exclusion- * rules, both ARMED only when LI's execution health is CONFIDENTLY below- * LI_HARD_GATE_EXECUTION_THRESHOLD (75%) — unknown or below-sample-floor health leaves- * the gate DISARMED, so a cold loop with no track record is never locked out:- * 1. Self-improve scope — any proposal in a SELF_IMPROVE_SCOPES scope (loop-meta /- * portos-self) is excluded regardless of domain. A degraded loop cannot repair- * itself; that work is deferred to a human.- * 2. Chronically-failing domain — a proposal whose OWN scope's hand-offs chronically- * fail (the SAME isAvoidDomain classifier the hand-off gate + reasoner avoid list- * use, so all three agree on which domains qualify) is excluded from FILING, not- * just from auto-hand-off.- *- * @param {object} args- * @param {object} args.proposal - the validated proposal ({ scope, ... }).- * @param {{ read: boolean, metrics: Object|null }|null} [args.liTaskStats] - readLiTaskMetrics output.- * @param {Array} [args.outcomes] - the app's li-outcomes records (for rule 2's domain lookup).- * @param {number} [args.now] - clock seam for the effective-rate window.- * @returns {{ excluded: boolean, reason: string|null, rule?: 'self-improve-scope'|'failing-domain' }}- */-export function computeHardExclusionGate({ proposal, liTaskStats = null, outcomes = [], now = Date.now() } = {}) {- if (!proposal || typeof proposal !== 'object') return { excluded: false, reason: null };-- // The gate is ARMED only on a confident read of degraded execution health. Unknown- // health (store unreadable / no runs) or a below-floor sample disarms it — the same- // 0-of-1-vs-0-of-N reasoning as LI_DEGRADED_MIN_SAMPLE. A healthy loop (>= 75%) files- // exactly as before this gate existed.- const health = computeLiExecutionHealth(liTaskStats, { now });- if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) {- return { excluded: false, reason: null };- }-- const scope = typeof proposal.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;- const healthClause = `LI execution health ${health.rate}% (< ${LI_HARD_GATE_EXECUTION_THRESHOLD}%)`;-- // Rule 1: self-improve scope — excluded wholesale while armed.- if (scope && SELF_IMPROVE_SCOPES.includes(scope)) {- return {- excluded: true,- rule: 'self-improve-scope',- reason: `${healthClause} — self-improve-scoped proposals (${scope}) are excluded while the loop's own runs are failing; a degraded loop cannot repair itself, so this is deferred to a human`- };- }-- // Rule 2: chronically-failing execution domain — same isAvoidDomain classifier the- // hand-off routing gate uses, so a domain on the reasoner's avoid list is the same- // set the gate blocks. Only reached for non-self-improve scopes with a scope present.- if (scope) {- const bucket = computeExecutionByDomain(outcomes)[scope];- if (isAvoidDomain(bucket)) {- const cause = formatDominantFailureCause(bucket.failureSummary);- return {- excluded: true,- rule: 'failing-domain',- reason: `${healthClause} and ${scope} hand-offs succeed only ${bucket.successRate}% over ${bucket.completed} executed — excluded from filing${cause ? ` (${cause})` : ''}`- };- }- }-- return { excluded: false, reason: null };-}--/**- * Render the reasoner-facing HARD EXCLUSION notice block (#2824). Computed from the- * SAME health + outcome inputs the enforcement gate (computeHardExclusionGate) reads,- * so the prompt's stated exclusions and what the gate actually suppresses can never- * disagree. Returns '' when the gate is DISARMED (health unknown, below sample floor,- * or at/above the threshold), so buildPrompt omits the block entirely on a healthy loop.- * Names both the self-improve scopes and any currently chronically-failing domain, and- * carries the explicit GATE CHECK step the reasoner must run before committing.- */-export function computeHardExclusionNotice({ liTaskStats = null, outcomes = [], now = Date.now() } = {}) {- const health = computeLiExecutionHealth(liTaskStats, { now });- if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) return '';-- const lines = [- `HARD EXCLUSION GATE ARMED — your execution health is ${health.rate}% (below ${LI_HARD_GATE_EXECUTION_THRESHOLD}%). The following work is EXCLUDED this run and will be dropped BEFORE filing even if your reasoning leads you to it:`,- `- Any self-improve-scoped proposal (${SELF_IMPROVE_SCOPES.join(', ')}). A degraded loop cannot repair itself — that work is deferred to a human.`- ];-- // Surface each currently chronically-failing domain by name so the reasoner can route- // around it explicitly — the same isAvoidDomain set rule 2 of the gate enforces. Skip- // any self-improve scope already named in the bullet above (gate rule 1 short-circuits- // rule 2 for those) so the notice never lists the same scope twice.- const byDomain = computeExecutionByDomain(outcomes);- const failing = Object.entries(byDomain)- .filter(([scope, bucket]) => isAvoidDomain(bucket) && !SELF_IMPROVE_SCOPES.includes(scope))- .map(([scope, bucket]) => `${clampScopeLabel(scope)} (${bucket.successRate}% over ${bucket.completed})`);- if (failing.length) {- lines.push(`- Any proposal in a chronically-failing execution domain: ${failing.join('; ')}.`);- }-- lines.push('', 'GATE CHECK: If your proposal maps to an excluded scope or domain above → return proposal: null. Do not reason past this gate.');- return lines.join('\n');-}--// Source keys that buildPrompt renders as their OWN dedicated block (with tailored-// guidance) instead of dumping into the generic "### <key>\n<value>" source list.-// Keeping them in one named set — rather than accreting `&& k !== 'x'` clauses on the-// filter — documents WHY these keys are special and gives the next dedicated-block-// signal a single edit point.-const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);--/**- * Build the JSON-only reasoning prompt for one app. Deterministic: given the- * gathered sources, open issues, and config, produces the exact string sent to- * the model. Meta/self scopes are only offered when the app is PortOS.- * `outcomesReport` (from computeOutcomesReport) is injected as a `liOutcomes`- * block with calibration guidance when non-empty (#2428). `selfEvalReport` (from- * computeSelfEvalSummary) is injected as a `liSelfEval` block the same way (#2700).- * `sources.scopeGuidance` (from computeScopeAwareness) is injected as a- * `liScopeAwareness` block the same way (#2760). `proposalExecutionReport` (from- * computeProposalExecutionAwareness) is injected as a `liProposalExecution` block —- * the TRUE per-proposal-domain execution record #2760 could only approximate (#2765).- * `crossReferenceReport` (from computeCrossReferenceAnalysis) is injected as a- * `liCrossReference` block that names domains LI proposes well but executes poorly (#2764 §3).- * `hardExclusionNotice` (from computeHardExclusionNotice, #2824) is injected as a- * prominent `liHardExclusions` block ABOVE the allowed scopes when LI's execution- * health is degraded — the reasoner-facing mirror of the deterministic filing gate.- * Finally, the static `liPlaybook` block (LI_PROPOSAL_PLAYBOOK, #2763) is ALWAYS- * appended: the a-priori scope/task-type/goal rule set LI needs from run one, before- * any per-app outcome data exists.- */-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '', crossReferenceReport = '', hardExclusionNotice = '' }) {- const allowed = (config.allowedScopes || []).filter(s =>- isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos })- );- const scopeLines = allowed.map(s => ` - ${s}`).join('\n');- // plannedWork renders as its OWN block (below) rather than inside the generic- // source list, so the cross-reference guidance is guaranteed to sit directly- // under the committed backlog it refers to instead of drifting to wherever- // object key order happens to put it.- const sourceBlocks = Object.entries(sources)- .filter(([k]) => !BESPOKE_SOURCE_BLOCK_KEYS.has(k))- .filter(([, v]) => typeof v === 'string' && v.trim())- .map(([k, v]) => `### ${k}\n${v.trim()}`)- .join('\n\n');- const openList = openIssues.length- ? openIssues.map(i => `- #${i.number ?? '?'} [${i.slug || extractSlugFromBody(i.body) || 'no-slug'}] ${i.title || ''}`).join('\n')- : '(none)';-- // Nudge a managed app with no own-performance signal (no METRICS.md gathered)- // toward adding one, so future runs can judge real performance. PortOS is exempt- // — it measures itself through cosMetrics. Also gate on the source being ENABLED:- // if the user deliberately turned appMetrics off, a METRICS.md may well exist, so- // "add a METRICS.md" would be a misleading (and possibly redundant) proposal.- const hasAppMetrics = Boolean(typeof sources.appMetrics === 'string' && sources.appMetrics.trim());- const appMetricsEnabled = config.sources?.appMetrics !== false;- const metricsGuidance = (!isPortos && appMetricsEnabled && !hasAppMetrics)- ? '\nThis app exposes no own-performance metrics yet (no METRICS.md). If you lack the data to judge how it is doing against its goals, a high-value app-data-gap proposal is to add a METRICS.md documenting how the app measures success — its user-success/KPI signals and where its production telemetry or data lives — so future runs can reason about real performance.\n'- : '';-- const handoffNote = config.handoff?.enabled- ? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first. Note: even a trivial+safe proposal is filed for a human (not auto-handed-off) when it falls in a domain where LI\'s own past hand-offs chronically fail, so prefer to narrow such a proposal to a slice an agent can actually finish.\n'- : '';-- // The committed backlog (#2698) + the instruction to check against it. Emitted- // whenever gatherPlannedWork produced ANY string — including its explicit- // "could not be read" marker, which must still reach the reasoner: silently- // dropping an unavailable read would look identical to "this app has nothing- // planned" and license a proposal straight into committed work.- const plannedWorkBlock = (typeof sources.plannedWork === 'string' && sources.plannedWork.trim())- ? `\n### plannedWork\n${sources.plannedWork.trim()}\n\n${PLANNED_WORK_GUIDANCE}\n`- : '';-- // Feedback loop (#2428): show the reasoner how its own past proposals fared so- // it can calibrate scope/merge-rate instead of proposing in a vacuum.- const outcomesBlock = (typeof outcomesReport === 'string' && outcomesReport.trim())- ? `\n### liOutcomes\n${outcomesReport.trim()}\n\nUse this data to calibrate your proposal: prefer scopes with higher merge rates, avoid patterns that were repeatedly rejected, and consider that lower-merge scopes may need more justification.\n`- : '';-- // Self-evaluation (#2700): the loop's own quality check BEFORE it files, so it- // can decline instead of learning only from a later rejection. Carries its own- // low-confidence / degraded-execution guidance (computeSelfEvalSummary), which is- // why no extra instruction sentence is appended here — the block is self-contained- // and its guidance is conditional on what the signals actually say.- const selfEvalBlock = (typeof selfEvalReport === 'string' && selfEvalReport.trim())- ? `\n### liSelfEval\n${selfEvalReport.trim()}\n\nWeigh this against the sources above before you commit to a proposal. Filing nothing (proposal: null) is a legitimate, and sometimes the correct, outcome — a marginal issue costs the user triage time and lowers your merge rate further.\n`- : '';-- // Scope-awareness (#2760): install-wide completion rates by CoS task TYPE — directional- // context for how reliably different KINDS of work get finished here. PortOS-only- // (codex P2): these rates are this install's own CoS execution history, meaningless to- // a managed app, so the block is gated on isPortos even if a managed app enabled the- // cosMetrics source. It is context, not a rule (codex P1): a proposal does not map 1:1- // onto a listed type, so treat a low-completion type as a reason for extra scrutiny /- // a narrower scope, not a hard veto.- const scopeGuidanceBlock = (isPortos && typeof sources.scopeGuidance === 'string' && sources.scopeGuidance.trim())- ? `\n### liScopeAwareness\n${sources.scopeGuidance.trim()}\n\nThese are per-task-type completion rates for THIS install — how reliably each KIND of work tends to get finished, not a per-proposal record (your proposals don't map 1:1 onto these types). Use it as directional context: a proposal whose implementation resembles a low-completion type deserves extra scrutiny or a narrower scope; high-completion kinds are safer bets. A low rate on self-improve:layered-intelligence is LI's OWN reasoning-run rate — a direct signal to propose conservatively. Where the liProposalExecution block below covers a domain, prefer it: it is a direct per-proposal record, whereas these buckets are only directional.\n`- : '';-- // Per-proposal-domain execution record (#2765): unlike liScopeAwareness above —- // which borrows install-wide per-task-TYPE rates a proposal only loosely maps onto —- // this keys on how LI's OWN proposals in each domain actually fared once handed off- // and executed. It carries NO "directional only" caveat because the mapping is real,- // so it is the authoritative avoid/prefer signal wherever it has data. The report is- // pre-gated on the outcomes source by the caller (built from the same records), so no- // isPortos re-check here — the block simply renders when execution history exists.- const proposalExecutionBlock = (typeof proposalExecutionReport === 'string' && proposalExecutionReport.trim())- ? `\n### liProposalExecution\n${proposalExecutionReport.trim()}\n\nThis is a DIRECT record of how LI's own proposals in each domain fared once implemented — not directional context. Favor domains LI executes reliably; for a low-execution domain, either narrow the proposal to a slice an agent can finish or justify why it is still the highest-value work despite the track record.\n`- : '';-- // Cross-reference (#2764 §3): the CONTRAST liOutcomes and liProposalExecution can't- // show on their own — a domain LI proposes well (merges) but executes poorly (its- // hand-offs fail with a named cause). It carries its own actionable guidance in the- // header, so no extra instruction sentence is appended. Gated on the outcomes source- // by the caller (built from the same records), so no isPortos re-check here.- const crossReferenceBlock = (typeof crossReferenceReport === 'string' && crossReferenceReport.trim())- ? `\n### liCrossReference\n${crossReferenceReport.trim()}\n`- : '';-- // Proposal Playbook (#2763): the STANDING, a-priori rule set — always rendered.- // Unlike the data blocks above (which appear only once enough per-app outcome data- // accumulates), the playbook is the guidance LI needs from run one, when it would- // otherwise be proposing blind. It sits last so it is the freshest instruction- // before the JSON contract, and its guidance sentence defers to any live data block- // above that has real numbers contradicting a general rule.- const playbookBlock = LI_PROPOSAL_PLAYBOOK- ? `\n### liPlaybook\n${LI_PROPOSAL_PLAYBOOK}\n\n${LI_PLAYBOOK_GUIDANCE}\n`- : '';-- // Hard exclusion gate (#2824): rendered ABOVE the allowed scopes and sources as a- // hard constraint so the reasoner sees what is off-limits before it picks a scope.- // Non-empty only when the deterministic filing gate is armed (execution health- // degraded), so a healthy loop's prompt is unchanged. Even if the reasoner reasons- // past this, computeHardExclusionGate drops the proposal before it is filed.- const hardExclusionBlock = (typeof hardExclusionNotice === 'string' && hardExclusionNotice.trim())- ? `\n### liHardExclusions\n${hardExclusionNotice.trim()}\n`- : '';-- return `You are the Layered Intelligence reasoner for the app "${app.name}". Your job is to evaluate how THIS app is performing against its OWN goals and purpose${isPortos ? '' : ', not how well PortOS\'s tooling manages it'}. Decide the SINGLE highest-value improvement to propose this run (signal, not noise), grounded in the app's own goals and its own performance metrics (user success, KPIs, production telemetry). You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.-${handoffNote}${metricsGuidance}${hardExclusionBlock}-Rules & guidance from the operator:-${config.rules?.trim() || '(none)'}--Allowed proposal scopes (you MUST pick one of these for any proposal):-${scopeLines || ' (none — return proposal: null)'}-${isPortos ? '' : 'Note: meta/self scopes are unavailable on this app; frame any data need as an "app-data-gap" against this app.\n'}-Already-open tracked issues (DO NOT duplicate these — reuse their slug only if genuinely the same work):-${openList}--Gathered sources:-${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}-${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${scopeGuidanceBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}-Respond with JSON only (no markdown fences):-{- "analysis": "brief reasoning summary",- "proposal": { // null if nothing worth filing this run- "scope": "<one allowed scope>",- "slug": "kebab-stable-id",- "title": "short imperative title",- "body": "markdown detail for the coding agent",- "value": "why this is the single highest-value item now",- "complexity": "trivial | moderate | complex", // honest effort/risk estimate- "safe": false // true ONLY if a coding agent could implement it end-to-end with no regression/data-loss risk- },- "pause": { // null if not pausing- "blockOnIssue": "this" or <existing issue number>,- "reason": "why the loop should pause on this app until resolved"- }-}`;-}--// ----------------------------------------------------------------------------// I/O layer — gather + filers. Injectable deps keep these testable.-// -----------------------------------------------------------------------------/** Run a CLI, resolving `{ code, stdout, stderr }` (never rejects). */-function runCli(cmd, args, options = {}) {- return new Promise((resolve) => {- const child = spawn(cmd, args, { shell: false, windowsHide: true, ...options });- let stdout = '', stderr = '';- child.stdout?.on('data', d => { stdout += d.toString(); });- child.stderr?.on('data', d => { stderr += d.toString(); });- child.on('close', code => resolve({ code, stdout, stderr }));- child.on('error', err => resolve({ code: -1, stdout: '', stderr: err.message }));- });-}--/**- * Why a planned-work read came back empty-handed. Rendered INSTEAD of a listing so- * a failed tracker read can never be mistaken for "this app has nothing planned" —- * the two are opposite instructions to the reasoner (be conservative vs. the field- * is wide open), and collapsing them is exactly the failure the sentinel rule in- * CLAUDE.md exists to prevent.- */-export function plannedWorkUnavailable(why) {- return `${PLANNED_WORK_UNAVAILABLE_PREFIX} (${why}). Do NOT treat this as "nothing is planned" — this app may well have a committed backlog that simply could not be listed this run. Be conservative: prefer proposal: null over filing work that might already be in scope.`;-}--/**- * Whether a gathered plannedWork string is an actual LISTING of committed work —- * i.e. something the reasoner can be told to go read — as opposed to one of the- * two sentinels ("nothing is planned" / "could not be read"). Both sentinels are- * meaningful in the prompt and still render, but neither is a backlog: telling- * the reasoner its proposals "may be overlapping with committed work — review the- * plannedWork source above" directly beneath a block stating no planned work- * exists is a contradiction that just biases it toward filing nothing.- */-export function hasPlannedWorkListing(plannedWork) {- if (typeof plannedWork !== 'string') return false;- const text = plannedWork.trim();- if (!text || text === PLANNED_WORK_NONE) return false;- return !text.startsWith(PLANNED_WORK_UNAVAILABLE_PREFIX);-}--/**- * Render a planned-work item list into the prompt block. Pure.- *- * Reports the count of everything it was HANDED even when the rendered list is- * truncated to `maxItems`, so the reasoner knows it is seeing the top of a larger- * backlog rather than all of it — 15 shown out of 100 must not read as "there are- * only 15". Note the caller's own read is capped too (the tracker lists cap at- * 100), so on a very large backlog this count is itself a floor, not a census.- */-export function formatPlannedWork(items, { maxItems = PLANNED_WORK_MAX_ITEMS, maxChars = PLANNED_WORK_MAX_CHARS } = {}) {- const list = (Array.isArray(items) ? items : []).filter(i => i && typeof i === 'object' && (i.title || i.number != null));- if (list.length === 0) return PLANNED_WORK_NONE;- const top = list.slice(0, maxItems);- const lines = top.map(i => {- const ref = i.number != null ? `#${i.number} ` : '';- const meta = [- i.priority ? `priority: ${i.priority}` : null,- Array.isArray(i.labels) && i.labels.length ? `labels: ${i.labels.join(', ')}` : null- ].filter(Boolean).join('; ');- return `- ${ref}${(i.title || '').trim()}${meta ? ` (${meta})` : ''}`;- });- const header = list.length > top.length- ? `${list.length} items of actively-planned work the user has already committed to (showing the top ${top.length}):`- : `${list.length} item(s) of actively-planned work the user has already committed to:`;- return [header, ...lines].join('\n').slice(0, maxChars);-}--/**- * Extract a PLAN.md's UNCHECKED (`- [ ]`) items — the plan tracker's equivalent of- * a `plan`-labeled issue. A `- [x]` item is finished work, not committed-and-- * pending, so it is excluded: proposing something already done is a different- * (and already-handled) problem than proposing something already scheduled.- */-export function extractPlannedPlanItems(planContent) {- if (typeof planContent !== 'string') return [];- const items = [];- const re = /^[ \t]*[-*][ \t]+\[ \][ \t]*(\S.*)$/gm;- let m;- while ((m = re.exec(planContent))) {- const title = m[1].replace(/\s+/g, ' ').trim();- if (title) items.push({ number: null, title: title.slice(0, 200), labels: [], priority: null });- }- return items;-}--/**- * Gather the app's actively-planned work — the backlog the user has ALREADY- * committed to — so the reasoner can cross-reference a proposal against it before- * filing (#2698). A deterministic tracker read: files + `gh`/`glab`/Jira REST, and- * NO LLM call (the no-cold-bootstrap rule).- *- * Returns a prompt-ready string, or `null` when the source does not apply at all- * (an unresolvable tracker: no forge CLI, no Jira coords, no repo path) — three- * distinct states, never collapsed:- * - `null` → nothing to say; buildPrompt omits the block- * - `plannedWorkUnavailable()` → the read FAILED; be conservative- * - a listing / PLANNED_WORK_NONE → the read SUCCEEDED and is trustworthy- * (a plan-tracked app with no PLAN.md at all is a real PLANNED_WORK_NONE)- *- * Deps are injectable so tests drive every branch without a live tracker.- */-export async function gatherPlannedWork({- filer,- forgeCli,- cwd,- jira,- listForge = listForgeIssues,- listJira = listJiraIssues,- readFileFn = tryReadFile-} = {}) {- if (filer === 'forge' && forgeCli && cwd) {- const { ok, issues } = await listForge({ cli: forgeCli, cwd, label: PLANNED_WORK_LABEL, state: 'open' });- if (!ok) return plannedWorkUnavailable(`the ${forgeCli} issue list failed`);- // gh honors --state open, but glab's label list can still surface a closed- // issue depending on version — re-filter so a done item never reads as pending.- const open = issues.filter(i => i.state === 'open');- return formatPlannedWork(open.map(i => ({- number: i.number,- title: i.title,- labels: i.labels || [],- priority: extractIssuePriority(i.labels)- })));- }-- if (filer === 'jira' && jira?.instanceId && jira?.projectKey) {- const { ok, issues } = await listJira({- instanceId: jira.instanceId,- projectKey: jira.projectKey,- jql: plannedWorkJql(jira.projectKey),- // Jira's priority field is not in searchIssues' default `fields` set — ask- // for it explicitly, or every item would report a null priority.- searchOptions: { fields: 'summary,status,labels,updated,description,resolutiondate,priority' }- });- if (!ok) return plannedWorkUnavailable('the Jira search failed');- const open = issues.filter(i => i.state === 'open');- return formatPlannedWork(open.map(i => ({- number: i.number,- title: i.title,- labels: i.labels || [],- // Prefer Jira's real priority field; fall back to a priority-ish label.- priority: i.priority || extractIssuePriority(i.labels)- })));- }-- if (filer === 'plan' && cwd) {- const planPath = join(cwd, 'PLAN.md');- // No PLAN.md at all is a real "nothing is planned" for a plan-tracked app —- // distinguish it from a PLAN.md that EXISTS but could not be read (a genuine- // failure), which tryReadFile's null would otherwise conflate.- if (!existsSync(planPath)) return PLANNED_WORK_NONE;- const content = await readFileFn(planPath);- if (typeof content !== 'string') return plannedWorkUnavailable('PLAN.md exists but could not be read');- return formatPlannedWork(extractPlannedPlanItems(content));- }-- return null;-}--/**- * Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.- * Deterministic reads only (files + CoS metric JSON + tracker lists); NO LLM calls.- * Missing files degrade to omitted keys, never throws. `openIssues` is gathered- * separately by the handler (it shells out to the forge). `tracker`- * (`{ filer, forgeCli, cwd, jira }`, resolved by the caller) enables the- * plannedWork source — absent, that source is simply skipped.- */-export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShellSources, tracker = null, isPortos = false } = {}) {- const out = {};- const src = config.sources || {};- const repo = app.repoPath;-- // Resolve the install-level shell-trust opt-in lazily and once — only when a- // `cmd` source is actually present — so apps with no shell sources never read- // settings. Injected value (tests) wins; otherwise fall back to settings.json.- let trustShell = trustShellSources;- const resolveTrustShell = async () => {- if (trustShell === undefined) trustShell = await getTrustShellSources();- return trustShell;- };-- if (src.goals && repo) {- const goals = await tryReadFile(join(repo, 'GOALS.md'));- if (goals) out.goals = goals.slice(0, 8000);- }- if (src.appMetrics && repo) {- // The app's own success/performance metrics doc (the METRICS.md convention,- // see docs/METRICS.md) — where a managed app records what "performing well"- // means. Absent → omitted (the reasoner may then propose adding one).- const metrics = await tryReadFile(join(repo, 'METRICS.md'));- if (metrics) out.appMetrics = metrics.slice(0, 8000);- }- if (src.planMd && repo) {- const plan = await tryReadFile(join(repo, 'PLAN.md'));- if (plan) out.planMd = plan.slice(0, 8000);- }- if (src.healthReport && repo) {- const health = await tryReadFile(join(repo, 'HEALTH_REPORT.md'));- if (health) out.healthReport = health.slice(0, 8000);- }- if (src.plannedWork && tracker) {- // The committed backlog (#2698). Unlike the file sources above, an EMPTY or- // FAILED result still emits a key — each renders a distinct sentence, and- // both are meaningful instructions to the reasoner (see gatherPlannedWork).- const planned = await gatherPlannedWork(tracker);- if (planned) out.plannedWork = planned.slice(0, PLANNED_WORK_MAX_CHARS);- }- if (src.cosMetrics) {- // This install's own autonomous-agent run stats (per task type), NOT scoped to- // the app being analyzed — see the default-config note for the PortOS-vs-managed- // rationale (default-off for managed apps).- const learning = await readJSONFile(join(cosPath, 'learning.json'), null);- if (learning?.byTaskType) {- // Surface BOTH the lifetime rate (the cumulative dashboard/telemetry truth)- // AND a recency-windowed rate (issue #2460) per task type, labeled distinctly- // so the reasoner doesn't conflate them. The windowed rate lets a- // since-resolved failure burst age out of the "is work needed" signal instead- // of permanently depressing it; `recentSuccessRate` is null when there are no- // in-window runs, in which case the reasoner leans on the lifetime rate.- // Note the intentional rename: computeWindowedStats' internal `windowed*`- // fields are surfaced to the reasoner as `recent*` (reads more naturally in- // the prompt context) — same concept, deliberately different label here.- const summary = {};- for (const [type, m] of Object.entries(learning.byTaskType)) {- const windowed = computeWindowedStats(m?.recentOutcomes);- summary[type] = {- lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,- lifetimeCompleted: m?.completed || 0,- recentSuccessRate: windowed.windowedSuccessRate,- recentCompleted: windowed.windowedCompleted,- avgDurationMs: m?.avgDurationMs || 0- };- }- out.cosMetrics = JSON.stringify(summary).slice(0, 4000);- // Scope-awareness guidance (#2760): a deterministic low/high-completion split- // derived from the SAME per-type rates above, so the reasoner gets an interpreted- // signal alongside the raw JSON instead of being asked to spot the pattern itself.- // Rendered as its own prompt block (see buildPrompt). Gated on isPortos (codex P2):- // these are THIS install's own CoS completion rates, meaningless to a managed app —- // and a managed app CAN enable the cosMetrics source, so the cosMetrics toggle- // alone is not the PortOS boundary. buildPrompt re-checks isPortos as defense in- // depth; deriving it here only for PortOS also avoids the wasted work.- if (isPortos) {- const scopeGuidance = computeScopeAwareness({ metricsByType: summary });- if (scopeGuidance) out.scopeGuidance = scopeGuidance;- }- }- }- for (const custom of src.custom || []) {- const key = customSourceKey(custom);- if (!key) continue;- if (custom.type === 'file' && typeof custom.ref === 'string' && repo) {- const safe = await confineToRepo(repo, custom.ref);- if (!safe) {- console.warn(`⚠️ Layered Intelligence: custom source "${custom.ref}" escapes repo — skipped`);- continue;- }- const content = await tryReadFile(safe);- if (content) out[key] = content.slice(0, 8000);- } else if (custom.type === 'http' && typeof custom.url === 'string') {- const content = await fetchHttpSource(custom.url);- if (content) out[key] = content.slice(0, 8000);- } else if (custom.type === 'cmd' && typeof custom.cmd === 'string' && repo) {- const content = await runShellCommand(custom.cmd, { cwd: repo, trustShellSources: await resolveTrustShell() });- if (content) out[key] = content.slice(0, 8000);- }- }- return out;-}--/**- * Read the LI loop's OWN agent-run metrics out of the CoS learning store (#2700).- * Deterministic file read; no LLM call. Feeds computeSelfEvalSummary's execution-- * health signal.- *- * Returns a discriminated result rather than a bare bucket-or-null, because the two- * empty cases are NOT the same fact and the reasoner is told them differently:- * `{ read: false, metrics: null }` — the store is missing/unreadable/malformed:- * we do not know how LI's runs are going.- * `{ read: true, metrics: null }` — the store is fine, LI has simply never run.- * `{ read: true, metrics: {...} }` — real history.- * Collapsing these to one `null` would let "cannot read the store" masquerade as- * "healthy loop with no history" (or vice versa) — the sentinel rule.- */-export async function readLiTaskMetrics({ cosPath = PATHS.cos } = {}) {- const file = join(cosPath, 'learning.json');- // An ABSENT store is a fresh install, not a broken read: learning.json is created- // lazily on the first recorded task outcome. readJSONFile returns its default for- // ENOENT, I/O errors, and parse failures ALIKE, so leaning on it alone would tell- // every fresh install "your learning store could not be read" when the truth is- // "nothing has run here yet" — the exact conflation this function exists to- // prevent, just inverted. Check existence first so the two stay distinct.- if (!existsSync(file)) return { read: true, metrics: null };- const learning = await readJSONFile(file, null);- const byTaskType = learning?.byTaskType;- if (!byTaskType || typeof byTaskType !== 'object' || Array.isArray(byTaskType)) {- return { read: false, metrics: null };- }- const bucket = byTaskType[LI_TASK_TYPE];- return {- read: true,- metrics: (bucket && typeof bucket === 'object' && !Array.isArray(bucket)) ? bucket : null- };-}--/**- * Stable map key for a custom source. Namespaced by type so a `file` ref and an- * `http` url that share a string can't collide, and so the prompt's source block- * labels are self-describing. Returns null for a malformed/unknown source.- */-export function customSourceKey(custom) {- if (!custom || typeof custom !== 'object') return null;- if (custom.type === 'file' && custom.ref) return `custom:${custom.ref}`;- if (custom.type === 'http' && custom.url) return `custom:http:${custom.url}`;- if (custom.type === 'cmd' && custom.cmd) return `custom:cmd:${custom.cmd}`;- return null;-}--/**- * Fetch an http(s) custom source for the loop's prompt. Deterministic read, no- * LLM. Rejects any non-http(s) scheme (defense in depth over the Zod refine),- * bounds the request with a 10s timeout, and returns null on any failure so a- * dead URL just omits the key rather than throwing.- *- * SSRF-guarded via `fetchPublicText` (default posture): loopback, link-local,- * and the cloud-metadata endpoint (127.0.0.1, 169.254.169.254,- * metadata.google.internal, ::1) are blocked so a hand-edited/hostile config- * can't exfiltrate them into the reasoner prompt, and redirects are revalidated- * against the same gate. LAN/private hosts (Tailscale peers, a home wiki) stay- * ALLOWED intentionally — PortOS is a single-user tool where a custom source- * legitimately points at the home network, and the URL is operator-configured.- * `throwOnUnsafe: false` makes a blocked host omit the key like any other dead- * URL instead of bubbling a 400. `fetchText` is injectable for tests.- */-export async function fetchHttpSource(url, { timeoutMs = 10_000, fetchText = fetchPublicText } = {}) {- if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null;- const text = await fetchText(url, { timeoutMs, throwOnUnsafe: false }).catch(() => null);- return text || null;-}--/**- * THREAT MODEL — a `cmd` custom source is attacker-reachable persistent config.- *- * The `sources.custom` array lives in each app's stored `layeredIntelligence`- * config, written through the validated `PUT /api/apps/:id` route. A `cmd` entry- * is executed here on the Layered Intelligence SCHEDULE (Engine-B autonomous job),- * with the PortOS process's own privileges and cwd = the app repo. So any path- * that can land a string in that config (a hand-edited config, a hostile sync- * payload, a future config-writing feature, an XSS-driven same-origin POST) gets- * *persistent, unattended* code execution — not a one-shot the operator watched.- *- * Historically this ran the full command string with `shell: true`, capped only- * by length + a 15s timeout. That is arbitrary RCE: `; rm -rf ~`, `$(curl … | sh)`,- * pipes to `sh`, etc. all execute. Issue #2515.- *- * Defense: by default we DENY the shell. The command is parsed and checked- * against the shared binary allowlist (`validateCommand` in commandSecurity.js —- * same gate the manual command runner uses), which rejects shell metacharacters- * (`;|&$(){}` …) and any binary not on the allowlist, then we spawn the base- * binary with parsed args and `shell: false` — so no shell ever interprets the- * string. A non-allowlisted / metacharacter command is dropped (key omitted) with- * a warning, exactly like any other failed source read.- *- * Escape hatch: an operator who genuinely needs a pipeline (`git log … | head`)- * can set the install-level `settings.layeredIntelligence.trustShellSources`- * flag, which restores the full `shell: true` behavior for THIS install only.- * It is an explicit, install-wide opt-in — off by default — so a fresh install- * (or a synced-in app config) can never execute an un-allowlisted command.- *- * `exec` is injectable for tests; `trustShellSources` is resolved by the caller- * (`gatherSources`) from install settings and threaded in.- *- * Returns null on rejection / non-zero exit / timeout / no output so a failing or- * denied command just omits the source key rather than throwing.- */-export async function runShellCommand(cmd, { cwd, timeoutMs = 15_000, exec = bufferedSpawn, trustShellSources = false } = {}) {- if (typeof cmd !== 'string' || !cmd.trim()) return null;- if (trustShellSources) {- // Operator has explicitly opted this install into full-shell custom sources.- const { code, stdout } = await exec(cmd, [], { cwd, timeoutMs, shell: true });- if (code !== 0) return null;- return (stdout || '').trim() || null;- }- const check = validateCommand(cmd);- if (!check.valid) {- console.warn(`⚠️ Layered Intelligence: custom cmd source "${cmd}" rejected — ${check.error} (enable settings.layeredIntelligence.trustShellSources to allow arbitrary shell commands)`);- return null;- }- const { code, stdout } = await exec(check.baseCommand, check.args, { cwd, timeoutMs, shell: false });- if (code !== 0) return null;- return (stdout || '').trim() || null;-}--/**- * Resolve the install-level "trust shell sources" opt-in from settings.json.- * `null`/absent/non-true all read as OFF (the safe default) — only an explicit- * `true` unlocks full-shell custom `cmd` sources. Injectable read for tests.- */-export async function getTrustShellSources(read = getSettings) {- const settings = await read();- return settings?.layeredIntelligence?.trustShellSources === true;-}--/**- * Confine a custom file `ref` to within `repo` so a hostile/hand-edited config- * can't read arbitrary files into the LLM prompt. Returns the safe absolute path,- * or null when it escapes. Guards BOTH lexical traversal (`..` / absolute) AND- * symlink escape — a symlink inside the repo pointing outside is resolved via- * realpath and rejected. Missing files return null (nothing to read).- */-export async function confineToRepo(repo, ref) {- const abs = resolve(repo, ref);- const rel = relative(repo, abs);- if (rel.startsWith('..') || isAbsolute(rel)) return null;- // Resolve symlinks on both sides; a link inside the repo that points outside- // is caught here (lexical check above only sees the link's own path).- const realRepo = await realpath(repo).catch(() => null);- const realAbs = await realpath(abs).catch(() => null);- if (!realRepo || !realAbs) return null;- const realRel = relative(realRepo, realAbs);- if (realRel.startsWith('..') || isAbsolute(realRel)) return null;- return realAbs;-}--/** Lazily resolve the default embedder so the pure module doesn't statically pull- * in the embeddings/settings/provider graph (matches the handler's dynamic-import- * pattern for heavy deps). Only reached in production — tests inject `embed`. */-async function defaultEmbed(text) {- const { embedText } = await import('./embeddings.js');- return embedText(text);-}--/**- * SEMANTIC dedup guard — the embedding-similarity layer ON TOP OF the exact- * slug/label dedup (`isProposalDuplicate`). Catches a proposal that describes the- * same work as an existing issue but was worded differently (so its slug differs).- * Runs only AFTER slug dedup passes, so it's a best-effort extra catch.- *- * Returns `{ available, duplicate, match }`:- * - `available:false` when semantic dedup couldn't run (no embeddable candidates,- * or the embeddings provider is off / the proposal embed failed). This is a- * SENTINEL, distinct from `available:true, duplicate:false` ("checked, no- * near-dup"): the handler treats unavailable as "proceed to file" because slug- * dedup already guarded the exact case — losing the semantic catch just- * restores pre-feature behavior, it never files a slug-duplicate.- * - `duplicate:true` with `match` = the highest-scoring near-duplicate issue.- *- * No cold-bootstrap risk: `embed` degrades to `{ skipped:true }` when no- * embeddings provider is configured, and this only runs inside the user-enabled- * scheduled sweep. `embed` is injectable for tests.- */-export async function checkSemanticDuplicate({ proposal, existingIssues = [], now = Date.now(), embed = defaultEmbed, threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {- const unavailable = { available: false, duplicate: false, match: null };- if (!proposal || typeof proposal !== 'object') return unavailable;-- // Only issues still within the dedup window with SOMETHING to embed are worth- // comparing; a plan-tracked slug-only issue (no title/body) can't be embedded.- const candidates = existingIssues- .filter(i => isIssueWithinDedupWindow(i, now) && (i.body || i.title))- .slice(0, SEMANTIC_DEDUP_MAX_CANDIDATES);- if (candidates.length === 0) return unavailable;-- // A failing embed (transient provider blip, malformed response) must degrade to- // the available:false sentinel — NOT reject through processApp and mark the- // whole app run 'error'. Deferring the call into a promise chain then catching- // absorbs BOTH an async rejection AND a synchronous throw from the (injectable)- // embedder, mirroring this file's fetchHttpSource / jira-search failure idiom- // (no non-boundary try/catch).- const safeEmbed = (text) => Promise.resolve().then(() => embed(text)).catch(() => null);-- const proposalRes = await safeEmbed(issueEmbedSeed({ title: proposal.title, body: proposal.body }));- if (!proposalRes?.success || !Array.isArray(proposalRes.embedding)) return unavailable;-- const embedded = [];- for (const c of candidates) {- const res = await safeEmbed(issueEmbedSeed({ title: c.title, body: c.body }));- if (res?.success && Array.isArray(res.embedding)) {- embedded.push({ slug: c.slug || null, number: c.number ?? null, title: c.title || '', embedding: res.embedding });- }- }- if (embedded.length === 0) return unavailable;-- const match = findSemanticDuplicate({ proposalEmbedding: proposalRes.embedding, candidates: embedded, threshold });- return { available: true, duplicate: !!match, match };-}--/**- * Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`- * (and `closed`/`locked`); GitHub reports `open`/`closed`. Anything that isn't a- * recognized closed/locked state is treated as open so dedup + park don't miss a- * GitLab-`opened` issue. (`merged` never applies to issues.)- */-export function normalizeIssueState(state) {- const s = (state || '').toLowerCase();- if (s === 'closed' || s === 'locked') return 'closed';- return 'open';-}--/**- * Normalize a forge issue's labels to a plain `string[]`. gh reports objects- * (`[{ name, color, … }]`); glab reports bare strings. Anything unrecognized- * drops out rather than rendering `[object Object]` into the reasoner's prompt.- */-export function normalizeIssueLabels(raw) {- if (!Array.isArray(raw)) return [];- return raw- .map(l => (typeof l === 'string' ? l : l?.name))- .filter(l => typeof l === 'string' && l.trim())- .map(l => l.trim());-}--/**- * Best-effort priority read from an issue's labels — there is no cross-forge- * priority field, so the common label conventions are matched instead:- * `priority: high` / `priority/high`, `P0`–`P4`, and a bare- * `critical|urgent|high|medium|low` (optionally suffixed `-priority`).- *- * Returns null when no label looks like a priority. Null means "this issue- * carries no priority label", NOT "priority zero" — the renderer omits the field- * entirely rather than inventing a default the tracker never asserted.- */-export function extractIssuePriority(labels = []) {- const re = /^(?:priority[:/\s-]+(.+)|p([0-4])|(critical|urgent|high|medium|low)(?:[\s-]priority)?)$/i;- for (const label of normalizeIssueLabels(labels)) {- const m = label.match(re);- if (!m) continue;- const value = m[1] ?? (m[2] != null ? `p${m[2]}` : m[3]);- if (typeof value === 'string' && value.trim()) return value.trim().toLowerCase();- }- return null;-}--/**- * List issues on a forge. Defaults to the layered-intelligence set (open +- * recently closed) for the reasoner + dedup guard; `label`/`state` are- * parameterized so the plannedWork source (#2698) can reuse the exact same- * parse/normalize path for the `plan`-labeled committed backlog.- *- * Returns `{ ok, issues }` — `ok:false` means the tracker read FAILED (CLI error- * or unparseable output), which is NOT the same as "no existing issues" (`ok:true,- * issues:[]`). The handler must NOT file when the read failed, or a transient- * `gh` blip would defeat dedup and file a duplicate (CLAUDE.md sentinel rule).- */-export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state = 'all', exec = runCli } = {}) {- // glab lists open issues by default and needs `--all` to widen to every state;- // gh takes the state explicitly.- const args = cli === 'glab'- ? ['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100', '-F', 'json']- : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences'];- const { code, stdout } = await exec(cli, args, { cwd, env });- if (code !== 0) return { ok: false, issues: [] };- if (!stdout.trim()) return { ok: true, issues: [] };- const parsed = safeJSONParse(stdout, null, { logError: false });- if (!Array.isArray(parsed)) return { ok: false, issues: [] };- return {- ok: true,- issues: parsed.map(i => ({- number: i.number ?? i.iid ?? null,- title: i.title || '',- body: i.body || i.description || '',- state: normalizeIssueState(i.state),- // GitHub-only: 'completed' | 'not_planned' | 'reopened'. glab omits it, so- // deriveOutcome falls back to treating any closed issue as merged.- stateReason: i.stateReason || i.state_reason || null,- closedAt: i.closedAt || i.closed_at || null,- // gh reports `url`; glab reports `web_url`. Null when neither is present so- // the overview's proposal links degrade to a plain count rather than a- // dead href.- url: i.url || i.web_url || null,- labels: normalizeIssueLabels(i.labels),- // The rejection classifier's last-resort signal (#2748): the prose a human- // left when declining, for a close with no matching label/close-reason. gh- // returns `comments` in the same batched list call (no extra fetch); glab's- // `-F json` omits them, so its rows carry null and fall through to label/- // stateReason only (tracked in the issue's Remaining).- closingComment: extractClosingComment(i.comments),- // The implementing-PR handle (#2748, deliverable 2): gh reports every PR that- // closes/references this issue in `closedByPullRequestsReferences`. Additive- // and null-defaulted — glab's `-F json` omits it, so its rows carry null and- // fall through to the label/comment signals, and the reconciler only reads a- // PR's state when it holds a number here. Scoped to the issue's own repo (parsed- // from its url) so a cross-repo closing PR can't resolve to the wrong number.- implementingPr: extractImplementingPr(i.closedByPullRequestsReferences, repoSlugFromUrl(i.url || i.web_url)),- slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')- }))- };-}--/**- * Parse an `owner/repo` slug (lower-cased for case-insensitive compare) from a GitHub- * issue/PR URL — `https://HOST/owner/repo/(issues|pull)/N` — host-agnostic so it works- * on github.com and Enterprise. Returns null when the shape doesn't match.- */-export function repoSlugFromUrl(url) {- if (typeof url !== 'string') return null;- const m = url.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/(?:issues|pull)\/\d+/);- return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;-}--/**- * The `owner/repo` a `closedByPullRequestsReferences` entry belongs to — from its- * structured `repository { owner { login }, name }`, falling back to parsing its `url`.- * Null when neither is present. Lower-cased to match `repoSlugFromUrl`.- */-function refRepoSlug(ref) {- const owner = ref?.repository?.owner?.login;- const name = ref?.repository?.name;- if (typeof owner === 'string' && typeof name === 'string') return `${owner}/${name}`.toLowerCase();- return repoSlugFromUrl(ref?.url);-}--/**- * The number of the PR that implements a proposal, from gh's- * `closedByPullRequestsReferences` (#2748, deliverable 2). Takes the LAST reference —- * the most recent PR linked to the issue — and returns its number, or null when there- * is none (glab, or an issue closed by hand). Pure.- *- * `selfRepo` (the issue's own `owner/repo`) scopes the match: the reconciler later runs- * `gh pr view <number>` in the issue's checkout, so a reference from a DIFFERENT repo- * (a cross-repo/fork PR that closed the issue) would resolve to the wrong PR number in- * cwd's repo — or none — and mis-diagnose the rejection. So a ref whose repo is known- * and differs from `selfRepo` is skipped. When `selfRepo` is unknown or a ref carries- * no repo, it is accepted (same-repo is the overwhelmingly common case for an LI- * proposal implemented in its own repo), preserving prior behavior.- */-export function extractImplementingPr(refs, selfRepo = null) {- if (!Array.isArray(refs)) return null;- const self = typeof selfRepo === 'string' ? selfRepo.toLowerCase() : null;- for (let i = refs.length - 1; i >= 0; i -= 1) {- const n = refs[i]?.number;- if (!Number.isInteger(n) || n <= 0) continue;- const refRepo = refRepoSlug(refs[i]);- if (self && refRepo && refRepo !== self) continue;- return n;- }- return null;-}--/**- * Read the merge state + check rollup of an implementing PR (#2748, deliverable 2),- * so the rejection reconciler can classify `merge-conflict` / `validation-failed`.- * gh-only (glab carries no PR handle) and bounded by the caller to the small set of- * non-merged proposals that both hold a PR ref and were left undiagnosed by the free- * signals — this is the ONE tracker fetch classification adds, and it never runs at- * boot (only the scheduler-tick reconcile, gated behind `sources.outcomes`).- * Returns `{ state, mergeStateStatus, statusCheckRollup }`, or null on any failure- * (a null read simply leaves the proposal on its existing, honest fallback reason).- */-export async function readImplementingPrState({ cli, cwd, env, number, exec = runCli } = {}) {- if (cli !== 'gh' || !Number.isInteger(number)) return null;- const { code, stdout } = await exec(cli, ['pr', 'view', String(number), '--json', 'state,mergeStateStatus,statusCheckRollup'], { cwd, env });- if (code !== 0 || !stdout.trim()) return null;- const parsed = safeJSONParse(stdout, null, { logError: false });- if (!parsed || typeof parsed !== 'object') return null;- return {- state: parsed.state ?? null,- mergeStateStatus: parsed.mergeStateStatus ?? null,- statusCheckRollup: Array.isArray(parsed.statusCheckRollup) ? parsed.statusCheckRollup : []- };-}--/**- * The rationale a human left when closing a proposal, for the rejection classifier- * (#2748). gh returns issue comments oldest-first; the LAST non-empty one sits- * closest to the close, so it carries the decline reason in the common case.- * Returns null for an issue closed with no comment — there is nothing to classify.- */-export function extractClosingComment(comments) {- if (!Array.isArray(comments)) return null;- for (let i = comments.length - 1; i >= 0; i -= 1) {- const body = comments[i]?.body;- if (typeof body === 'string' && body.trim()) return body;- }- return null;-}--/**- * List OPEN blocking-labeled issues for the app (park check). Returns- * `{ ok, issues }` with the same failed-vs-empty distinction as listForgeIssues.- */-export async function listBlockingIssues({ cli, cwd, env, exec = runCli } = {}) {- const args = cli === 'glab'- ? ['issue', 'list', '--label', LI_BLOCKING_LABEL, '-P', '100', '-F', 'json']- : ['issue', 'list', '--label', LI_BLOCKING_LABEL, '--state', 'open', '--limit', '100', '--json', 'number,title,state'];- const { code, stdout } = await exec(cli, args, { cwd, env });- if (code !== 0) return { ok: false, issues: [] };- if (!stdout.trim()) return { ok: true, issues: [] };- const parsed = safeJSONParse(stdout, null, { logError: false });- if (!Array.isArray(parsed)) return { ok: false, issues: [] };- return {- ok: true,- issues: parsed.map(i => ({- number: i.number ?? i.iid ?? null,- title: i.title || '',- state: normalizeIssueState(i.state)- }))- };-}--/**- * Ensure the layered-intelligence labels exist before the first `issue create`- * (gh/glab both fail creating an issue with a non-existent label). Idempotent —- * `--force` (gh) / re-create (glab) is a no-op when the label already exists.- */-export async function ensureForgeLabels({ cli, cwd, env, exec = runCli } = {}) {- const labels = [- { name: LI_LABEL, color: '1d76db', desc: 'Filed by the Layered Intelligence loop' },- { name: LI_BLOCKING_LABEL, color: 'b60205', desc: 'Layered Intelligence loop is paused on this issue' }- ];- for (const l of labels) {- if (cli === 'glab') {- await exec(cli, ['label', 'create', '--name', l.name, '--color', `#${l.color}`, '--description', l.desc], { cwd, env });- } else {- await exec(cli, ['label', 'create', l.name, '--color', l.color, '--description', l.desc, '--force'], { cwd, env });- }- }-}--/**- * File ONE proposal issue on a forge (gh/glab). Ensures labels first, embeds the- * slug marker in the body, and returns `{ success, number, url }`. The issue- * number is parsed from the created URL's trailing digits.- */-export async function fileProposalToForge({ cli, cwd, env, title, body, slug, exec = runCli } = {}) {- await ensureForgeLabels({ cli, cwd, env, exec });- const fullBody = `${body}\n\n${slugMarker(slug)}`;- const args = cli === 'glab'- ? ['issue', 'create', '--title', title, '--description', fullBody, '--label', LI_LABEL]- : ['issue', 'create', '--title', title, '--body', fullBody, '--label', LI_LABEL];- const { code, stdout, stderr } = await exec(cli, args, { cwd, env });- if (code !== 0) return { success: false, error: stderr || `${cli} exited with code ${code}` };- const urlMatch = stdout.trim().match(/(https?:\/\/\S+)/);- const url = urlMatch ? urlMatch[1] : stdout.trim();- const numMatch = url.match(/(\d+)\s*$/);- return { success: true, number: numMatch ? Number(numMatch[1]) : null, url };-}--/** Apply the blocking label to an existing issue (pause). Returns `{ success }`. */-export async function applyBlockingLabel({ cli, cwd, env, number, exec = runCli } = {}) {- if (!Number.isInteger(number)) return { success: false, error: 'no issue number' };- const args = cli === 'glab'- ? ['issue', 'update', String(number), '--label', LI_BLOCKING_LABEL]- : ['issue', 'edit', String(number), '--add-label', LI_BLOCKING_LABEL];- const { code, stderr } = await exec(cli, args, { cwd, env });- return code === 0 ? { success: true } : { success: false, error: stderr };-}--// ----------------------------------------------------------------------------// Jira filer. Jira has no forge CLI — it goes through the PortOS Jira REST-// service (server/services/jira.js). Dedup + pause are label-based (same as the-// forges) via JQL, with the slug marker embedded in the ticket description.-// The Jira deps (search/create/addLabel) are injectable so tests drive the-// dispatch without a live Jira instance.-// -----------------------------------------------------------------------------/**- * Normalize a Jira status CATEGORY to `open` / `closed`. Jira's three canonical- * categories are "To Do" / "In Progress" / "Done"; only "Done" counts as closed- * for dedup + park. Anything unrecognized is treated as open so a custom- * in-flight status can't slip past dedup.- */-export function normalizeJiraState(statusCategory) {- return (statusCategory || '').toLowerCase() === 'done' ? 'closed' : 'open';-}--/**- * List existing layered-intelligence tickets in a Jira project (open + recently- * closed) for the reasoner + dedup guard. Mirrors listForgeIssues' `{ ok, issues }`- * failed-vs-empty contract: a thrown search is `ok:false` (do NOT file — a blind- * dedup would duplicate); an empty result is `ok:true, issues:[]`.- */-export async function listJiraIssues({ instanceId, projectKey, jql, searchOptions, search = searchIssues } = {}) {- if (!instanceId || !projectKey) return { ok: false, issues: [] };- // `jql` lets the plannedWork source (#2698) reuse this parse path for the- // prioritized backlog; absent, it's the layered-intelligence label set.- const query = jql || `project = "${escapeJql(projectKey)}" AND labels = "${LI_LABEL}" ORDER BY updated DESC`;- const rows = searchOptions- ? await search(instanceId, query, searchOptions).then(r => r, () => null)- : await search(instanceId, query).then(r => r, () => null);- if (!Array.isArray(rows)) return { ok: false, issues: [] };- return {- ok: true,- issues: rows.map(i => ({- number: i.key || null,- title: i.summary || '',- body: i.description || '',- state: normalizeJiraState(i.statusCategory),- closedAt: i.resolutiondate || null,- labels: normalizeIssueLabels(i.labels),- // Jira DOES have a real priority field (unlike the forges) — but only when- // the caller asked searchIssues for it. Absent → null → the renderer omits- // it, rather than a fabricated default.- priority: typeof i.priority === 'string' && i.priority.trim() ? i.priority.trim() : null,- slug: extractSlugFromBody(i.description || '') || extractSlugFromBody(i.summary || '')- }))- };-}--/**- * The JQL for a Jira project's committed backlog (#2698): `plan`-labeled tickets- * that aren't Done, highest priority first.- *- * The label filter is NOT optional — it is what makes this source mean the same- * thing on Jira as on a forge. Without it the query returns every open ticket,- * i.e. the untriaged backlog nobody has committed to (plus LI's own past- * proposals), which would then render under a header asserting the user- * "already committed to" them and instruct the reasoner to suppress against- * essentially the whole tracker — and duplicate the `openIssues` source besides.- * A project that doesn't use the label reports a truthful "nothing planned"- * rather than a backlog-shaped lie.- *- * Deliberately NOT `sprint in openSprints()` — the Sprint field only exists on- * Scrum-board-backed projects, and JQL referencing an absent field is a hard 400- * rather than an empty result, which would make gatherPlannedWork report- * "unavailable" forever on every Kanban/basic project. `labels` exists on every- * project shape. Priority is an ORDER BY rather than a filter for the same- * reason: priority NAMES are scheme-specific (a project can rename or drop- * "Highest"), so filtering on them risks the same permanent-400.- */-export function plannedWorkJql(projectKey) {- return `project = "${escapeJql(projectKey)}" AND labels = "${PLANNED_WORK_LABEL}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`;-}--/**- * List OPEN blocking-labeled Jira tickets for the app (park check). `{ ok, issues }`- * with the same failed-vs-empty distinction. JQL filters out Done so a resolved- * blocking ticket un-parks the app automatically (matching the forge pause model).- */-export async function listJiraBlockingIssues({ instanceId, projectKey, search = searchIssues } = {}) {- if (!instanceId || !projectKey) return { ok: false, issues: [] };- const jql = `project = "${escapeJql(projectKey)}" AND labels = "${LI_JIRA_BLOCKING_LABEL}" AND statusCategory != Done ORDER BY updated DESC`;- const rows = await search(instanceId, jql).then(r => r, () => null);- if (!Array.isArray(rows)) return { ok: false, issues: [] };- return {- ok: true,- issues: rows.map(i => ({ number: i.key || null, title: i.summary || '', state: normalizeJiraState(i.statusCategory) }))- };-}--/**- * File ONE proposal ticket in a Jira project. Embeds the slug marker in the- * description (searchable for dedup) and tags it with the layered-intelligence- * label. Returns `{ success, key, url }` — Jira issues are keyed strings- * (`PROJ-123`), not integers, so the handler resolves pause targets by key.- */-export async function fileProposalToJira({ instanceId, projectKey, issueType = 'Task', title, body, slug, create = createTicket } = {}) {- if (!instanceId || !projectKey) return { success: false, error: 'jira instance/project not configured' };- const description = `${body}\n\n${slugMarker(slug)}`;- const res = await create(instanceId, {- projectKey,- summary: title,- description,- issueType,- labels: [LI_LABEL]- }).then(r => r, (err) => ({ success: false, error: err?.message || 'jira create failed' }));- if (!res?.success) return { success: false, error: res?.error || 'jira create failed' };- return { success: true, key: res.ticketId || null, url: res.url || null };-}--/**- * Resolve a Jira pause target to a concrete issue KEY. `"this"` → the just-filed- * ticket's key; an integer → `<projectKey>-<n>` (a pre-existing ticket in the- * same project). Returns null when it can't resolve (e.g. `"this"` but nothing- * was filed, or no project key for an integer target).- */-export function resolveJiraBlockKey(pause, filedKey, projectKey) {- if (!pause) return null;- if (pause.blockOnIssue === 'this') return filedKey || null;- if (Number.isInteger(pause.blockOnIssue) && projectKey) return `${projectKey}-${pause.blockOnIssue}`;- return null;-}--/** Apply the Jira blocking label to an existing ticket (pause). Returns `{ success }`. */-export async function applyJiraBlockingLabel({ instanceId, key, addLabel = addLabels } = {}) {- if (!instanceId || !key) return { success: false, error: 'no jira ticket key' };- const res = await addLabel(instanceId, key, [LI_JIRA_BLOCKING_LABEL]).then(r => r, (err) => ({ success: false, error: err?.message }));- return res?.success ? { success: true } : { success: false, error: res?.error || 'jira label failed' };-}--/**- * Append a slug-tagged proposal to the app's PLAN.md (the `plan` tracker path).- * Dedups by scanning for the `[lil-<slug>]` tag. Creates PLAN.md with a heading- * + `## Next Up` section if absent. Returns `{ success, duplicate }`.+ * See docs/plans/2026-07-07-layered-intelligence-loop.md for the full design.*/-export async function appendProposalToPlan({ repoPath, appName, slug, title, body } = {}) {- const planPath = join(repoPath, 'PLAN.md');- const tag = `[lil-${slug}]`;- const existing = existsSync(planPath) ? await readFile(planPath, 'utf-8').catch(() => '') : '';- if (existing.includes(tag)) return { success: true, duplicate: true };- const oneLine = (body || '').replace(/\s+/g, ' ').trim().slice(0, 500);- const item = `- [ ] ${tag} **${title}** ${oneLine}`.trim();-- if (!existing) {- const content = `# ${appName} — Development Plan\n\n## Next Up\n\n${item}\n`;- await writeFile(planPath, content);- return { success: true, duplicate: false };- }- const nextUpRe = /(##\s+Next Up[^\n]*)(\n?)/;- if (nextUpRe.test(existing)) {- // Insert right after the "## Next Up" heading line, normalizing the heading's- // line ending first so a file that ENDS at `## Next Up` (no trailing newline)- // gets the item on its own line rather than a second section appended below.- const updated = existing.replace(nextUpRe, `$1\n${item}\n`);- await writeFile(planPath, updated.endsWith('\n') ? updated : `${updated}\n`);- return { success: true, duplicate: false };- }- // No Next Up section — append one.- const sep = existing.endsWith('\n') ? '' : '\n';- await appendFile(planPath, `${sep}\n## Next Up\n\n${item}\n`);- return { success: true, duplicate: false };-}--/**- * Scan a PLAN.md string for `[lil-<slug>]` tags → array of `{ slug, state }`.- * Preserves each tag's list-item checkbox so the outcome loop (#2435) can- * reconcile a completed PLAN proposal: `- [x] [lil-foo]` reads as `closed`,- * `- [ ] [lil-foo]` as `open`.- *- * Absent ≠ done (the CLAUDE.md sentinel rule): a bare tag with NO preceding- * checkbox stays `open` (still tracked/suppressed) rather than collapsing to- * `closed` — a missing checkbox must not silently make an item re-proposable.- * A `closed` item carries no `closedAt` (PLAN.md checkboxes have no timestamp),- * which `isIssueWithinDedupWindow` treats as permanently in-window → a completed- * proposal stays suppressed forever instead of being re-reasoned every run (#2620).- */-export function extractPlanSlugs(planContent) {- if (typeof planContent !== 'string') return [];- const items = [];- // Alt 1: a list item `- [ ]`/`- [x]` whose line also carries the tag (state- // from the checkbox char). Alt 2: a bare tag with no checkbox (state 'open').- const re = /^[ \t]*[-*][ \t]*\[([ xX])\][^\n]*?\[lil-([a-z0-9][a-z0-9-]*)\]|\[lil-([a-z0-9][a-z0-9-]*)\]/gim;- let m;- while ((m = re.exec(planContent))) {- if (m[2]) {- items.push({ slug: m[2].toLowerCase(), state: m[1].toLowerCase() === 'x' ? 'closed' : 'open' });- } else {- items.push({ slug: m[3].toLowerCase(), state: 'open' });- }- }- return items;-}+export * from './layeredIntelligence/constants.js';+export * from './layeredIntelligence/config.js';+export * from './layeredIntelligence/dedup.js';+export * from './layeredIntelligence/proposal.js';+export * from './layeredIntelligence/outcomes.js';+export * from './layeredIntelligence/awareness.js';+export * from './layeredIntelligence/gates.js';+export * from './layeredIntelligence/prompt.js';+export * from './layeredIntelligence/runCli.js';+export * from './layeredIntelligence/sources.js';+export * from './layeredIntelligence/semanticDedup.js';+export * from './layeredIntelligence/forgeFiler.js';+export * from './layeredIntelligence/jiraFiler.js';+export * from './layeredIntelligence/planFiler.js';diff --git a/server/services/layeredIntelligence/awareness.js b/server/services/layeredIntelligence/awareness.jsnew file mode 100644index 0000000000..a619332915--- /dev/null+++ b/server/services/layeredIntelligence/awareness.js@@ -0,0 +1,385 @@+/**+ * Layered Intelligence — scope / execution awareness reports+ * (#2842 split of layeredIntelligence.js).+ *+ * The avoid/prefer signals derived from task-learning metrics and proposal+ * execution outcomes, the propose-well-but-execute-poorly cross-reference, and the+ * deterministic hand-off routing decision (auto-hand-off vs file-for-human).+ */++import { EFFECTIVE_RATE_MIN_WINDOW_SAMPLES } from '../taskLearning/store.js';+import { summarizeExecutionFailures, formatExecutionFailure } from '../layeredIntelligenceExecutionFailures.js';+import {+ SCOPE_AWARENESS_MAX_TYPE_LEN, SCOPE_AWARENESS_MAX_PER_LIST, SCOPE_AWARENESS_MIN_SAMPLE,+ SCOPE_AVOID_SUCCESS_THRESHOLD, SCOPE_PREFER_SUCCESS_THRESHOLD,+ PROPOSAL_OUTCOMES, PROPOSAL_EXECUTION_OUTCOMES, PROPOSAL_EXECUTION_MIN_SAMPLE,+} from './constants.js';++/**+ * Clamp a task-type / proposal-domain label so one pathological key (e.g. a mission+ * task type embedding an unbounded mission name) can't blow the scope-awareness block+ * budget. Shared by both avoid/prefer signals below.+ */+export function clampScopeLabel(label) {+ return label.length > SCOPE_AWARENESS_MAX_TYPE_LEN+ ? `${label.slice(0, SCOPE_AWARENESS_MAX_TYPE_LEN - 1)}…`+ : label;+}++/**+ * Render an avoid/prefer prompt block from pre-classified item lists — the presentation+ * both scope-awareness signals share (#2760 install-wide task-type rates, #2765+ * per-proposal-domain execution rates). Owns the sort (worst-first avoid, best-first+ * prefer), the per-list cap + "…and N more" overflow, and the empty-guard, so a tweak+ * to any of those lands in one place. Callers supply their own classified `avoid`/+ * `prefer` lists, the per-item `fmt`, and the two headers — the only parts that+ * legitimately differ between the two signals. Returns '' when both lists are empty.+ */+function renderAvoidPreferSections({ avoid = [], prefer = [], fmt, avoidHeader, preferHeader }) {+ if (!avoid.length && !prefer.length) return '';+ avoid.sort((a, b) => a.rate - b.rate); // worst-first — sharpest signal at the top+ prefer.sort((a, b) => b.rate - a.rate); // best-first+ const section = (header, items) => {+ const shown = items.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);+ const more = items.length - shown.length;+ const lines = shown.map(fmt);+ if (more > 0) lines.push(`- …and ${more} more`);+ return `${header}\n${lines.join('\n')}`;+ };+ const sections = [];+ if (avoid.length) sections.push(section(avoidHeader, avoid));+ if (prefer.length) sections.push(section(preferHeader, prefer));+ return sections.join('\n\n');+}++/**+ * Scope-awareness report (#2760). Classifies each CoS task TYPE by its completion rate+ * into low-completion and high-completion lists, as directional context for the+ * reasoner. Pure — takes the already-parsed per-type metrics map (the `summary`+ * gatherSources builds from learning.byTaskType) and returns a report string, or ''+ * when no type has enough runs to qualify either way.+ *+ * IMPORTANT (codex P1): this is per-task-TYPE, install-wide completion telemetry — NOT+ * a per-proposal execution record. An LI proposal is later implemented through a+ * claim/plan/handoff task whose task type does NOT carry the proposal's domain (a+ * handoff becomes `internal-task`; a claimed issue runs under the claim task type), so+ * these buckets are populated by independently-scheduled jobs, not by LI's own+ * proposals bucketed by subject. The block is therefore framed as "work of this KIND+ * tends to (not) get finished here" — useful directional context (especially LI's own+ * reasoning-run type, self-improve:layered-intelligence, which IS LI's execution) — and+ * deliberately NOT a claim that a given proposal maps 1:1 onto a listed type. Proper+ * per-proposal-domain outcome correlation is tracked as a follow-up (#2765).+ *+ * `metricsByType[type] = { lifetimeSuccessRate, lifetimeCompleted, recentSuccessRate, recentCompleted, ... }`.+ *+ * Classification judges on the EFFECTIVE rate — the recency-windowed rate when the+ * window has enough samples, else lifetime — NOT the raw lifetime rate. This matters+ * for the issue's "dynamic adjustment" requirement: the lifetime rate barely decays+ * (an old failure burst depresses it near-permanently), so a scope that has actually+ * recovered would stay stuck on the avoid list for dozens of runs. Using the windowed+ * rate lets a recovered scope leave "avoid" promptly — and, critically, this uses the+ * SAME window floor as the scheduler's own skip logic+ * (EFFECTIVE_RATE_MIN_WINDOW_SAMPLES, the threshold in computeEffectiveSuccessRate /+ * isSkipCandidate): the window is trusted only at >= that many in-window runs, so a+ * single noisy recent result can't flip a lifetime-reliable scope to avoid (or vice+ * versa). Below that floor the lifetime rate governs, exactly as the scheduler does,+ * so this advisory list moves in the same direction the scheduler acts on. The base+ * sample floor still gates on LIFETIME completed: a scope needs enough TOTAL evidence+ * to be judged at all. Each rendered rate is paired with the run count of the SAME+ * basis (windowed count when the window governs, lifetime count otherwise) so the+ * "N% over M runs" line never mixes a windowed rate with a lifetime count.+ *+ * The thresholds (50/75) are deliberately NOT the scheduler's 30% hard-skip line: this+ * steering is advisory (it nudges what LI PROPOSES, it never suppresses execution), so+ * a wider, more cautious net is correct here. LI still MAY propose in an avoid scope+ * when it is genuinely the highest-value work — it just has to justify doing so.+ */+export function computeScopeAwareness({ metricsByType = {} } = {}) {+ const avoid = [];+ const prefer = [];+ for (const [type, m] of Object.entries(metricsByType || {})) {+ const lifetimeN = m?.lifetimeCompleted || 0;+ if (lifetimeN < SCOPE_AWARENESS_MIN_SAMPLE) continue; // not enough total evidence to judge+ // Effective rate: trust the recency window ONLY when it carries enough samples —+ // the same EFFECTIVE_RATE_MIN_WINDOW_SAMPLES floor the scheduler's+ // computeEffectiveSuccessRate uses — so one noisy recent run can't flip a+ // lifetime-reliable scope. Below the floor (including an empty window, where+ // recentSuccessRate is null, not 0 — #2460), lifetime governs. Pair the rate with+ // the count of its own basis so the rendered "N% over M runs" is truthful.+ const useWindow = m?.recentCompleted >= EFFECTIVE_RATE_MIN_WINDOW_SAMPLES+ && typeof m?.recentSuccessRate === 'number';+ const rate = useWindow ? m.recentSuccessRate : m?.lifetimeSuccessRate;+ if (typeof rate !== 'number') continue; // a never-run scope stays neutral+ const n = useWindow ? m.recentCompleted : lifetimeN;+ if (rate < SCOPE_AVOID_SUCCESS_THRESHOLD) avoid.push({ type, rate, n });+ else if (rate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ type, rate, n });+ }+ // Honest framing (#2760, codex P1): these are per-task-TYPE completion rates for the+ // whole install — NOT a per-proposal execution record. An LI proposal is implemented+ // through a claim/plan/handoff task whose type does not carry the proposal's domain,+ // so this is directional context ("work of this kind tends to (not) get finished+ // here"), not a claim that a given proposal maps 1:1 onto a listed type.+ return renderAvoidPreferSections({+ avoid,+ prefer,+ fmt: ({ type, rate, n }) => `- ${clampScopeLabel(type)}: ${Math.round(rate)}% completed over ${n} runs`,+ avoidHeader: `LOW-COMPLETION task types — work of this kind is finished below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time on this install:`,+ preferHeader: `HIGH-COMPLETION task types — finished at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%:`+ });+}++/**+ * Aggregate LI proposal EXECUTION outcomes by proposal DOMAIN (scope) (#2765).+ * Pure. Unlike computeScopeAwareness — which borrows install-wide CoS+ * per-task-TYPE completion rates that a proposal only loosely maps onto — this is a+ * TRUE per-proposal record: each data point is one of LI's OWN filed proposals that+ * was handed off and executed, keyed by the domain (scope) it was proposed under.+ *+ * `outcomes` is the app's outcome records (from listOutcomes); only records carrying+ * a resolved `executionOutcome` AND a `scope` contribute. Returns+ * `{ [scope]: { completed, succeeded, successRate, failureSummary } }` (empty when+ * nothing has been executed yet). The acceptance signal for #2765: after one proposal+ * in domain X is executed, only X's bucket moves.+ *+ * `failureSummary` (#2764 §3) carries the per-domain execution-FAILURE taxonomy tally+ * so a low execution rate no longer arrives without its cause: it is the shared+ * `summarizeExecutionFailures` engine run over ONLY this domain's records (the engine+ * itself keeps just the failures), the "filter per-domain, then reuse the existing+ * summariser" join #2764 §3 asks for. Every bucket carries one — a domain with zero+ * failed hand-offs simply reports `total: 0`, the honest "nothing to explain" reading.+ */+export function computeExecutionByDomain(outcomes = []) {+ // Group each executed record by its domain first, so the failure taxonomy can be+ // tallied over that domain's OWN records rather than the install-wide set.+ const recordsByScope = new Map();+ for (const r of Array.isArray(outcomes) ? outcomes : []) {+ if (!r || typeof r !== 'object') continue;+ if (!PROPOSAL_EXECUTION_OUTCOMES.includes(r.executionOutcome)) continue;+ const scope = typeof r.scope === 'string' && r.scope.trim() ? r.scope.trim() : null;+ if (!scope) continue;+ if (!recordsByScope.has(scope)) recordsByScope.set(scope, []);+ recordsByScope.get(scope).push(r);+ }+ // Null prototype: `scope` is an LLM-authored free string, and a "__proto__"+ // key on a plain object would silently rewrite the prototype instead of+ // adding a bucket — vanishing from Object.entries while lookups read the+ // prototype object.+ const byDomain = Object.create(null);+ for (const [scope, records] of recordsByScope) {+ const completed = records.length;+ const succeeded = records.filter(r => r.executionOutcome === 'success').length;+ byDomain[scope] = {+ completed,+ succeeded,+ successRate: Math.round((succeeded / completed) * 100),+ // Reuse the shared taxonomy engine on this domain's slice — it discards the+ // successes internally, so passing the whole slice yields this domain's own+ // failure shape without a second pre-filter here.+ failureSummary: summarizeExecutionFailures(records)+ };+ }+ return byDomain;+}++/**+ * Render the dominant execution-failure causes from a domain's `failureSummary`+ * (#2764 §3) as a compact clause for the per-domain avoid line. Reuses the shared+ * `formatExecutionFailure` gloss so the wording matches the install-wide failure line+ * in computeOutcomesReport. Returns '' when the domain holds NO diagnosed failure — a+ * pure-`unknown`/`unclassified` (or failure-free) domain adds no cause clause rather+ * than a hollow "failed for unknown reasons" tail on every low-execution line.+ */+export function formatDominantFailureCause(failureSummary, limit = 2) {+ const entries = Array.isArray(failureSummary?.entries) ? failureSummary.entries : [];+ if (entries.length === 0) return '';+ const listed = entries+ .slice(0, limit)+ .map(({ category, count }) => `${formatExecutionFailure(category)} (${count})`)+ .join('; ');+ return `failing mostly on ${listed}`;+}++/**+ * Is this a proposal DOMAIN whose OWN hand-offs chronically fail — enough executed+ * hand-offs to be evidence (PROPOSAL_EXECUTION_MIN_SAMPLE) AND a success rate below+ * the coin-flip avoid line (SCOPE_AVOID_SUCCESS_THRESHOLD)? The single load-bearing+ * definition of "on the avoid list", shared so the reasoner-facing prompt+ * (computeProposalExecutionAwareness) and the deterministic hand-off gate+ * (computeHandoffRouting) can NEVER disagree about which domains qualify — the+ * design requires the prompt's avoid list and the gate to name the same set. Takes+ * a per-domain bucket from computeExecutionByDomain (or undefined when the domain+ * has no execution history → false).+ */+export function isAvoidDomain(bucket) {+ return !!bucket+ && bucket.completed >= PROPOSAL_EXECUTION_MIN_SAMPLE+ && bucket.successRate < SCOPE_AVOID_SUCCESS_THRESHOLD;+}++/**+ * Render the per-proposal-DOMAIN execution avoid/prefer split for the reasoning+ * prompt (#2765) — the real per-proposal signal the #2760 install-wide scope block+ * could only approximate. Returns '' when no domain clears the sample floor, so+ * buildPrompt omits the block. Mirrors computeScopeAwareness's 50/75 thresholds and+ * bounded rendering, but keys on the proposal's own scope and carries NO+ * "directional context only" caveat: this IS how LI's own proposals in each domain+ * fared, so the reasoner can steer toward domains it actually executes and away from+ * domains where its own hand-offs fail even after the proposal was accepted.+ */+export function computeProposalExecutionAwareness({ outcomes = [] } = {}) {+ const byDomain = computeExecutionByDomain(outcomes);+ const avoid = [];+ const prefer = [];+ for (const [scope, bucket] of Object.entries(byDomain)) {+ // The per-domain failure CAUSE (#2764 §3) is surfaced only for domains that clear+ // this floor — i.e. only where the domain is already listed as low-execution. A+ // single failed hand-off below the floor is the install-wide early-signal case the+ // "Why LI's own hand-offs failed" line in computeOutcomesReport already reports, so+ // we do not also emit a one-sample per-domain cause here (it would read as a trend+ // off n=1).+ if (bucket.completed < PROPOSAL_EXECUTION_MIN_SAMPLE) continue; // not enough executions to judge this domain+ if (isAvoidDomain(bucket)) avoid.push({ scope, rate: bucket.successRate, n: bucket.completed, cause: formatDominantFailureCause(bucket.failureSummary) });+ else if (bucket.successRate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ scope, rate: bucket.successRate, n: bucket.completed });+ }+ return renderAvoidPreferSections({+ avoid,+ prefer,+ // Only the avoid list carries a `cause`; a preferred (reliably-executed) domain has+ // no failure shape worth naming, so its clause is simply absent.+ fmt: ({ scope, rate, n, cause }) => `- ${clampScopeLabel(scope)}: LI implemented ${rate}% of its own ${scope} proposals successfully over ${n} executed${cause ? ` — ${cause}` : ''}`,+ avoidHeader: `LOW-EXECUTION proposal domains — LI's OWN hand-offs in these domains succeed below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time; a proposal here needs a strong justification or a narrower slice:`,+ preferHeader: `HIGH-EXECUTION proposal domains — LI reliably implements its own proposals here (at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%):`+ });+}++// Header for the cross-reference block (#2764 §3). Names the pattern the block exists+// to surface: a domain LI PROPOSES well (its proposals earn merges) yet EXECUTES+// poorly (its own hand-offs there fail), which neither liOutcomes (merge rate alone)+// nor liProposalExecution (execution rate alone) puts side by side.+const CROSS_REFERENCE_HEADER = "Domains where LI PROPOSES well but EXECUTES poorly — the proposal earns a merge, yet LI's OWN hand-off to implement it tends to fail with the named cause. These are blind spots: you pick the right work here but can't finish it as handed off. Narrow such a proposal to a slice an agent can complete, split it, or route it to a human — don't re-file the same shape expecting a different execution result:";++/**+ * Cross-reference MERGED-proposal success against EXECUTION-failure modes within the+ * SAME domain (#2764 §3). Pure + side-effect-free like the sibling report functions;+ * derives only from the outcome records already loaded (no new store read, no AI/tracker+ * call). The unique signal it adds over liOutcomes (per-scope merge rate) and+ * liProposalExecution (per-domain execution rate) is the CONTRAST between them: a domain+ * whose proposals the user merges but whose hand-offs then fail is "proposes well,+ * executes poorly" — the reasoner should keep proposing there but narrow the scope, not+ * abandon the domain (which a low execution rate read alone might imply).+ *+ * A domain qualifies only when BOTH signals are present: at least one MERGED proposal+ * (the "proposes well" side — otherwise the domain is just failing outright, which+ * liProposalExecution already covers) AND at least one DIAGNOSED failed hand-off (the+ * "executes poorly" side, with a concrete cause to name — a purely `unknown`/+ * `unclassified` failure history has no actionable mode to cross-reference). Merge rate+ * is measured over RESOLVED proposals only — the same denominator summarizeOutcomeStats+ * uses for its rawMergeRate (pending ≠ a merge verdict), not computeOutcomesReport's+ * per-scope rate, which divides by all filed. Sorted sharpest-execution-problem first;+ * bounded like the avoid/prefer lists. Returns '' when no domain qualifies, so+ * buildPrompt omits the block.+ */+export function computeCrossReferenceAnalysis({ outcomes = [] } = {}) {+ const records = Array.isArray(outcomes) ? outcomes : [];+ const byDomain = computeExecutionByDomain(records); // per-domain failure taxonomy (self-guards bad records)++ // Per-domain merge stats over RESOLVED proposals (pending ≠ a merge verdict).+ const mergeByScope = new Map();+ for (const o of records) {+ if (!o || typeof o !== 'object') continue;+ const scope = typeof o.scope === 'string' && o.scope.trim() ? o.scope.trim() : null;+ if (!scope) continue;+ if (!PROPOSAL_OUTCOMES.includes(o.outcome)) continue; // unresolved: no verdict yet+ const agg = mergeByScope.get(scope) || { merged: 0, resolved: 0 };+ agg.resolved += 1;+ if (o.outcome === 'merged') agg.merged += 1;+ mergeByScope.set(scope, agg);+ }++ const qualifying = [];+ for (const [scope, exec] of Object.entries(byDomain)) {+ const merge = mergeByScope.get(scope);+ if (!merge || merge.merged < 1) continue; // "proposes well" side needs a merge+ const { entries, diagnosed, total: failTotal } = exec.failureSummary;+ if (diagnosed < 1) continue; // "executes poorly" side needs a diagnosed failed hand-off+ const top = entries[0];+ qualifying.push({+ scope,+ mergeRate: Math.round((merge.merged / merge.resolved) * 100),+ merged: merge.merged,+ resolved: merge.resolved,+ cause: top.category,+ causeCount: top.count,+ failTotal,+ diagnosed+ });+ }+ if (!qualifying.length) return '';+ // Sharpest execution problem first (most diagnosed failures), ties broken by the+ // strongest "proposes well" contrast (highest merge rate) so the output is stable.+ qualifying.sort((a, b) => b.diagnosed - a.diagnosed || b.mergeRate - a.mergeRate);+ const shown = qualifying.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);+ const more = qualifying.length - shown.length;+ const lines = shown.map(q =>+ `- ${clampScopeLabel(q.scope)}: proposals merge at ${q.mergeRate}% (${q.merged}/${q.resolved}) but hand-offs here fail on ${q.cause} (${q.causeCount} of ${q.failTotal})`+ );+ if (more > 0) lines.push(`- …and ${more} more`);+ return `${CROSS_REFERENCE_HEADER}\n${lines.join('\n')}`;+}++/**+ * Deterministic hand-off routing gate (#2764 §4). Given a proposal and the app's+ * historical outcome records, decides whether a trivial+safe proposal may be+ * auto-handed-off to a coding agent NOW, or must instead be filed for a human —+ * because LI's OWN prior hand-offs in that domain chronically fail. This is the+ * SYSTEM-side enforcement of the same signal the reasoner is merely WARNED about+ * in the liProposalExecution / liCrossReference prompt blocks: even when the+ * reasoner marks a proposal trivial+safe, the gate suppresses the auto-hand-off+ * for a domain whose track record says the hand-off will just fail again.+ *+ * Pure + side-effect-free, like the sibling compute* report functions — derives+ * only from the `li-outcomes` records already loaded (no new AI/tracker/store+ * call). The just-filed proposal cannot skew this: computeExecutionByDomain only+ * counts records carrying a resolved `executionOutcome`, which a freshly-filed+ * proposal has not got yet.+ *+ * Shares the isAvoidDomain classifier with computeProposalExecutionAwareness so the+ * gate and the reasoner-facing prompt can NEVER disagree about which domains are+ * "chronically failing": a domain qualifies only when it has at least+ * PROPOSAL_EXECUTION_MIN_SAMPLE executed hand-offs AND its success rate is below+ * SCOPE_AVOID_SUCCESS_THRESHOLD — the SAME floor + threshold that puts a domain on+ * the reasoner's avoid list.+ *+ * Returns:+ * - `{ handoff: true, reason: null }` — allow the auto-hand-off, when the+ * proposal has no scope (can't judge), the domain is below the sample floor,+ * the domain has no execution history, or its rate is at/above the threshold.+ * - `{ handoff: false, domain, rate, n, cause, reason }` — SUPPRESS: file for a+ * human instead. `reason` names the domain, rate, sample size, and (when a+ * dominant failure cause is diagnosed) the cause — reusing formatDominantFailureCause,+ * which returns '' for a purely unknown/unclassified domain so the cause clause+ * is simply omitted there.+ *+ * @param {object} args+ * @param {object} args.proposal - the reasoner's proposal ({ scope, ... }).+ * @param {Array} [args.outcomes] - the app's li-outcomes records.+ * @returns {{ handoff: boolean, reason: string|null, domain?: string, rate?: number, n?: number, cause?: string }}+ */+export function computeHandoffRouting({ proposal, outcomes = [] } = {}) {+ // No scope → we can't map the proposal to a domain's track record, so we can't+ // justify suppressing the hand-off. Allow, as before §4 existed.+ const domain = typeof proposal?.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;+ if (!domain) return { handoff: true, reason: null };++ const byDomain = computeExecutionByDomain(outcomes);+ const bucket = byDomain[domain];+ // Below the floor, no bucket, or at/above the threshold → no signal to suppress on,+ // so allow the hand-off exactly as today. isAvoidDomain is the SAME predicate+ // computeProposalExecutionAwareness uses for its avoid list, so the gate and the+ // reasoner-facing prompt agree on which domains are "chronically failing".+ if (!isAvoidDomain(bucket)) return { handoff: true, reason: null };++ const cause = formatDominantFailureCause(bucket.failureSummary);+ const reason = `${domain} hand-offs succeed ${bucket.successRate}% over ${bucket.completed} executed — filing for human review instead of auto-hand-off${cause ? ` (${cause})` : ''}`;+ return { handoff: false, domain, rate: bucket.successRate, n: bucket.completed, cause, reason };+}diff --git a/server/services/layeredIntelligence/config.js b/server/services/layeredIntelligence/config.jsnew file mode 100644index 0000000000..6eb735f650--- /dev/null+++ b/server/services/layeredIntelligence/config.js@@ -0,0 +1,114 @@+/**+ * Layered Intelligence — per-app config resolution (#2842 split of layeredIntelligence.js).+ *+ * The shipped defaults, the settings→effective-config merge, and the scope gate+ * that keeps the PortOS-only meta/self scopes off other apps.+ */++import { DAY } from '../../lib/fileUtils.js';+import { PROPOSAL_SCOPES, PORTOS_ONLY_SCOPES } from './constants.js';++/**+ * The default per-app config. PortOS (isPortos) additionally gets the meta/self+ * scopes so the loop can extend itself; every other app is capped at its own+ * improvement + data-gap scopes. Off by default — the loop is a user-enabled+ * scheduled automation (AI-provider "no cold-bootstrap" policy).+ */+export function defaultLayeredIntelligenceConfig(isPortos = false) {+ return {+ enabled: false,+ intervalMs: DAY,+ providerId: null,+ model: null,+ sources: {+ goals: true,+ // The app's OWN performance metrics (a METRICS.md doc in the app repo): the+ // user-success / KPI / production-telemetry signals the app tracks about+ // itself. This is the PRIMARY signal for evaluating a managed app against+ // its own goals and purpose, so it's on by default for every app. See the+ // METRICS.md convention in docs/METRICS.md.+ appMetrics: true,+ // The autonomous coding-agent run stats this install records (learning.json).+ // For the PortOS install these ARE its own-performance metrics; for a MANAGED+ // app they describe how reliably PortOS's agents change the app (a tooling /+ // interaction signal), NOT the app's own product performance — so default it+ // on only for PortOS. A managed app measures itself through appMetrics/custom+ // sources instead; the user can still opt this on per-app.+ cosMetrics: isPortos,+ healthReport: true,+ planMd: true,+ openIssues: true,+ // The backlog the user has ALREADY committed to (#2698): `plan`-labeled+ // tracker issues / the app's prioritized Jira backlog / PLAN.md's unchecked+ // items. Open issues alone read as a flat list with no priority context, so+ // the reasoner had no way to tell "nobody has looked at this" from "the user+ // already scheduled this" — the top NOT_PLANNED rejection cause. On by+ // default for every app: cross-referencing against committed work is only+ // useful if it is there by default.+ plannedWork: true,+ // The self-feedback signal (#2428): past LI proposals + their tracker+ // outcomes, fed back so the reasoner calibrates on its own merge rate.+ // Default ON for the PortOS install (it improves itself), OFF for managed+ // apps — the user opts in per-app via the LI config UI.+ outcomes: isPortos,+ // The loop's self-awareness signal (#2700): a deterministic read of LI's OWN+ // record — proposal merge rate, how many of its proposals are already filed+ // and suppressed, and whether its own agent runs are succeeding — folded back+ // so the reasoner can judge its proposal quality BEFORE filing rather than+ // only learning from rejections after. Same PortOS-only default as `outcomes`:+ // it is built from LI's own history, which only the self-improving install+ // accumulates meaningfully; managed apps opt in per-app.+ selfEval: isPortos,+ custom: []+ },+ rules: '',+ allowedScopes: isPortos+ ? ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']+ : ['app-improvement', 'app-data-gap'],+ // Engine-A hand-off. When enabled, a proposal the reasoner marks trivial+safe+ // is ALSO enqueued as a CoS coding-agent task (approval-gated) instead of only+ // being filed for later human triage. Off by default — letting an agent write+ // code from the loop unattended is an extra opt-in on top of enabling the loop.+ handoff: { enabled: false }+ };+}++/**+ * Merge an app record's stored `layeredIntelligence` over the defaults so a+ * partial config (or none) still yields a complete, safe config. `sources` is+ * merged one level deep so a stored `{ sources: { goals: false } }` doesn't wipe+ * the other source toggles.+ */+export function getEffectiveConfig(app) {+ const isPortos = !!app?.isPortos;+ const base = defaultLayeredIntelligenceConfig(isPortos);+ const stored = (app?.layeredIntelligence && typeof app.layeredIntelligence === 'object' && !Array.isArray(app.layeredIntelligence))+ ? app.layeredIntelligence+ : {};+ const merged = { ...base, ...stored };+ merged.sources = {+ ...base.sources,+ ...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {})+ };+ // Merge handoff one level deep (like sources) so a partial `{ handoff: {} }`+ // doesn't wipe the default `enabled`.+ merged.handoff = {+ ...base.handoff,+ ...(stored.handoff && typeof stored.handoff === 'object' && !Array.isArray(stored.handoff) ? stored.handoff : {})+ };+ if (!Array.isArray(merged.sources.custom)) merged.sources.custom = [];+ if (!Array.isArray(merged.allowedScopes)) merged.allowedScopes = base.allowedScopes;+ return merged;+}++/**+ * Whether a proposal scope is allowed for this app. A hallucinated or+ * hand-edited scope cannot escape this gate: it must be a recognized scope, be+ * in the app's `allowedScopes`, and — for meta/self scopes — the app must BE the+ * PortOS install. Double-enforced regardless of what the prompt told the model.+ */+export function isScopeAllowed({ scope, allowedScopes = [], isPortos = false }) {+ if (!PROPOSAL_SCOPES.includes(scope)) return false;+ if (PORTOS_ONLY_SCOPES.includes(scope) && !isPortos) return false;+ return allowedScopes.includes(scope);+}diff --git a/server/services/layeredIntelligence/constants.js b/server/services/layeredIntelligence/constants.jsnew file mode 100644index 0000000000..7f31672900--- /dev/null+++ b/server/services/layeredIntelligence/constants.js@@ -0,0 +1,237 @@+/**+ * Layered Intelligence — constants & tunables (#2842 split of layeredIntelligence.js).+ *+ * The tracker labels, dedup/suppression windows, scope + complexity vocabularies,+ * degradation/exclusion thresholds and the shipped proposal playbook. Pure data —+ * no behaviour — so every other LI module can import from here without a cycle.+ */++import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { DAY } from '../../lib/fileUtils.js';+import { extractTaskType } from '../taskLearning/store.js';++// Tracker labels + slug marker. The slug is the stable dedup key the reasoner+// chooses; it is embedded in each filed issue body so a later run (or the+// reasoner reading open issues) can self-avoid duplicates.+export const LI_LABEL = 'layered-intelligence';+export const LI_BLOCKING_LABEL = 'layered-intelligence:blocking';++// The tracker label marking an issue as work the user has COMMITTED to — the+// `plannedWork` source's filter (#2698). PortOS's own roadmap "lives entirely in+// the GitHub issue tracker" as `plan`-labeled issues, and that convention is the+// default for managed apps too.+export const PLANNED_WORK_LABEL = 'plan';++// How many planned-work items are surfaced to the reasoner. The point is to give+// it enough of the committed backlog to spot an overlap, not to reproduce the+// tracker — the count of the FULL set is always reported alongside, so a+// truncated list never reads as the whole picture.+export const PLANNED_WORK_MAX_ITEMS = 15;++// Character bound for the rendered plannedWork block, matching the other+// file-backed sources' 8000-char ceiling.+export const PLANNED_WORK_MAX_CHARS = 8000;++// The instruction buildPrompt attaches directly beneath the plannedWork block —+// the whole point of the source: turn "here is the backlog" into "so do not file+// against it".+export const PLANNED_WORK_GUIDANCE = 'Cross-reference your proposal against the user\'s actively-planned work above. If your proposal duplicates or conflicts with an active item, DO NOT file — return proposal: null. Only propose genuinely new work that does NOT overlap with what is already in scope.';++// The LI Proposal Playbook (#2763): standing, human-authored guidance distilling+// which proposals actually land vs. get rejected — scope selection, success/rejection+// pattern catalogs, task-type selection rules, and a goal-alignment check. Loaded+// once from the co-located markdown file so the prose stays reviewable-as-prose and+// buildPrompt can render it verbatim as the always-on `liPlaybook` block. It ships in+// the SOURCE tree (not seeded to data/prompts/), so it is code-versioned guidance that+// updates with the code — NOT a user-customizable stage prompt, and thus needs no+// PROMPT_VERSIONS bump or setup-data migration. Read synchronously at module load so+// the constant is ready before the first buildPrompt call; the file ships with the+// module, so a miss is a packaging bug worth surfacing loudly rather than swallowing.+export const LI_PROPOSAL_PLAYBOOK = readFileSync(+ // `..` — the playbook ships next to the barrel in server/services/, one level+ // up from this module's ./layeredIntelligence/ directory (#2842 split).+ join(dirname(fileURLToPath(import.meta.url)), '..', 'layeredIntelligence.playbook.md'),+ 'utf-8'+).trim();++// The instruction that frames the playbook block: apply it as a standing constraint,+// but let a live per-app data block (liOutcomes / liProposalExecution) override a+// general rule when it has real numbers that contradict it.+export const LI_PLAYBOOK_GUIDANCE = 'This playbook is the distilled, standing rule set for choosing WHAT to propose — apply it as a hard constraint on scope, task type, and goal alignment before you commit to a proposal. Where a live report above (liOutcomes / liProposalExecution) contradicts a general rule here with real data for THIS app, the live data wins; absent that data, follow the playbook.';++// Rendered when the tracker read SUCCEEDED and the app genuinely has no committed+// backlog. Says so explicitly rather than omitting the block, so "nothing planned"+// is legible to the reasoner as a real answer rather than a missing source.+export const PLANNED_WORK_NONE = 'No actively-planned work is currently tracked for this app. (The tracker was read successfully — this is a real "nothing is planned", not a failed read.)';++// Stable opening of the failed-read marker, so `hasPlannedWorkListing` can tell a+// sentinel from a real backlog listing without re-deriving the whole sentence.+export const PLANNED_WORK_UNAVAILABLE_PREFIX = 'Planned work could NOT be read';++// Jira labels can't contain spaces, and a ':' is unsafe on some Jira versions,+// so the Jira pause label swaps the ':' for a '-'. The base LI_LABEL is already+// Jira-safe (kebab, no colon) and is reused verbatim across all trackers.+export const LI_JIRA_BLOCKING_LABEL = 'layered-intelligence-blocking';++// Closed issues carrying a matching slug suppress a re-proposal for this long,+// so the loop doesn't immediately re-file something the user just resolved.+export const CLOSED_SUPPRESSION_MS = 30 * DAY;++// Cosine-similarity floor for the semantic (embedding) near-duplicate guard that+// layers atop the exact slug/label dedup. A proposal whose embedding is at least+// this close to an existing dedup-window issue is treated as the same work worded+// differently and suppressed. Deliberately conservative — only near-identical+// intent should trip it (768-dim local embeddings put genuine near-dups ≳0.9).+export const SEMANTIC_DEDUP_THRESHOLD = 0.9;++// Cap the number of existing issues embedded per run so a repo with a large LI+// backlog can't fan out into an unbounded embedding sweep. Open dedup-window+// issues should be few (the loop files ≤1/run), so this is a generous ceiling.+export const SEMANTIC_DEDUP_MAX_CANDIDATES = 50;++// The id of the RETIRED global autonomous-job that used to drive the whole loop+// (the cross-app sweep). Layered Intelligence is now a per-app handler-backed+// scheduled task (#2322), so this constant is kept ONLY so migration 184 can find+// and tombstone the legacy `data/cos/autonomous-jobs.json` record on installs that+// still carry it. Nothing dispatches on it anymore.+export const LI_JOB_ID = 'job-layered-intelligence';++// Every proposal scope the reasoner may return. The handler enforces WHERE each+// lands (see PROPOSAL_SCOPE_TARGETS) and gates meta/self scopes to PortOS only.+export const PROPOSAL_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];++// Scopes that may only be filed when the sweeping app IS the PortOS install+// itself (they extend / improve the loop, which lives in the PortOS repo).+export const PORTOS_ONLY_SCOPES = ['loop-meta', 'portos-self'];++// The reasoner's honest effort/risk estimate for a proposal. Only a `trivial`+// proposal is ever eligible for the optional Engine-A hand-off (below); anything+// unrecognized normalizes to null (unknown → not trivial → never auto-handed-off).+export const PROPOSAL_COMPLEXITIES = ['trivial', 'moderate', 'complex'];++// The single complexity level that (with `safe: true` and hand-off enabled)+// lets the loop enqueue a coding agent instead of only filing the issue.+export const HANDOFF_COMPLEXITY = 'trivial';++// Merge rate (as a %) below which computeOutcomesReport tells the reasoner its+// proposals are landing badly and points it at the plannedWork source (#2698).+// Measured over RESOLVED proposals only — see computeOutcomesReport.+export const LOW_MERGE_RATE_THRESHOLD = 20;++// Minimum RESOLVED proposals before the low-merge-rate alarm is allowed to fire.+// 0-of-1 and 0-of-50 are both "0%", but only the second is evidence: telling the+// loop its rate is "critically low" after a single early rejection biases it+// toward filing nothing, which is self-reinforcing — it can never earn a merge if+// it stops proposing. A rate needs a sample before it means anything.+export const LOW_MERGE_RATE_MIN_SAMPLE = 4;++// LI's SCHEDULE name (taskSchedule.js SELF_IMPROVEMENT_TASK_TYPES) — also the key+// the type-failure ledger uses. NOT the key its runs are recorded under.+export const LI_SCHEDULED_TASK_TYPE = 'layered-intelligence';++// The `learning.json` byTaskType key LI's own agent runs actually land under — the+// bucket computeSelfEvalSummary reads to judge whether the LI machinery ITSELF is+// healthy (as opposed to how its proposals fare downstream once filed).+//+// DERIVED, never restated: a scheduled LI task is generated with+// `metadata.analysisType = 'layered-intelligence'` (cosTaskGenerator's+// generateSelfImprovementTaskForType), and extractTaskType's FIRST branch turns any+// task carrying an analysisType into `self-improve:<type>` — so these runs are+// recorded under `self-improve:layered-intelligence`, not the bare schedule name.+// The bare name IS correct in two OTHER stores (the schedule map and the+// type-failure ledger), which makes this an easy and silent thing to get wrong:+// guessing it would leave the execution-health signal permanently reading "no LI+// runs recorded yet". Building the key with the same function the WRITER uses means+// it cannot drift out of sync with however task types are keyed later.+export const LI_TASK_TYPE = extractTaskType({ metadata: { analysisType: LI_SCHEDULED_TASK_TYPE } });++// LI-task success rate (%) below which selfEval reports the loop's own execution+// as DEGRADED (#2700) — a separate failure mode from a low merge rate: the merge+// rate says "the user rejects what I propose", this says "my own runs are+// failing". Kept at 50 (a coin flip) rather than the merge-rate's 20: a proposal+// being rejected is normal triage, an LI run outright failing is not.+export const LI_DEGRADED_SUCCESS_THRESHOLD = 50;++// Minimum recorded LI runs before the degraded-execution signal is allowed to+// fire, for the same reason as LOW_MERGE_RATE_MIN_SAMPLE: 0-of-1 and 0-of-50 are+// both "0%", but only the second is evidence. Below the floor the rate is+// reported as-is but is NOT treated as a confidence signal either way.+export const LI_DEGRADED_MIN_SAMPLE = 4;++// LI execution health (%) below which the deterministic HARD PRE-FILING EXCLUSION+// gate (#2824) arms. Distinct from LI_DEGRADED_SUCCESS_THRESHOLD (50 — the "your+// loop is failing, hold a higher bar" ADVISORY line surfaced to the reasoner): the+// hard gate does not advise, it SUPPRESSES filing, so it opens a WIDER, more cautious+// net. Once LI's own runs dip below three-quarters success it stops FILING self-+// directed work it demonstrably cannot see through, rather than merely being warned.+// Reuses the SCOPE_PREFER value (75) intentionally: the same "reliably executes" bar+// that marks a proposal DOMAIN preferable is the bar LI's own execution health must+// clear before it is trusted to file self-improvement work. The gate arms only on a+// CONFIDENT read (>= LI_DEGRADED_MIN_SAMPLE runs) — a cold loop is never locked out.+export const LI_HARD_GATE_EXECUTION_THRESHOLD = 75;++// The resolved outcomes a filed proposal can reach (the feedback loop, #2428).+// A record with a null outcome is still open/unresolved. All three are+// auto-derived from the tracker's closed state by deriveOutcome: completed →+// merged, not_planned → rejected, and any other PRESENT close reason+// (duplicate/stale/etc.) → abandoned (#2620); a reason-less close falls back+// to merged for trackers that report no stateReason.+export const PROPOSAL_OUTCOMES = ['merged', 'rejected', 'abandoned'];++// The EXECUTION outcomes an LI proposal reaches once it is handed off to a coding+// agent and that agent's run completes (#2765). Distinct from PROPOSAL_OUTCOMES+// (the FILING fate — did the issue get merged/closed): execution is "did LI's own+// coding agent successfully implement the proposal it filed". Only populated for+// proposals that took the Engine-A hand-off path (config.handoff.enabled + a+// trivial+safe proposal); a filed-but-never-handed-off proposal keeps a null+// executionOutcome. Environmental failures (rate-limit/outage) are NOT recorded —+// they say nothing about the proposal's domain (same gate as #2618).+export const PROPOSAL_EXECUTION_OUTCOMES = ['success', 'failure'];++// Minimum recorded executions before a proposal DOMAIN's success rate is trusted+// for the per-domain avoid/prefer split (#2765). Lower than SCOPE_AWARENESS_MIN_SAMPLE+// (3) because each data point here is a REAL, high-signal LI-proposal execution — not+// install-wide task-type telemetry that a proposal only loosely maps onto — and the+// hand-off path is rare, so a floor of 2 lets a genuine per-domain signal surface+// without letting a single fluke mint a list.+export const PROPOSAL_EXECUTION_MIN_SAMPLE = 2;++// Scope-awareness thresholds (#2760). LI's own execution data shows several CoS+// task-type scopes it consistently fails at (e.g. self-improve:layered-intelligence,+// branch-reconcile, accessibility all sit at 0%) while others succeed reliably+// (plan-task, test-coverage, performance at ~100%). Since an LI proposal is later+// EXECUTED as a CoS task, proposing work that maps to a chronically-failing scope is+// systematic waste. These bound a deterministic, self-clearing classifier+// (computeScopeAwareness) that surfaces the avoid/prefer split to the reasoner so it+// can steer proposals toward scopes that actually execute.+//+// A scope is "avoid" when its effective (recency-windowed-or-lifetime) success rate is+// below AVOID and it has enough completed runs to be evidence; "prefer" when at/above+// PREFER with the same sample floor. Reusing the degraded-execution boundary (50%) for+// AVOID keeps LI's two success signals — its own loop health and per-scope+// executability — on the same coin-flip line. The classification is recomputed from+// fresh metrics every run and keyed on the windowed rate (once the window clears the+// scheduler's own EFFECTIVE_RATE_MIN_WINDOW_SAMPLES floor), so an "avoid" scope+// self-clears once it recovers in-window — no persisted avoid-list to go stale (the+// issue's "dynamic adjustment" requirement). See computeScopeAwareness for why the+// windowed rate, not the near-permanent lifetime rate, is the right basis.+export const SCOPE_AVOID_SUCCESS_THRESHOLD = LI_DEGRADED_SUCCESS_THRESHOLD; // < 50% → avoid+export const SCOPE_PREFER_SUCCESS_THRESHOLD = 75; // >= 75% → prefer++// Minimum completed runs before a scope's rate is trusted for avoid/prefer, mirroring+// LI_DEGRADED_MIN_SAMPLE's rationale (0-of-1 and 0-of-50 are both "0%", only the+// second is evidence). Set to 3 per #2760 — one below the degraded floor because the+// prompt guidance is advisory (it steers the reasoner, it does not hard-suppress a+// proposal), so a slightly lower bar to surface the signal is acceptable.+export const SCOPE_AWARENESS_MIN_SAMPLE = 3;++// Prompt-size bounds for the scope-awareness block, so a long-lived install with many+// task types (mission task keys embed an unbounded mission name) can't render an+// oversized block — the raw cosMetrics source is already char-capped for the same+// reason. Cap the entries surfaced per list (the lists are sorted sharpest-first, so+// the cap keeps the most decision-relevant scopes) and truncate any single task-type+// name so one pathological key can't blow the budget.+export const SCOPE_AWARENESS_MAX_PER_LIST = 12;+export const SCOPE_AWARENESS_MAX_TYPE_LEN = 80;diff --git a/server/services/layeredIntelligence/dedup.js b/server/services/layeredIntelligence/dedup.jsnew file mode 100644index 0000000000..fd9a8f7435--- /dev/null+++ b/server/services/layeredIntelligence/dedup.js@@ -0,0 +1,133 @@+/**+ * Layered Intelligence — slug + duplicate detection (#2842 split of layeredIntelligence.js).+ *+ * The `[lil-<slug>]` marker vocabulary, the closed-issue suppression window, the+ * exact-slug dedup check, and the pure cosine-similarity half of semantic dedup.+ * Also the park check (`isAppParked`) that reads the blocking-label issues.+ */++import { CLOSED_SUPPRESSION_MS, SEMANTIC_DEDUP_THRESHOLD } from './constants.js';++/** The HTML-comment slug marker embedded in a filed issue/ticket body. */+export function slugMarker(slug) {+ return `<!-- lil-slug: ${slug} -->`;+}++/** Extract a `lil-slug` marker's value from a body string (null if absent). */+export function extractSlugFromBody(body) {+ if (typeof body !== 'string') return null;+ const m = body.match(/<!--\s*lil-slug:\s*([a-z0-9][a-z0-9-]*)\s*-->/i);+ return m ? m[1].toLowerCase() : null;+}++/**+ * Normalize a reasoner-chosen slug to a stable kebab id. Returns null for a+ * non-string or an input that reduces to empty (so a bad slug is a no-op, never+ * a mystery label).+ */+export function normalizeSlug(slug) {+ if (typeof slug !== 'string') return null;+ const norm = slug+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 80);+ return norm || null;+}++/**+ * Whether an existing tracker issue is still within the dedup suppression window:+ * OPEN, or CLOSED within CLOSED_SUPPRESSION_MS. Only a closed-long-ago issue+ * falls out of the window so its work can be re-proposed. A closed issue with a+ * missing/unparseable `closedAt` is PERMANENTLY in-window (suppressed): the main+ * producer of that shape is a checked `- [x]` PLAN.md item (checkboxes carry no+ * timestamp), and a completed plan item never needs re-proposal — treating it as+ * "closed long ago" made the reasoner re-propose every done item on every run+ * (#2620). A tracker row missing its close time (e.g. a jira Done ticket with no+ * resolutiondate) is likewise suppressed rather than re-proposed — done work is+ * never worth re-reasoning. Shared by both the slug dedup and the semantic dedup+ * so the two guards agree on which issues still count.+ */+export function isIssueWithinDedupWindow(issue, now = Date.now()) {+ if ((issue?.state || '').toLowerCase() === 'open') return true;+ const closedAt = issue?.closedAt ? Date.parse(issue.closedAt) : NaN;+ if (!Number.isFinite(closedAt)) return true;+ return now - closedAt <= CLOSED_SUPPRESSION_MS;+}++/**+ * Deterministic dedup guard. Given the slug of the proposed item and the live+ * tracker's existing issues (each `{ slug, state, closedAt }`), suppress the+ * proposal when a match is open, OR closed within CLOSED_SUPPRESSION_MS.+ *+ * `slug` matching is case-insensitive on the normalized slug. `existingIssues`+ * may carry either a parsed `slug` or a raw `body`/`title` we extract from.+ */+export function isProposalDuplicate({ slug, existingIssues = [], now = Date.now() }) {+ const target = normalizeSlug(slug);+ if (!target) return false;+ for (const issue of existingIssues) {+ const issueSlug = issue.slug+ ? normalizeSlug(issue.slug)+ : extractSlugFromBody(issue.body) || extractSlugFromBody(issue.title);+ if (issueSlug !== target) continue;+ if (isIssueWithinDedupWindow(issue, now)) return true;+ }+ return false;+}++/**+ * Build the text to embed for a proposal OR an existing issue — title + body,+ * trimmed and length-capped so a single huge body can't blow the embedding+ * model's context. Both sides go through THIS helper so the proposal and the+ * candidates are embedded from the same seed shape (a fair comparison).+ */+export function issueEmbedSeed({ title = '', body = '' } = {}) {+ const parts = [title, body].map(s => (typeof s === 'string' ? s.trim() : '')).filter(Boolean);+ return parts.join('\n\n').slice(0, 2000);+}++/** Cosine similarity of two equal-length numeric vectors. Returns 0 for a shape+ * mismatch, empty vector, or a zero-magnitude vector (nothing meaningful to+ * compare) rather than NaN, so a bad embedding can never trip the dedup guard. */+export function cosineSimilarity(a, b) {+ if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0;+ let dot = 0, na = 0, nb = 0;+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i];+ na += a[i] * a[i];+ nb += b[i] * b[i];+ }+ if (na === 0 || nb === 0) return 0;+ return dot / (Math.sqrt(na) * Math.sqrt(nb));+}++/**+ * Pure near-duplicate finder. Given the proposal's embedding and an array of+ * candidates (each `{ slug?, number?, title?, embedding }`), return the single+ * best candidate whose cosine similarity meets `threshold` (highest score wins),+ * or null when none qualify / the proposal embedding is unusable. Side-effect-free+ * and unit-tested; the I/O layer feeds it real embeddings.+ */+export function findSemanticDuplicate({ proposalEmbedding, candidates = [], threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {+ if (!Array.isArray(proposalEmbedding) || proposalEmbedding.length === 0) return null;+ let best = null;+ for (const c of candidates) {+ if (!Array.isArray(c?.embedding) || c.embedding.length === 0) continue;+ const score = cosineSimilarity(proposalEmbedding, c.embedding);+ if (score >= threshold && (!best || score > best.score)) {+ best = { slug: c.slug || null, number: c.number ?? null, title: c.title || '', score };+ }+ }+ return best;+}++/**+ * Whether the app is currently PARKED — i.e. has at least one OPEN blocking+ * issue. When parked, the sweep skips the app entirely (no gather, no reason),+ * resuming automatically once the blocking issue closes. Fully tracker-derived.+ */+export function isAppParked(blockingIssues = []) {+ return blockingIssues.some(i => (i.state || '').toLowerCase() === 'open');+}diff --git a/server/services/layeredIntelligence/forgeFiler.js b/server/services/layeredIntelligence/forgeFiler.jsnew file mode 100644index 0000000000..9156a15173--- /dev/null+++ b/server/services/layeredIntelligence/forgeFiler.js@@ -0,0 +1,272 @@+/**+ * Layered Intelligence — GitHub/GitLab forge filer (#2842 split of+ * layeredIntelligence.js). Lists/normalizes forge issues, resolves the+ * implementing PR + closing comment, and files/labels proposals through the+ * forge CLI (injectable `exec`).+ */++import { safeJSONParse } from '../../lib/fileUtils.js';+import { LI_LABEL, LI_BLOCKING_LABEL } from './constants.js';+import { slugMarker, extractSlugFromBody } from './dedup.js';+import { runCli } from './runCli.js';++/**+ * Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`+ * (and `closed`/`locked`); GitHub reports `open`/`closed`. Anything that isn't a+ * recognized closed/locked state is treated as open so dedup + park don't miss a+ * GitLab-`opened` issue. (`merged` never applies to issues.)+ */+export function normalizeIssueState(state) {+ const s = (state || '').toLowerCase();+ if (s === 'closed' || s === 'locked') return 'closed';+ return 'open';+}++/**+ * Normalize a forge issue's labels to a plain `string[]`. gh reports objects+ * (`[{ name, color, … }]`); glab reports bare strings. Anything unrecognized+ * drops out rather than rendering `[object Object]` into the reasoner's prompt.+ */+export function normalizeIssueLabels(raw) {+ if (!Array.isArray(raw)) return [];+ return raw+ .map(l => (typeof l === 'string' ? l : l?.name))+ .filter(l => typeof l === 'string' && l.trim())+ .map(l => l.trim());+}++/**+ * Best-effort priority read from an issue's labels — there is no cross-forge+ * priority field, so the common label conventions are matched instead:+ * `priority: high` / `priority/high`, `P0`–`P4`, and a bare+ * `critical|urgent|high|medium|low` (optionally suffixed `-priority`).+ *+ * Returns null when no label looks like a priority. Null means "this issue+ * carries no priority label", NOT "priority zero" — the renderer omits the field+ * entirely rather than inventing a default the tracker never asserted.+ */+export function extractIssuePriority(labels = []) {+ const re = /^(?:priority[:/\s-]+(.+)|p([0-4])|(critical|urgent|high|medium|low)(?:[\s-]priority)?)$/i;+ for (const label of normalizeIssueLabels(labels)) {+ const m = label.match(re);+ if (!m) continue;+ const value = m[1] ?? (m[2] != null ? `p${m[2]}` : m[3]);+ if (typeof value === 'string' && value.trim()) return value.trim().toLowerCase();+ }+ return null;+}++/**+ * List issues on a forge. Defaults to the layered-intelligence set (open ++ * recently closed) for the reasoner + dedup guard; `label`/`state` are+ * parameterized so the plannedWork source (#2698) can reuse the exact same+ * parse/normalize path for the `plan`-labeled committed backlog.+ *+ * Returns `{ ok, issues }` — `ok:false` means the tracker read FAILED (CLI error+ * or unparseable output), which is NOT the same as "no existing issues" (`ok:true,+ * issues:[]`). The handler must NOT file when the read failed, or a transient+ * `gh` blip would defeat dedup and file a duplicate (CLAUDE.md sentinel rule).+ */+export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state = 'all', exec = runCli } = {}) {+ // glab lists open issues by default and needs `--all` to widen to every state;+ // gh takes the state explicitly.+ const args = cli === 'glab'+ ? ['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100', '-F', 'json']+ : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences'];+ const { code, stdout } = await exec(cli, args, { cwd, env });+ if (code !== 0) return { ok: false, issues: [] };+ if (!stdout.trim()) return { ok: true, issues: [] };+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: parsed.map(i => ({+ number: i.number ?? i.iid ?? null,+ title: i.title || '',+ body: i.body || i.description || '',+ state: normalizeIssueState(i.state),+ // GitHub-only: 'completed' | 'not_planned' | 'reopened'. glab omits it, so+ // deriveOutcome falls back to treating any closed issue as merged.+ stateReason: i.stateReason || i.state_reason || null,+ closedAt: i.closedAt || i.closed_at || null,+ // gh reports `url`; glab reports `web_url`. Null when neither is present so+ // the overview's proposal links degrade to a plain count rather than a+ // dead href.+ url: i.url || i.web_url || null,+ labels: normalizeIssueLabels(i.labels),+ // The rejection classifier's last-resort signal (#2748): the prose a human+ // left when declining, for a close with no matching label/close-reason. gh+ // returns `comments` in the same batched list call (no extra fetch); glab's+ // `-F json` omits them, so its rows carry null and fall through to label/+ // stateReason only (tracked in the issue's Remaining).+ closingComment: extractClosingComment(i.comments),+ // The implementing-PR handle (#2748, deliverable 2): gh reports every PR that+ // closes/references this issue in `closedByPullRequestsReferences`. Additive+ // and null-defaulted — glab's `-F json` omits it, so its rows carry null and+ // fall through to the label/comment signals, and the reconciler only reads a+ // PR's state when it holds a number here. Scoped to the issue's own repo (parsed+ // from its url) so a cross-repo closing PR can't resolve to the wrong number.+ implementingPr: extractImplementingPr(i.closedByPullRequestsReferences, repoSlugFromUrl(i.url || i.web_url)),+ slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')+ }))+ };+}++/**+ * Parse an `owner/repo` slug (lower-cased for case-insensitive compare) from a GitHub+ * issue/PR URL — `https://HOST/owner/repo/(issues|pull)/N` — host-agnostic so it works+ * on github.com and Enterprise. Returns null when the shape doesn't match.+ */+export function repoSlugFromUrl(url) {+ if (typeof url !== 'string') return null;+ const m = url.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/(?:issues|pull)\/\d+/);+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;+}++/**+ * The `owner/repo` a `closedByPullRequestsReferences` entry belongs to — from its+ * structured `repository { owner { login }, name }`, falling back to parsing its `url`.+ * Null when neither is present. Lower-cased to match `repoSlugFromUrl`.+ */+function refRepoSlug(ref) {+ const owner = ref?.repository?.owner?.login;+ const name = ref?.repository?.name;+ if (typeof owner === 'string' && typeof name === 'string') return `${owner}/${name}`.toLowerCase();+ return repoSlugFromUrl(ref?.url);+}++/**+ * The number of the PR that implements a proposal, from gh's+ * `closedByPullRequestsReferences` (#2748, deliverable 2). Takes the LAST reference —+ * the most recent PR linked to the issue — and returns its number, or null when there+ * is none (glab, or an issue closed by hand). Pure.+ *+ * `selfRepo` (the issue's own `owner/repo`) scopes the match: the reconciler later runs+ * `gh pr view <number>` in the issue's checkout, so a reference from a DIFFERENT repo+ * (a cross-repo/fork PR that closed the issue) would resolve to the wrong PR number in+ * cwd's repo — or none — and mis-diagnose the rejection. So a ref whose repo is known+ * and differs from `selfRepo` is skipped. When `selfRepo` is unknown or a ref carries+ * no repo, it is accepted (same-repo is the overwhelmingly common case for an LI+ * proposal implemented in its own repo), preserving prior behavior.+ */+export function extractImplementingPr(refs, selfRepo = null) {+ if (!Array.isArray(refs)) return null;+ const self = typeof selfRepo === 'string' ? selfRepo.toLowerCase() : null;+ for (let i = refs.length - 1; i >= 0; i -= 1) {+ const n = refs[i]?.number;+ if (!Number.isInteger(n) || n <= 0) continue;+ const refRepo = refRepoSlug(refs[i]);+ if (self && refRepo && refRepo !== self) continue;+ return n;+ }+ return null;+}++/**+ * Read the merge state + check rollup of an implementing PR (#2748, deliverable 2),+ * so the rejection reconciler can classify `merge-conflict` / `validation-failed`.+ * gh-only (glab carries no PR handle) and bounded by the caller to the small set of+ * non-merged proposals that both hold a PR ref and were left undiagnosed by the free+ * signals — this is the ONE tracker fetch classification adds, and it never runs at+ * boot (only the scheduler-tick reconcile, gated behind `sources.outcomes`).+ * Returns `{ state, mergeStateStatus, statusCheckRollup }`, or null on any failure+ * (a null read simply leaves the proposal on its existing, honest fallback reason).+ */+export async function readImplementingPrState({ cli, cwd, env, number, exec = runCli } = {}) {+ if (cli !== 'gh' || !Number.isInteger(number)) return null;+ const { code, stdout } = await exec(cli, ['pr', 'view', String(number), '--json', 'state,mergeStateStatus,statusCheckRollup'], { cwd, env });+ if (code !== 0 || !stdout.trim()) return null;+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!parsed || typeof parsed !== 'object') return null;+ return {+ state: parsed.state ?? null,+ mergeStateStatus: parsed.mergeStateStatus ?? null,+ statusCheckRollup: Array.isArray(parsed.statusCheckRollup) ? parsed.statusCheckRollup : []+ };+}++/**+ * The rationale a human left when closing a proposal, for the rejection classifier+ * (#2748). gh returns issue comments oldest-first; the LAST non-empty one sits+ * closest to the close, so it carries the decline reason in the common case.+ * Returns null for an issue closed with no comment — there is nothing to classify.+ */+export function extractClosingComment(comments) {+ if (!Array.isArray(comments)) return null;+ for (let i = comments.length - 1; i >= 0; i -= 1) {+ const body = comments[i]?.body;+ if (typeof body === 'string' && body.trim()) return body;+ }+ return null;+}++/**+ * List OPEN blocking-labeled issues for the app (park check). Returns+ * `{ ok, issues }` with the same failed-vs-empty distinction as listForgeIssues.+ */+export async function listBlockingIssues({ cli, cwd, env, exec = runCli } = {}) {+ const args = cli === 'glab'+ ? ['issue', 'list', '--label', LI_BLOCKING_LABEL, '-P', '100', '-F', 'json']+ : ['issue', 'list', '--label', LI_BLOCKING_LABEL, '--state', 'open', '--limit', '100', '--json', 'number,title,state'];+ const { code, stdout } = await exec(cli, args, { cwd, env });+ if (code !== 0) return { ok: false, issues: [] };+ if (!stdout.trim()) return { ok: true, issues: [] };+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: parsed.map(i => ({+ number: i.number ?? i.iid ?? null,+ title: i.title || '',+ state: normalizeIssueState(i.state)+ }))+ };+}++/**+ * Ensure the layered-intelligence labels exist before the first `issue create`+ * (gh/glab both fail creating an issue with a non-existent label). Idempotent —+ * `--force` (gh) / re-create (glab) is a no-op when the label already exists.+ */+export async function ensureForgeLabels({ cli, cwd, env, exec = runCli } = {}) {+ const labels = [+ { name: LI_LABEL, color: '1d76db', desc: 'Filed by the Layered Intelligence loop' },+ { name: LI_BLOCKING_LABEL, color: 'b60205', desc: 'Layered Intelligence loop is paused on this issue' }+ ];+ for (const l of labels) {+ if (cli === 'glab') {+ await exec(cli, ['label', 'create', '--name', l.name, '--color', `#${l.color}`, '--description', l.desc], { cwd, env });+ } else {+ await exec(cli, ['label', 'create', l.name, '--color', l.color, '--description', l.desc, '--force'], { cwd, env });+ }+ }+}++/**+ * File ONE proposal issue on a forge (gh/glab). Ensures labels first, embeds the+ * slug marker in the body, and returns `{ success, number, url }`. The issue+ * number is parsed from the created URL's trailing digits.+ */+export async function fileProposalToForge({ cli, cwd, env, title, body, slug, exec = runCli } = {}) {+ await ensureForgeLabels({ cli, cwd, env, exec });+ const fullBody = `${body}\n\n${slugMarker(slug)}`;+ const args = cli === 'glab'+ ? ['issue', 'create', '--title', title, '--description', fullBody, '--label', LI_LABEL]+ : ['issue', 'create', '--title', title, '--body', fullBody, '--label', LI_LABEL];+ const { code, stdout, stderr } = await exec(cli, args, { cwd, env });+ if (code !== 0) return { success: false, error: stderr || `${cli} exited with code ${code}` };+ const urlMatch = stdout.trim().match(/(https?:\/\/\S+)/);+ const url = urlMatch ? urlMatch[1] : stdout.trim();+ const numMatch = url.match(/(\d+)\s*$/);+ return { success: true, number: numMatch ? Number(numMatch[1]) : null, url };+}++/** Apply the blocking label to an existing issue (pause). Returns `{ success }`. */+export async function applyBlockingLabel({ cli, cwd, env, number, exec = runCli } = {}) {+ if (!Number.isInteger(number)) return { success: false, error: 'no issue number' };+ const args = cli === 'glab'+ ? ['issue', 'update', String(number), '--label', LI_BLOCKING_LABEL]+ : ['issue', 'edit', String(number), '--add-label', LI_BLOCKING_LABEL];+ const { code, stderr } = await exec(cli, args, { cwd, env });+ return code === 0 ? { success: true } : { success: false, error: stderr };+}diff --git a/server/services/layeredIntelligence/gates.js b/server/services/layeredIntelligence/gates.jsnew file mode 100644index 0000000000..be0010eae5--- /dev/null+++ b/server/services/layeredIntelligence/gates.js@@ -0,0 +1,119 @@+/**+ * Layered Intelligence — hard pre-filing exclusion gate (#2824)+ * (#2842 split of layeredIntelligence.js).+ */++import { PORTOS_ONLY_SCOPES, LI_HARD_GATE_EXECUTION_THRESHOLD } from './constants.js';+import { computeLiExecutionHealth } from './outcomes.js';+import { computeExecutionByDomain, isAvoidDomain, formatDominantFailureCause, clampScopeLabel } from './awareness.js';++// The proposal scopes treated as LI "self-improve" work by the hard exclusion gate+// (#2824): the PortOS-only meta/self scopes. These are the proposals that improve LI /+// PortOS itself and execute under self-improve:* task types — the exact execution class+// whose chronic failure motivated the gate. Reuses PORTOS_ONLY_SCOPES as the single+// definition so "self-improve scope" can never drift from "the PortOS-only scopes".+export const SELF_IMPROVE_SCOPES = PORTOS_ONLY_SCOPES;++/**+ * Deterministic HARD PRE-FILING EXCLUSION gate (#2824). Given a validated proposal,+ * LI's own execution-health stats, and the app's outcome records, decides whether the+ * proposal must be SUPPRESSED before it is ever filed — because LI's own execution is+ * degraded and the proposal maps to work LI cannot see through. This is the SYSTEM-side+ * enforcement of the exclusion the reasoner is merely WARNED about in the prompt notice+ * (computeHardExclusionNotice): even when the reasoner "wants" to file, this gate drops+ * the proposal to null.+ *+ * Pure + side-effect-free like the sibling compute* gates. Two independent exclusion+ * rules, both ARMED only when LI's execution health is CONFIDENTLY below+ * LI_HARD_GATE_EXECUTION_THRESHOLD (75%) — unknown or below-sample-floor health leaves+ * the gate DISARMED, so a cold loop with no track record is never locked out:+ * 1. Self-improve scope — any proposal in a SELF_IMPROVE_SCOPES scope (loop-meta /+ * portos-self) is excluded regardless of domain. A degraded loop cannot repair+ * itself; that work is deferred to a human.+ * 2. Chronically-failing domain — a proposal whose OWN scope's hand-offs chronically+ * fail (the SAME isAvoidDomain classifier the hand-off gate + reasoner avoid list+ * use, so all three agree on which domains qualify) is excluded from FILING, not+ * just from auto-hand-off.+ *+ * @param {object} args+ * @param {object} args.proposal - the validated proposal ({ scope, ... }).+ * @param {{ read: boolean, metrics: Object|null }|null} [args.liTaskStats] - readLiTaskMetrics output.+ * @param {Array} [args.outcomes] - the app's li-outcomes records (for rule 2's domain lookup).+ * @param {number} [args.now] - clock seam for the effective-rate window.+ * @returns {{ excluded: boolean, reason: string|null, rule?: 'self-improve-scope'|'failing-domain' }}+ */+export function computeHardExclusionGate({ proposal, liTaskStats = null, outcomes = [], now = Date.now() } = {}) {+ if (!proposal || typeof proposal !== 'object') return { excluded: false, reason: null };++ // The gate is ARMED only on a confident read of degraded execution health. Unknown+ // health (store unreadable / no runs) or a below-floor sample disarms it — the same+ // 0-of-1-vs-0-of-N reasoning as LI_DEGRADED_MIN_SAMPLE. A healthy loop (>= 75%) files+ // exactly as before this gate existed.+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) {+ return { excluded: false, reason: null };+ }++ const scope = typeof proposal.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;+ const healthClause = `LI execution health ${health.rate}% (< ${LI_HARD_GATE_EXECUTION_THRESHOLD}%)`;++ // Rule 1: self-improve scope — excluded wholesale while armed.+ if (scope && SELF_IMPROVE_SCOPES.includes(scope)) {+ return {+ excluded: true,+ rule: 'self-improve-scope',+ reason: `${healthClause} — self-improve-scoped proposals (${scope}) are excluded while the loop's own runs are failing; a degraded loop cannot repair itself, so this is deferred to a human`+ };+ }++ // Rule 2: chronically-failing execution domain — same isAvoidDomain classifier the+ // hand-off routing gate uses, so a domain on the reasoner's avoid list is the same+ // set the gate blocks. Only reached for non-self-improve scopes with a scope present.+ if (scope) {+ const bucket = computeExecutionByDomain(outcomes)[scope];+ if (isAvoidDomain(bucket)) {+ const cause = formatDominantFailureCause(bucket.failureSummary);+ return {+ excluded: true,+ rule: 'failing-domain',+ reason: `${healthClause} and ${scope} hand-offs succeed only ${bucket.successRate}% over ${bucket.completed} executed — excluded from filing${cause ? ` (${cause})` : ''}`+ };+ }+ }++ return { excluded: false, reason: null };+}++/**+ * Render the reasoner-facing HARD EXCLUSION notice block (#2824). Computed from the+ * SAME health + outcome inputs the enforcement gate (computeHardExclusionGate) reads,+ * so the prompt's stated exclusions and what the gate actually suppresses can never+ * disagree. Returns '' when the gate is DISARMED (health unknown, below sample floor,+ * or at/above the threshold), so buildPrompt omits the block entirely on a healthy loop.+ * Names both the self-improve scopes and any currently chronically-failing domain, and+ * carries the explicit GATE CHECK step the reasoner must run before committing.+ */+export function computeHardExclusionNotice({ liTaskStats = null, outcomes = [], now = Date.now() } = {}) {+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) return '';++ const lines = [+ `HARD EXCLUSION GATE ARMED — your execution health is ${health.rate}% (below ${LI_HARD_GATE_EXECUTION_THRESHOLD}%). The following work is EXCLUDED this run and will be dropped BEFORE filing even if your reasoning leads you to it:`,+ `- Any self-improve-scoped proposal (${SELF_IMPROVE_SCOPES.join(', ')}). A degraded loop cannot repair itself — that work is deferred to a human.`+ ];++ // Surface each currently chronically-failing domain by name so the reasoner can route+ // around it explicitly — the same isAvoidDomain set rule 2 of the gate enforces. Skip+ // any self-improve scope already named in the bullet above (gate rule 1 short-circuits+ // rule 2 for those) so the notice never lists the same scope twice.+ const byDomain = computeExecutionByDomain(outcomes);+ const failing = Object.entries(byDomain)+ .filter(([scope, bucket]) => isAvoidDomain(bucket) && !SELF_IMPROVE_SCOPES.includes(scope))+ .map(([scope, bucket]) => `${clampScopeLabel(scope)} (${bucket.successRate}% over ${bucket.completed})`);+ if (failing.length) {+ lines.push(`- Any proposal in a chronically-failing execution domain: ${failing.join('; ')}.`);+ }++ lines.push('', 'GATE CHECK: If your proposal maps to an excluded scope or domain above → return proposal: null. Do not reason past this gate.');+ return lines.join('\n');+}diff --git a/server/services/layeredIntelligence/jiraFiler.js b/server/services/layeredIntelligence/jiraFiler.jsnew file mode 100644index 0000000000..754f910b4c--- /dev/null+++ b/server/services/layeredIntelligence/jiraFiler.js@@ -0,0 +1,146 @@+/**+ * Layered Intelligence — Jira filer (#2842 split of layeredIntelligence.js).+ *+ * Jira has no forge CLI — it goes through the PortOS Jira REST service+ * (server/services/jira.js). Dedup + pause are label-based (same as the forges)+ * via JQL, with the slug marker embedded in the ticket description. The Jira deps+ * (search/create/addLabel) are injectable so tests drive the dispatch without a+ * live Jira instance.+ */++import { createTicket, searchIssues, addLabels, escapeJql } from '../jira.js';+import { LI_LABEL, PLANNED_WORK_LABEL, LI_JIRA_BLOCKING_LABEL } from './constants.js';+import { slugMarker, extractSlugFromBody } from './dedup.js';+import { normalizeIssueLabels } from './forgeFiler.js';++// ---------------------------------------------------------------------------+// Jira filer. Jira has no forge CLI — it goes through the PortOS Jira REST+// service (server/services/jira.js). Dedup + pause are label-based (same as the+// forges) via JQL, with the slug marker embedded in the ticket description.+// The Jira deps (search/create/addLabel) are injectable so tests drive the+// dispatch without a live Jira instance.+// ---------------------------------------------------------------------------++/**+ * Normalize a Jira status CATEGORY to `open` / `closed`. Jira's three canonical+ * categories are "To Do" / "In Progress" / "Done"; only "Done" counts as closed+ * for dedup + park. Anything unrecognized is treated as open so a custom+ * in-flight status can't slip past dedup.+ */+export function normalizeJiraState(statusCategory) {+ return (statusCategory || '').toLowerCase() === 'done' ? 'closed' : 'open';+}++/**+ * List existing layered-intelligence tickets in a Jira project (open + recently+ * closed) for the reasoner + dedup guard. Mirrors listForgeIssues' `{ ok, issues }`+ * failed-vs-empty contract: a thrown search is `ok:false` (do NOT file — a blind+ * dedup would duplicate); an empty result is `ok:true, issues:[]`.+ */+export async function listJiraIssues({ instanceId, projectKey, jql, searchOptions, search = searchIssues } = {}) {+ if (!instanceId || !projectKey) return { ok: false, issues: [] };+ // `jql` lets the plannedWork source (#2698) reuse this parse path for the+ // prioritized backlog; absent, it's the layered-intelligence label set.+ const query = jql || `project = "${escapeJql(projectKey)}" AND labels = "${LI_LABEL}" ORDER BY updated DESC`;+ const rows = searchOptions+ ? await search(instanceId, query, searchOptions).then(r => r, () => null)+ : await search(instanceId, query).then(r => r, () => null);+ if (!Array.isArray(rows)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: rows.map(i => ({+ number: i.key || null,+ title: i.summary || '',+ body: i.description || '',+ state: normalizeJiraState(i.statusCategory),+ closedAt: i.resolutiondate || null,+ labels: normalizeIssueLabels(i.labels),+ // Jira DOES have a real priority field (unlike the forges) — but only when+ // the caller asked searchIssues for it. Absent → null → the renderer omits+ // it, rather than a fabricated default.+ priority: typeof i.priority === 'string' && i.priority.trim() ? i.priority.trim() : null,+ slug: extractSlugFromBody(i.description || '') || extractSlugFromBody(i.summary || '')+ }))+ };+}++/**+ * The JQL for a Jira project's committed backlog (#2698): `plan`-labeled tickets+ * that aren't Done, highest priority first.+ *+ * The label filter is NOT optional — it is what makes this source mean the same+ * thing on Jira as on a forge. Without it the query returns every open ticket,+ * i.e. the untriaged backlog nobody has committed to (plus LI's own past+ * proposals), which would then render under a header asserting the user+ * "already committed to" them and instruct the reasoner to suppress against+ * essentially the whole tracker — and duplicate the `openIssues` source besides.+ * A project that doesn't use the label reports a truthful "nothing planned"+ * rather than a backlog-shaped lie.+ *+ * Deliberately NOT `sprint in openSprints()` — the Sprint field only exists on+ * Scrum-board-backed projects, and JQL referencing an absent field is a hard 400+ * rather than an empty result, which would make gatherPlannedWork report+ * "unavailable" forever on every Kanban/basic project. `labels` exists on every+ * project shape. Priority is an ORDER BY rather than a filter for the same+ * reason: priority NAMES are scheme-specific (a project can rename or drop+ * "Highest"), so filtering on them risks the same permanent-400.+ */+export function plannedWorkJql(projectKey) {+ return `project = "${escapeJql(projectKey)}" AND labels = "${PLANNED_WORK_LABEL}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`;+}++/**+ * List OPEN blocking-labeled Jira tickets for the app (park check). `{ ok, issues }`+ * with the same failed-vs-empty distinction. JQL filters out Done so a resolved+ * blocking ticket un-parks the app automatically (matching the forge pause model).+ */+export async function listJiraBlockingIssues({ instanceId, projectKey, search = searchIssues } = {}) {+ if (!instanceId || !projectKey) return { ok: false, issues: [] };+ const jql = `project = "${escapeJql(projectKey)}" AND labels = "${LI_JIRA_BLOCKING_LABEL}" AND statusCategory != Done ORDER BY updated DESC`;+ const rows = await search(instanceId, jql).then(r => r, () => null);+ if (!Array.isArray(rows)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: rows.map(i => ({ number: i.key || null, title: i.summary || '', state: normalizeJiraState(i.statusCategory) }))+ };+}++/**+ * File ONE proposal ticket in a Jira project. Embeds the slug marker in the+ * description (searchable for dedup) and tags it with the layered-intelligence+ * label. Returns `{ success, key, url }` — Jira issues are keyed strings+ * (`PROJ-123`), not integers, so the handler resolves pause targets by key.+ */+export async function fileProposalToJira({ instanceId, projectKey, issueType = 'Task', title, body, slug, create = createTicket } = {}) {+ if (!instanceId || !projectKey) return { success: false, error: 'jira instance/project not configured' };+ const description = `${body}\n\n${slugMarker(slug)}`;+ const res = await create(instanceId, {+ projectKey,+ summary: title,+ description,+ issueType,+ labels: [LI_LABEL]+ }).then(r => r, (err) => ({ success: false, error: err?.message || 'jira create failed' }));+ if (!res?.success) return { success: false, error: res?.error || 'jira create failed' };+ return { success: true, key: res.ticketId || null, url: res.url || null };+}++/**+ * Resolve a Jira pause target to a concrete issue KEY. `"this"` → the just-filed+ * ticket's key; an integer → `<projectKey>-<n>` (a pre-existing ticket in the+ * same project). Returns null when it can't resolve (e.g. `"this"` but nothing+ * was filed, or no project key for an integer target).+ */+export function resolveJiraBlockKey(pause, filedKey, projectKey) {+ if (!pause) return null;+ if (pause.blockOnIssue === 'this') return filedKey || null;+ if (Number.isInteger(pause.blockOnIssue) && projectKey) return `${projectKey}-${pause.blockOnIssue}`;+ return null;+}++/** Apply the Jira blocking label to an existing ticket (pause). Returns `{ success }`. */+export async function applyJiraBlockingLabel({ instanceId, key, addLabel = addLabels } = {}) {+ if (!instanceId || !key) return { success: false, error: 'no jira ticket key' };+ const res = await addLabel(instanceId, key, [LI_JIRA_BLOCKING_LABEL]).then(r => r, (err) => ({ success: false, error: err?.message }));+ return res?.success ? { success: true } : { success: false, error: res?.error || 'jira label failed' };+}diff --git a/server/services/layeredIntelligence/outcomes.js b/server/services/layeredIntelligence/outcomes.jsnew file mode 100644index 0000000000..f44394a491--- /dev/null+++ b/server/services/layeredIntelligence/outcomes.js@@ -0,0 +1,421 @@+/**+ * Layered Intelligence — proposal outcomes & self-evaluation reports+ * (#2842 split of layeredIntelligence.js).+ *+ * Derives merged/rejected/abandoned outcomes from closed tracker issues, rolls them+ * into the merge-rate report fed back into the next prompt, and builds the+ * self-eval summary (suppressed issues, rejection reasons, LI execution health).+ */++import { DAY } from '../../lib/fileUtils.js';+import { computeEffectiveSuccessRate } from '../taskLearning/store.js';+import { formatRejectionReasons, formatRejectionReason, REJECTION_REASONS } from '../layeredIntelligenceRejections.js';+import { formatExecutionFailures } from '../layeredIntelligenceExecutionFailures.js';+import {+ LOW_MERGE_RATE_MIN_SAMPLE, LOW_MERGE_RATE_THRESHOLD, LI_DEGRADED_MIN_SAMPLE,+ LI_DEGRADED_SUCCESS_THRESHOLD, LI_HARD_GATE_EXECUTION_THRESHOLD, CLOSED_SUPPRESSION_MS,+} from './constants.js';+import { normalizeSlug, extractSlugFromBody, isIssueWithinDedupWindow } from './dedup.js';++/**+ * Derive a resolved outcome for a filed proposal from its live tracker issue.+ * Pure — the reconciler feeds it a `{ state, stateReason, closedAt }` issue:+ * - still open (or unknown state) → null (unresolved)+ * - closed as "completed" → 'merged'+ * - closed as "not planned" → 'rejected'+ * - closed with any OTHER reason → 'abandoned' (duplicate/stale/etc. —+ * counting these as merged inflated the+ * merge-rate calibration signal, #2620)+ * - closed with NO reason → 'merged' (graceful fallback: glab/jira+ * and the plan filer report no stateReason,+ * and their common close path IS a merge —+ * absent ≠ other, per the sentinel rule)+ * GitHub reports `stateReason` ('completed' | 'not_planned' | 'reopened' | …);+ * other trackers omit it, so a bare closed issue reads as merged.+ */+export function deriveOutcome(issue) {+ if ((issue?.state || '').toLowerCase() !== 'closed') return null;+ const reason = (issue?.stateReason || '').toLowerCase().replace(/[\s-]+/g, '_');+ if (reason === 'not_planned') return 'rejected';+ if (reason === '' || reason === 'completed') return 'merged';+ return 'abandoned';+}++/**+ * Tally a recorded-outcome list into the counts BOTH the outcomes report (#2428)+ * and the self-eval summary (#2700) reason over. Pure; the single place the+ * merge-rate math lives so the two blocks can never disagree about LI's record.+ *+ * `rawMergeRate` is measured over RESOLVED proposals only and is `null` when+ * nothing has resolved yet — the sentinel rule: "no proposal has been judged" must+ * not collapse into the same 0 as "every judged proposal was rejected". Callers+ * round only for display (rounding before a threshold compare would let 19.6%+ * read as 20% and suppress a warning that should fire).+ */+export function summarizeOutcomeStats(outcomes = []) {+ const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');+ const total = filed.length;+ const count = (name) => filed.filter(o => o.outcome === name).length;+ const merged = count('merged');+ const rejected = count('rejected');+ const abandoned = count('abandoned');+ const resolved = merged + rejected + abandoned;+ return {+ filed,+ total,+ merged,+ rejected,+ abandoned,+ // Anything filed but not yet resolved — still awaiting triage, NOT a failure.+ pending: total - resolved,+ resolved,+ rawMergeRate: resolved > 0 ? (merged / resolved) * 100 : null+ };+}++/**+ * Format the LI outcome-feedback report (#2428) from this app's recorded+ * proposals + their reconciled outcomes. Pure + side-effect-free: the LI hook+ * loads the outcomes and passes them here, then feeds the string into buildPrompt.+ * Returns '' when there's nothing to report (no filed history) so the caller omits+ * the block entirely rather than injecting an empty section.+ */+export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false } = {}) {+ const { filed, total, merged, rejected, abandoned, pending, resolved, rawMergeRate } =+ summarizeOutcomeStats(outcomes);+ if (total === 0) return '';+ const pct = (n) => Math.round((n / total) * 100);++ // Per-scope merge rate — the calibration signal the reasoner acts on.+ const scopes = new Map();+ for (const o of filed) {+ const s = o.scope || 'unknown';+ const agg = scopes.get(s) || { filed: 0, merged: 0 };+ agg.filed += 1;+ if (o.outcome === 'merged') agg.merged += 1;+ scopes.set(s, agg);+ }+ const scopeLines = [...scopes.entries()]+ .sort((a, b) => b[1].filed - a[1].filed)+ .map(([s, v]) => `- ${s}: ${v.filed} filed, ${v.merged} merged (${v.filed ? Math.round((v.merged / v.filed) * 100) : 0}%)`)+ .join('\n');++ // Structured diagnosis of every non-merged proposal (#2689), replacing the raw+ // tracker string this used to echo ('not_planned' merely restated the outcome).+ // '' when nothing has been closed unmerged — distinct from "closed, reason+ // unknown", which the line reports explicitly.+ const rejectionReasons = formatRejectionReasons(filed, 5);++ // Structured diagnosis of every FAILED hand-off (#2764 §1) — the "why" behind the+ // per-domain execution rate the liProposalExecution block reports (#2765). '' when+ // no hand-off has failed, so the line below is omitted rather than contradicting a+ // clean execution record.+ const executionFailures = formatExecutionFailures(filed, 5);++ // Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED+ // proposals only and is null when none have resolved — see summarizeOutcomeStats+ // for the sentinel rationale (pending ≠ rejected). A null rate stays silent+ // rather than alarming an app whose first proposal is simply still in flight.+ // The sample floor is the same idea one step further out: 0-of-1 is not evidence.+ const lowMergeWarning = (+ rawMergeRate !== null+ && resolved >= LOW_MERGE_RATE_MIN_SAMPLE+ && rawMergeRate < LOW_MERGE_RATE_THRESHOLD+ )+ ? [+ '',+ `WARNING: your merge rate is critically low — only ${merged} of ${resolved} resolved proposals (${Math.round(rawMergeRate)}%) were merged.`,+ // Only point at the plannedWork block when one was actually gathered — the+ // source is per-app-toggleable and yields nothing on an unresolvable+ // tracker, and citing a section that isn't in the prompt is just noise.+ hasPlannedWork+ ? 'Review the "plannedWork" source above: your proposals may be overlapping with work the user has already committed to. Propose only work that is clearly outside that committed backlog — and if you cannot find any, return proposal: null rather than filing something marginal.'+ : 'Your proposals may be overlapping with work the user has already committed to, or missing what they actually value. Hold a higher bar: return proposal: null rather than filing something marginal.'+ ]+ : [];++ return [+ 'Recent LI proposals (all still-open, plus outcomes resolved within ~30 days):',+ `- Total filed: ${total}`,+ `- Merged/implemented: ${merged} (${pct(merged)}%)`,+ `- Rejected: ${rejected} (${pct(rejected)}%)`,+ `- Abandoned: ${abandoned} (${pct(abandoned)}%)`,+ `- Still open: ${pending} (${pct(pending)}%)`,+ '',+ 'By scope:',+ scopeLines || '- (none)',+ '',+ `Why non-merged proposals were closed: ${rejectionReasons || 'nothing has been closed unmerged yet'}`,+ // Only emit the execution-failure line when a hand-off has actually failed —+ // an app whose proposals were never handed off (or all succeeded) shows nothing+ // here rather than a misleading "no failures" line.+ ...(executionFailures ? [`Why LI's own hand-offs failed when implemented: ${executionFailures}`] : []),+ ...lowMergeWarning+ ].join('\n');+}++// How many closed-but-still-suppressed proposals selfEval names before it+// summarizes the rest as a count. The block is a calibration aid, not a backlog+// dump — an unbounded list would crowd out the sources it exists to be weighed+// against, and past this many the reasoner has the pattern anyway.+export const SELF_EVAL_MAX_SUPPRESSED_LISTED = 8;++/**+ * Recover a suppressed issue's normalized dedup slug — the key the reasoner must+ * avoid re-using and the join key onto the outcome store's rejectionReason. Shapes+ * vary by tracker: forge/jira rows carry `{ number, title, body }` (the slug lives+ * in the body marker), while the `plan` filer yields bare `{ slug, state }`.+ * Normalized both ways so the value matches the outcome record's stored slug+ * (`normalizeSlug(slug)` at file time) exactly. Returns null when unrecoverable.+ */+export function suppressedIssueSlug(issue) {+ if (issue?.slug) return normalizeSlug(issue.slug);+ return normalizeSlug(extractSlugFromBody(issue?.body) || extractSlugFromBody(issue?.title));+}++/**+ * Build a `slug → rejectionReason` lookup from reconciled outcome records, so the+ * self-eval "recently closed" line can tell the reasoner not just WHICH proposals+ * to avoid but WHY each was closed — the feedback loop of #2689 (ask #4), closing+ * the loop with the taxonomy #2735 already persists rather than any new signal.+ *+ * Only a RESOLVED non-merged record carries a diagnosis, and only a REAL taxonomy+ * token (a member of REJECTION_REASONS) counts: a merged, unresolved, or+ * still-unclassified (`rejectionReason == null`) record contributes nothing, and so+ * does the `unknown-reason` SENTINEL — it means "we looked and found no signal",+ * which is not an actionable failure pattern to route around, so annotating a+ * suppressed proposal with "closed with no recorded reason" would add noise the+ * reasoner can't act on (and would contradict the promise that undiagnosed closures+ * stay unannotated). The annotation therefore appears only where a concrete reason+ * explains the closure. First diagnosed record per slug wins (records arrive+ * newest-filed-first). Pure.+ */+export function rejectionReasonBySlug(outcomes = []) {+ const map = new Map();+ for (const o of Array.isArray(outcomes) ? outcomes : []) {+ if (!o || (o.outcome !== 'rejected' && o.outcome !== 'abandoned')) continue;+ if (!REJECTION_REASONS.includes(o.rejectionReason)) continue;+ const slug = normalizeSlug(o.slug);+ if (slug && !map.has(slug)) map.set(slug, o.rejectionReason);+ }+ return map;+}++/**+ * Identify a suppressed proposal for the prompt: its slug (the actual dedup key the+ * reasoner must avoid re-using) plus its title for human-readable context. Returns+ * null when neither is recoverable — an unidentifiable entry is left to the count+ * rather than rendered as a mystery bullet the reasoner can't act on.+ *+ * When `reasonBySlug` (from rejectionReasonBySlug) holds this slug's diagnosis, it+ * is appended as glossed prose so the reasoner sees the specific failure pattern+ * that sank the earlier proposal (#2689), not merely a slug to route around. An+ * undiagnosed (null) or unmatched slug renders exactly as before.+ */+export function describeSuppressedIssue(issue, reasonBySlug = null) {+ const slug = suppressedIssueSlug(issue);+ const title = typeof issue?.title === 'string' ? issue.title.trim() : '';+ if (!slug && !title) return null;+ const ref = issue?.number ? `#${issue.number} ` : '';+ const reason = slug && reasonBySlug instanceof Map ? reasonBySlug.get(slug) : null;+ const why = reason ? ` — previously closed: ${formatRejectionReason(reason)}` : '';+ if (!slug) return `${ref}${title}${why}`.trim();+ return `${ref}[${slug}]${title ? ` ${title}` : ''}${why}`.trim();+}++/**+ * Format LI's self-evaluation block (#2700) — the loop's pre-filing quality check+ * on its OWN reasoning. Pure + side-effect-free and NO LLM call: every line is+ * derived from data the loop already has, so this never adds a provider round-trip+ * (the "no cold-bootstrap LLM calls" policy). The hook loads the inputs and feeds+ * the string to buildPrompt, exactly like computeOutcomesReport.+ *+ * Three independent self-signals, each of which is either PRESENT or explicitly+ * reported ABSENT — never silently defaulted, because "I have no data about myself"+ * and "the data says I am doing badly" demand opposite responses from the reasoner:+ * 1. Proposal merge rate — do the user's triage decisions validate my picks?+ * 2. Already-filed proposals — what have I said already that I must not repeat?+ * 3. LI execution health — are my own agent runs even succeeding?+ *+ * Unlike computeOutcomesReport this ALWAYS returns a block when called: "you are+ * reasoning with no signal about yourself, hold a higher bar" is the single most+ * useful thing to tell a cold loop, so an empty-handed run is exactly when the+ * block matters most.+ *+ * @param {Object} args+ * @param {Array|null} args.outcomes - recorded proposals; `null` = NOT gathered+ * (source off / outcomes-incapable tracker), `[]` = gathered and genuinely none.+ * @param {Array|null} args.existingIssues - LI-labeled tracker issues; `null` = the+ * tracker read FAILED or never ran, `[]` = read fine and LI has filed nothing.+ * The caller MUST pass null on a failed read: readIssues returns `[]` for a blown+ * read, which would otherwise read as "nothing filed" and license a re-file.+ * @param {{ read: boolean, metrics: Object|null }|null} args.liTaskStats - from+ * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;+ * `read:true, metrics:null` = read fine and LI has simply never run a task.+ * @param {number} [args.now] - clock seam for the suppression window.+ * @returns {string} the liSelfEval block body.+ */+/**+ * Resolve LI's own EXECUTION HEALTH — the loop's reasoning-run success rate — into a+ * single structured read, so every consumer (the selfEval Signal 3 line AND the hard+ * exclusion gate, #2824) judges LI's health off the SAME number instead of each+ * re-deriving it and risking drift. Reads the LI-task metrics bucket+ * (readLiTaskMetrics) through the effective (recency-windowed-or-lifetime) success+ * rate, exactly as Signal 3 did inline.+ *+ * @param {{ read: boolean, metrics: Object|null }|null} liTaskStats - from+ * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;+ * `read:true, metrics:null` = read fine and LI has simply never run a task.+ * @param {{ now?: number }} [opts] - clock seam forwarded to computeEffectiveSuccessRate.+ * @returns {{ rate: number|null, sample: number, source: string|null, confident: boolean }}+ * `rate` is null when health is UNKNOWN (store unreadable, no runs, or no completed+ * runs). `confident` is true only at >= LI_DEGRADED_MIN_SAMPLE runs — the floor+ * below which a rate (0-of-1 vs 0-of-N) is not yet evidence.+ */+export function computeLiExecutionHealth(liTaskStats = null, { now = Date.now() } = {}) {+ if (!liTaskStats?.read || !liTaskStats.metrics) {+ return { rate: null, sample: 0, source: null, confident: false };+ }+ const { successRate, source, windowedCompleted } = computeEffectiveSuccessRate(liTaskStats.metrics, { now });+ if (successRate === null) return { rate: null, sample: 0, source: null, confident: false };+ const sample = source === 'windowed' ? windowedCompleted : (liTaskStats.metrics.completed || 0);+ return { rate: successRate, sample, source, confident: sample >= LI_DEGRADED_MIN_SAMPLE };+}++export function computeSelfEvalSummary({+ outcomes = null,+ existingIssues = null,+ liTaskStats = null,+ now = Date.now()+} = {}) {+ const lines = [];++ // --- Signal 1: does the user actually merge what I propose? -----------------+ let mergeSignal = false;+ if (!Array.isArray(outcomes)) {+ lines.push('- Proposal merge rate: UNAVAILABLE — no outcome history was gathered this run (the outcomes source is off, or this tracker cannot report outcomes). You cannot see how your past proposals fared; do not assume they went well.');+ } else {+ const { total, merged, resolved, rawMergeRate, filed } = summarizeOutcomeStats(outcomes);+ if (total === 0) {+ lines.push('- Proposal merge rate: no proposals filed yet for this app — you have no track record here to calibrate against.');+ } else if (rawMergeRate === null) {+ lines.push(`- Proposal merge rate: ${total} filed, none resolved yet — rate unknown. Awaiting triage is NOT rejection; do not read this as failure.`);+ } else {+ mergeSignal = resolved >= LOW_MERGE_RATE_MIN_SAMPLE;+ // Same structured diagnosis as computeOutcomesReport (#2689) — one helper, so+ // the two blocks can never disagree about why proposals were closed. Gated on+ // the formatted string, not on `rejected`, because an `abandoned` proposal is+ // also a non-merge worth explaining.+ const reasons = formatRejectionReasons(filed, 3);+ lines.push(+ `- Proposal merge rate: ${merged} of ${resolved} resolved proposals merged (${Math.round(rawMergeRate)}%)`+ + `${resolved < LOW_MERGE_RATE_MIN_SAMPLE ? ' — too small a sample to read a rate from yet' : ''}.`+ + (reasons ? ` Why the rest were closed: ${reasons}.` : '')+ );+ }+ }++ // --- Signal 2: what have I already said? (dedup awareness) ------------------+ let trackerSignal = false;+ if (!Array.isArray(existingIssues)) {+ lines.push('- Your already-filed proposals: UNKNOWN — the tracker could not be read this run. You may be about to re-file something that already exists; hold a higher bar than usual.');+ } else {+ trackerSignal = true;+ const open = existingIssues.filter(i => (i?.state || '').toLowerCase() === 'open');+ // Closed but still inside the 30-day suppression window: re-proposing one of+ // these gets deterministically dropped downstream, so spending the run on it is+ // a wasted run. Surfaced so the reasoner can route around it BEFORE proposing.+ const closedSuppressed = existingIssues.filter(i =>+ (i?.state || '').toLowerCase() !== 'open' && isIssueWithinDedupWindow(i, now));+ lines.push(+ `- Your already-filed proposals: ${open.length} open`+ + `${closedSuppressed.length ? `, plus ${closedSuppressed.length} closed but still within the ${Math.round(CLOSED_SUPPRESSION_MS / DAY)}-day suppression window` : ''}.`+ + ` ${open.length + closedSuppressed.length+ ? 'Re-proposing any of these is deterministically suppressed — the run is wasted. Propose something genuinely new.'+ : 'Nothing is currently suppressed.'}`+ );+ // NAME the closed-but-suppressed ones. The open proposals are already listed in+ // full elsewhere in the prompt, but a closed issue appears NOWHERE else — so+ // without this the reasoner is told a number it cannot act on and can burn the+ // whole run re-proposing something the dedup guard silently drops. Capped so a+ // long tail can't crowd out the sources it is meant to be reasoning about.+ if (closedSuppressed.length) {+ // Join each suppressed proposal to its reconciled rejection reason (#2689),+ // so the "do NOT re-propose" line also carries WHY each was closed — a+ // no-extra-cost read of the outcome records selfEval already received. Empty+ // when outcomes weren't gathered this run (`outcomes` not an array), leaving+ // the line exactly as before.+ const reasonBySlug = rejectionReasonBySlug(Array.isArray(outcomes) ? outcomes : []);+ const named = closedSuppressed+ .map(i => describeSuppressedIssue(i, reasonBySlug))+ .filter(Boolean)+ .slice(0, SELF_EVAL_MAX_SUPPRESSED_LISTED);+ if (named.length) {+ lines.push(+ ` Recently closed (do NOT re-propose): ${named.join('; ')}`+ + `${closedSuppressed.length > named.length ? ` (+${closedSuppressed.length - named.length} more)` : ''}`+ );+ }+ }+ }++ // --- Signal 3: is the LI machinery itself healthy? --------------------------+ // Deliberately GLOBAL, not per-app: the learning store keys LI runs by task type+ // alone, so this bucket aggregates the loop's runs across every app. That is the+ // right scope for the question being asked — "is the LI machinery working?" is a+ // property of the shared loop, not of the app it happens to be pointed at — and+ // it mirrors the cosMetrics source, which is likewise install-wide.+ let taskSignal = false;+ let liDegraded = false;+ if (!liTaskStats?.read) {+ lines.push('- LI execution health: UNAVAILABLE — the CoS learning store could not be read.');+ } else if (!liTaskStats.metrics) {+ lines.push('- LI execution health: no LI runs recorded yet — this loop has no execution history.');+ } else {+ // Forward the clock seam via the shared helper (computeLiExecutionHealth), which+ // the hard exclusion gate (#2824) reads too — so the DEGRADED line and the gate can+ // never disagree about LI's own success rate. Without `now` computeEffectiveSuccessRate+ // would read the real wall clock while the suppression-window branch above uses the+ // injected one — the same summary reasoning against two different "nows".+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (health.rate === null) {+ lines.push('- LI execution health: no completed LI runs recorded yet — success rate unknown.');+ } else {+ taskSignal = health.confident;+ liDegraded = taskSignal && health.rate < LI_DEGRADED_SUCCESS_THRESHOLD;+ lines.push(+ `- LI execution health: ${health.rate}% of ${health.sample} ${health.source} LI runs succeeded`+ + `${taskSignal ? '' : ' — too small a sample to judge'}${liDegraded ? ' — DEGRADED' : ''}.`+ );+ }+ }++ // --- Confidence: how much do I actually know about myself? ------------------+ // Purely a count of PRESENT signals — it rates the evidence available to the+ // reasoner, NOT whether that evidence is flattering. A loop with a well-measured+ // 0% merge rate has HIGH confidence in a bad result, which is precisely the state+ // where it should act decisively rather than hedge.+ const signalCount = [mergeSignal, trackerSignal, taskSignal].filter(Boolean).length;+ const confidence = signalCount >= 3 ? 'high' : signalCount === 2 ? 'medium' : 'low';++ const guidance = [];+ if (confidence === 'low') {+ guidance.push(+ '',+ `GUIDANCE — low self-confidence (${signalCount} of 3 self-signals available): you are reasoning about this app with little evidence about your own track record. Do NOT compensate by proposing something speculative or sweeping. Prefer a small, concretely-grounded proposal you can justify from the gathered sources alone, and return proposal: null rather than filing a guess.`+ );+ }+ if (liDegraded) {+ guidance.push(+ '',+ `GUIDANCE — your own execution is degraded (LI run success is under ${LI_DEGRADED_SUCCESS_THRESHOLD}%): the problem may be THIS LOOP, not the app. Favor a narrowly-scoped, low-risk app-improvement / app-data-gap proposal that a coding agent can finish, and do not mark anything trivial+safe for hand-off while your runs are failing this often. Self-improve-scoped work (loop-meta / portos-self) is HARD-EXCLUDED while your execution health is below ${LI_HARD_GATE_EXECUTION_THRESHOLD}% (#2824): a degraded loop cannot repair itself, so that work is deferred to a human — return proposal: null rather than filing it.`+ );+ }++ return [+ 'LI self-evaluation (deterministic — computed from this loop\'s own record, not a model\'s opinion):',+ `- Reasoning confidence: ${confidence} (${signalCount} of 3 self-signals available)`,+ ...lines,+ ...guidance+ ].join('\n');+}diff --git a/server/services/layeredIntelligence/planFiler.js b/server/services/layeredIntelligence/planFiler.jsnew file mode 100644index 0000000000..25dc9c58d9--- /dev/null+++ b/server/services/layeredIntelligence/planFiler.js@@ -0,0 +1,73 @@+/**+ * Layered Intelligence — PLAN.md filer (#2842 split of layeredIntelligence.js).+ * The tracker path for apps with no issue tracker: slug-tagged checklist items+ * appended under `## Next Up`.+ */++import { join } from 'path';+import { existsSync } from 'fs';+import { readFile, writeFile, appendFile } from 'fs/promises';++/**+ * Append a slug-tagged proposal to the app's PLAN.md (the `plan` tracker path).+ * Dedups by scanning for the `[lil-<slug>]` tag. Creates PLAN.md with a heading+ * + `## Next Up` section if absent. Returns `{ success, duplicate }`.+ */+export async function appendProposalToPlan({ repoPath, appName, slug, title, body } = {}) {+ const planPath = join(repoPath, 'PLAN.md');+ const tag = `[lil-${slug}]`;+ const existing = existsSync(planPath) ? await readFile(planPath, 'utf-8').catch(() => '') : '';+ if (existing.includes(tag)) return { success: true, duplicate: true };++ const oneLine = (body || '').replace(/\s+/g, ' ').trim().slice(0, 500);+ const item = `- [ ] ${tag} **${title}** ${oneLine}`.trim();++ if (!existing) {+ const content = `# ${appName} — Development Plan\n\n## Next Up\n\n${item}\n`;+ await writeFile(planPath, content);+ return { success: true, duplicate: false };+ }+ const nextUpRe = /(##\s+Next Up[^\n]*)(\n?)/;+ if (nextUpRe.test(existing)) {+ // Insert right after the "## Next Up" heading line, normalizing the heading's+ // line ending first so a file that ENDS at `## Next Up` (no trailing newline)+ // gets the item on its own line rather than a second section appended below.+ const updated = existing.replace(nextUpRe, `$1\n${item}\n`);+ await writeFile(planPath, updated.endsWith('\n') ? updated : `${updated}\n`);+ return { success: true, duplicate: false };+ }+ // No Next Up section — append one.+ const sep = existing.endsWith('\n') ? '' : '\n';+ await appendFile(planPath, `${sep}\n## Next Up\n\n${item}\n`);+ return { success: true, duplicate: false };+}++/**+ * Scan a PLAN.md string for `[lil-<slug>]` tags → array of `{ slug, state }`.+ * Preserves each tag's list-item checkbox so the outcome loop (#2435) can+ * reconcile a completed PLAN proposal: `- [x] [lil-foo]` reads as `closed`,+ * `- [ ] [lil-foo]` as `open`.+ *+ * Absent ≠ done (the CLAUDE.md sentinel rule): a bare tag with NO preceding+ * checkbox stays `open` (still tracked/suppressed) rather than collapsing to+ * `closed` — a missing checkbox must not silently make an item re-proposable.+ * A `closed` item carries no `closedAt` (PLAN.md checkboxes have no timestamp),+ * which `isIssueWithinDedupWindow` treats as permanently in-window → a completed+ * proposal stays suppressed forever instead of being re-reasoned every run (#2620).+ */+export function extractPlanSlugs(planContent) {+ if (typeof planContent !== 'string') return [];+ const items = [];+ // Alt 1: a list item `- [ ]`/`- [x]` whose line also carries the tag (state+ // from the checkbox char). Alt 2: a bare tag with no checkbox (state 'open').+ const re = /^[ \t]*[-*][ \t]*\[([ xX])\][^\n]*?\[lil-([a-z0-9][a-z0-9-]*)\]|\[lil-([a-z0-9][a-z0-9-]*)\]/gim;+ let m;+ while ((m = re.exec(planContent))) {+ if (m[2]) {+ items.push({ slug: m[2].toLowerCase(), state: m[1].toLowerCase() === 'x' ? 'closed' : 'open' });+ } else {+ items.push({ slug: m[3].toLowerCase(), state: 'open' });+ }+ }+ return items;+}diff --git a/server/services/layeredIntelligence/prompt.js b/server/services/layeredIntelligence/prompt.jsnew file mode 100644index 0000000000..f7fbbc6593--- /dev/null+++ b/server/services/layeredIntelligence/prompt.js@@ -0,0 +1,178 @@+/**+ * Layered Intelligence — reasoning-prompt assembly+ * (#2842 split of layeredIntelligence.js).+ *+ * Deterministic: given the gathered sources, open issues and config, produces the+ * exact JSON-only string sent to the reasoning model.+ */++import { PLANNED_WORK_GUIDANCE, LI_PROPOSAL_PLAYBOOK, LI_PLAYBOOK_GUIDANCE } from './constants.js';+import { isScopeAllowed } from './config.js';+import { extractSlugFromBody } from './dedup.js';++// Source keys that buildPrompt renders as their OWN dedicated block (with tailored+// guidance) instead of dumping into the generic "### <key>\n<value>" source list.+// Keeping them in one named set — rather than accreting `&& k !== 'x'` clauses on the+// filter — documents WHY these keys are special and gives the next dedicated-block+// signal a single edit point.+const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);++/**+ * Build the JSON-only reasoning prompt for one app. Deterministic: given the+ * gathered sources, open issues, and config, produces the exact string sent to+ * the model. Meta/self scopes are only offered when the app is PortOS.+ * `outcomesReport` (from computeOutcomesReport) is injected as a `liOutcomes`+ * block with calibration guidance when non-empty (#2428). `selfEvalReport` (from+ * computeSelfEvalSummary) is injected as a `liSelfEval` block the same way (#2700).+ * `sources.scopeGuidance` (from computeScopeAwareness) is injected as a+ * `liScopeAwareness` block the same way (#2760). `proposalExecutionReport` (from+ * computeProposalExecutionAwareness) is injected as a `liProposalExecution` block —+ * the TRUE per-proposal-domain execution record #2760 could only approximate (#2765).+ * `crossReferenceReport` (from computeCrossReferenceAnalysis) is injected as a+ * `liCrossReference` block that names domains LI proposes well but executes poorly (#2764 §3).+ * `hardExclusionNotice` (from computeHardExclusionNotice, #2824) is injected as a+ * prominent `liHardExclusions` block ABOVE the allowed scopes when LI's execution+ * health is degraded — the reasoner-facing mirror of the deterministic filing gate.+ * Finally, the static `liPlaybook` block (LI_PROPOSAL_PLAYBOOK, #2763) is ALWAYS+ * appended: the a-priori scope/task-type/goal rule set LI needs from run one, before+ * any per-app outcome data exists.+ */+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '', crossReferenceReport = '', hardExclusionNotice = '' }) {+ const allowed = (config.allowedScopes || []).filter(s =>+ isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos })+ );+ const scopeLines = allowed.map(s => ` - ${s}`).join('\n');+ // plannedWork renders as its OWN block (below) rather than inside the generic+ // source list, so the cross-reference guidance is guaranteed to sit directly+ // under the committed backlog it refers to instead of drifting to wherever+ // object key order happens to put it.+ const sourceBlocks = Object.entries(sources)+ .filter(([k]) => !BESPOKE_SOURCE_BLOCK_KEYS.has(k))+ .filter(([, v]) => typeof v === 'string' && v.trim())+ .map(([k, v]) => `### ${k}\n${v.trim()}`)+ .join('\n\n');+ const openList = openIssues.length+ ? openIssues.map(i => `- #${i.number ?? '?'} [${i.slug || extractSlugFromBody(i.body) || 'no-slug'}] ${i.title || ''}`).join('\n')+ : '(none)';++ // Nudge a managed app with no own-performance signal (no METRICS.md gathered)+ // toward adding one, so future runs can judge real performance. PortOS is exempt+ // — it measures itself through cosMetrics. Also gate on the source being ENABLED:+ // if the user deliberately turned appMetrics off, a METRICS.md may well exist, so+ // "add a METRICS.md" would be a misleading (and possibly redundant) proposal.+ const hasAppMetrics = Boolean(typeof sources.appMetrics === 'string' && sources.appMetrics.trim());+ const appMetricsEnabled = config.sources?.appMetrics !== false;+ const metricsGuidance = (!isPortos && appMetricsEnabled && !hasAppMetrics)+ ? '\nThis app exposes no own-performance metrics yet (no METRICS.md). If you lack the data to judge how it is doing against its goals, a high-value app-data-gap proposal is to add a METRICS.md documenting how the app measures success — its user-success/KPI signals and where its production telemetry or data lives — so future runs can reason about real performance.\n'+ : '';++ const handoffNote = config.handoff?.enabled+ ? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first. Note: even a trivial+safe proposal is filed for a human (not auto-handed-off) when it falls in a domain where LI\'s own past hand-offs chronically fail, so prefer to narrow such a proposal to a slice an agent can actually finish.\n'+ : '';++ // The committed backlog (#2698) + the instruction to check against it. Emitted+ // whenever gatherPlannedWork produced ANY string — including its explicit+ // "could not be read" marker, which must still reach the reasoner: silently+ // dropping an unavailable read would look identical to "this app has nothing+ // planned" and license a proposal straight into committed work.+ const plannedWorkBlock = (typeof sources.plannedWork === 'string' && sources.plannedWork.trim())+ ? `\n### plannedWork\n${sources.plannedWork.trim()}\n\n${PLANNED_WORK_GUIDANCE}\n`+ : '';++ // Feedback loop (#2428): show the reasoner how its own past proposals fared so+ // it can calibrate scope/merge-rate instead of proposing in a vacuum.+ const outcomesBlock = (typeof outcomesReport === 'string' && outcomesReport.trim())+ ? `\n### liOutcomes\n${outcomesReport.trim()}\n\nUse this data to calibrate your proposal: prefer scopes with higher merge rates, avoid patterns that were repeatedly rejected, and consider that lower-merge scopes may need more justification.\n`+ : '';++ // Self-evaluation (#2700): the loop's own quality check BEFORE it files, so it+ // can decline instead of learning only from a later rejection. Carries its own+ // low-confidence / degraded-execution guidance (computeSelfEvalSummary), which is+ // why no extra instruction sentence is appended here — the block is self-contained+ // and its guidance is conditional on what the signals actually say.+ const selfEvalBlock = (typeof selfEvalReport === 'string' && selfEvalReport.trim())+ ? `\n### liSelfEval\n${selfEvalReport.trim()}\n\nWeigh this against the sources above before you commit to a proposal. Filing nothing (proposal: null) is a legitimate, and sometimes the correct, outcome — a marginal issue costs the user triage time and lowers your merge rate further.\n`+ : '';++ // Scope-awareness (#2760): install-wide completion rates by CoS task TYPE — directional+ // context for how reliably different KINDS of work get finished here. PortOS-only+ // (codex P2): these rates are this install's own CoS execution history, meaningless to+ // a managed app, so the block is gated on isPortos even if a managed app enabled the+ // cosMetrics source. It is context, not a rule (codex P1): a proposal does not map 1:1+ // onto a listed type, so treat a low-completion type as a reason for extra scrutiny /+ // a narrower scope, not a hard veto.+ const scopeGuidanceBlock = (isPortos && typeof sources.scopeGuidance === 'string' && sources.scopeGuidance.trim())+ ? `\n### liScopeAwareness\n${sources.scopeGuidance.trim()}\n\nThese are per-task-type completion rates for THIS install — how reliably each KIND of work tends to get finished, not a per-proposal record (your proposals don't map 1:1 onto these types). Use it as directional context: a proposal whose implementation resembles a low-completion type deserves extra scrutiny or a narrower scope; high-completion kinds are safer bets. A low rate on self-improve:layered-intelligence is LI's OWN reasoning-run rate — a direct signal to propose conservatively. Where the liProposalExecution block below covers a domain, prefer it: it is a direct per-proposal record, whereas these buckets are only directional.\n`+ : '';++ // Per-proposal-domain execution record (#2765): unlike liScopeAwareness above —+ // which borrows install-wide per-task-TYPE rates a proposal only loosely maps onto —+ // this keys on how LI's OWN proposals in each domain actually fared once handed off+ // and executed. It carries NO "directional only" caveat because the mapping is real,+ // so it is the authoritative avoid/prefer signal wherever it has data. The report is+ // pre-gated on the outcomes source by the caller (built from the same records), so no+ // isPortos re-check here — the block simply renders when execution history exists.+ const proposalExecutionBlock = (typeof proposalExecutionReport === 'string' && proposalExecutionReport.trim())+ ? `\n### liProposalExecution\n${proposalExecutionReport.trim()}\n\nThis is a DIRECT record of how LI's own proposals in each domain fared once implemented — not directional context. Favor domains LI executes reliably; for a low-execution domain, either narrow the proposal to a slice an agent can finish or justify why it is still the highest-value work despite the track record.\n`+ : '';++ // Cross-reference (#2764 §3): the CONTRAST liOutcomes and liProposalExecution can't+ // show on their own — a domain LI proposes well (merges) but executes poorly (its+ // hand-offs fail with a named cause). It carries its own actionable guidance in the+ // header, so no extra instruction sentence is appended. Gated on the outcomes source+ // by the caller (built from the same records), so no isPortos re-check here.+ const crossReferenceBlock = (typeof crossReferenceReport === 'string' && crossReferenceReport.trim())+ ? `\n### liCrossReference\n${crossReferenceReport.trim()}\n`+ : '';++ // Proposal Playbook (#2763): the STANDING, a-priori rule set — always rendered.+ // Unlike the data blocks above (which appear only once enough per-app outcome data+ // accumulates), the playbook is the guidance LI needs from run one, when it would+ // otherwise be proposing blind. It sits last so it is the freshest instruction+ // before the JSON contract, and its guidance sentence defers to any live data block+ // above that has real numbers contradicting a general rule.+ const playbookBlock = LI_PROPOSAL_PLAYBOOK+ ? `\n### liPlaybook\n${LI_PROPOSAL_PLAYBOOK}\n\n${LI_PLAYBOOK_GUIDANCE}\n`+ : '';++ // Hard exclusion gate (#2824): rendered ABOVE the allowed scopes and sources as a+ // hard constraint so the reasoner sees what is off-limits before it picks a scope.+ // Non-empty only when the deterministic filing gate is armed (execution health+ // degraded), so a healthy loop's prompt is unchanged. Even if the reasoner reasons+ // past this, computeHardExclusionGate drops the proposal before it is filed.+ const hardExclusionBlock = (typeof hardExclusionNotice === 'string' && hardExclusionNotice.trim())+ ? `\n### liHardExclusions\n${hardExclusionNotice.trim()}\n`+ : '';++ return `You are the Layered Intelligence reasoner for the app "${app.name}". Your job is to evaluate how THIS app is performing against its OWN goals and purpose${isPortos ? '' : ', not how well PortOS\'s tooling manages it'}. Decide the SINGLE highest-value improvement to propose this run (signal, not noise), grounded in the app's own goals and its own performance metrics (user success, KPIs, production telemetry). You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.+${handoffNote}${metricsGuidance}${hardExclusionBlock}+Rules & guidance from the operator:+${config.rules?.trim() || '(none)'}++Allowed proposal scopes (you MUST pick one of these for any proposal):+${scopeLines || ' (none — return proposal: null)'}+${isPortos ? '' : 'Note: meta/self scopes are unavailable on this app; frame any data need as an "app-data-gap" against this app.\n'}+Already-open tracked issues (DO NOT duplicate these — reuse their slug only if genuinely the same work):+${openList}++Gathered sources:+${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}+${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${scopeGuidanceBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}+Respond with JSON only (no markdown fences):+{+ "analysis": "brief reasoning summary",+ "proposal": { // null if nothing worth filing this run+ "scope": "<one allowed scope>",+ "slug": "kebab-stable-id",+ "title": "short imperative title",+ "body": "markdown detail for the coding agent",+ "value": "why this is the single highest-value item now",+ "complexity": "trivial | moderate | complex", // honest effort/risk estimate+ "safe": false // true ONLY if a coding agent could implement it end-to-end with no regression/data-loss risk+ },+ "pause": { // null if not pausing+ "blockOnIssue": "this" or <existing issue number>,+ "reason": "why the loop should pause on this app until resolved"+ }+}`;+}diff --git a/server/services/layeredIntelligence/proposal.js b/server/services/layeredIntelligence/proposal.jsnew file mode 100644index 0000000000..be6f7fdbc2--- /dev/null+++ b/server/services/layeredIntelligence/proposal.js@@ -0,0 +1,161 @@+/**+ * Layered Intelligence — reasoner-output validation & hand-off shaping+ * (#2842 split of layeredIntelligence.js).+ *+ * Validates the model's JSON into a `{ analysis, proposal, pause }` triple, resolves+ * the pause target, and decides whether/how a filed proposal becomes an autonomous+ * CoS hand-off task. Also the tracker→filer dispatch table.+ */++import { PROPOSAL_SCOPES, PROPOSAL_COMPLEXITIES, HANDOFF_COMPLEXITY } from './constants.js';+import { normalizeSlug } from './dedup.js';++/**+ * Validate + normalize the reasoner's JSON. Returns+ * `{ analysis, proposal, pause }` with invalid pieces dropped (never throws):+ * - `proposal` kept only when it has a recognized scope + a normalizable slug+ * + a non-empty title. `slug` is normalized in place.+ * - `pause` kept only when it has a reason AND a resolvable target: an integer+ * issue number, or `"this"` WITH a surviving proposal to block on. A+ * `pause.blockOnIssue: "this"` with a null proposal is invalid → dropped.+ */+export function validateReasonerResponse(parsed) {+ const out = { analysis: '', proposal: null, pause: null };+ if (!parsed || typeof parsed !== 'object') return out;+ if (typeof parsed.analysis === 'string') out.analysis = parsed.analysis;++ const p = parsed.proposal;+ if (p && typeof p === 'object' && !Array.isArray(p)) {+ const slug = normalizeSlug(p.slug);+ const title = typeof p.title === 'string' ? p.title.trim() : '';+ if (PROPOSAL_SCOPES.includes(p.scope) && slug && title) {+ out.proposal = {+ scope: p.scope,+ slug,+ title,+ body: typeof p.body === 'string' ? p.body : '',+ value: typeof p.value === 'string' ? p.value : '',+ // Hand-off signals. `complexity` normalizes to a known level or null+ // (unknown → never trivial → never auto-handed-off); `safe` is a strict+ // boolean so only an explicit `true` opens the hand-off path.+ complexity: PROPOSAL_COMPLEXITIES.includes(p.complexity) ? p.complexity : null,+ safe: p.safe === true+ };+ }+ }++ const pause = parsed.pause;+ if (pause && typeof pause === 'object' && !Array.isArray(pause)) {+ const reason = typeof pause.reason === 'string' ? pause.reason.trim() : '';+ const target = pause.blockOnIssue;+ const isThis = target === 'this';+ const num = Number.isInteger(target) ? target : (typeof target === 'string' && /^\d+$/.test(target) ? Number(target) : null);+ // "this" requires a surviving proposal to block on; else an explicit issue number.+ if (reason && ((isThis && out.proposal) || num)) {+ out.pause = { blockOnIssue: isThis ? 'this' : num, reason };+ }+ }+ return out;+}++/**+ * Resolve `pause.blockOnIssue` to a concrete issue number. `"this"` maps to the+ * number of the issue just filed from the proposal; an integer passes through.+ * Returns null when it can't resolve (e.g. `"this"` but nothing was filed).+ */+export function resolveBlockOnIssue(pause, filedIssueNumber) {+ if (!pause) return null;+ if (pause.blockOnIssue === 'this') return filedIssueNumber ?? null;+ return Number.isInteger(pause.blockOnIssue) ? pause.blockOnIssue : null;+}++/**+ * Whether a filed proposal qualifies for the optional Engine-A hand-off — i.e.+ * the loop should enqueue a coding agent to implement it now, not just file it.+ * Requires ALL of: hand-off enabled in the app's config, an issue actually filed+ * (a concrete `filed` ref for the agent to work), and the reasoner marking the+ * proposal both trivial AND safe. Any missing/false signal falls through to+ * file-only. Pure — the handler feeds it the filed ref.+ */+export function isHandoffEligible({ proposal, config, filed } = {}) {+ if (filed == null || filed === '' || filed === false) return false;+ if (!config?.handoff?.enabled) return false;+ if (!proposal || typeof proposal !== 'object') return false;+ return proposal.complexity === HANDOFF_COMPLEXITY && proposal.safe === true;+}++/**+ * Build the CoS task payload that hands a filed proposal to an Engine-A coding+ * agent. Deterministic (no I/O) so it's unit-tested; the handler passes the+ * result to `addTask(..., 'internal')`. The task is APPROVAL-GATED — an agent+ * writing code straight from the loop shouldn't run unattended (mirrors+ * autoFixer's every code-editing task). The description leads with a stable+ * `LI hand-off:` prefix so addTask's per-app dedup suppresses a re-enqueue while+ * the same proposal's task is still pending/in-flight.+ */+export function buildHandoffTask({ app, proposal, issueRef, recordExecution = false } = {}) {+ const ref = typeof issueRef === 'number' ? `#${issueRef}` : String(issueRef ?? '').trim();+ const context = [+ '# Layered Intelligence hand-off',+ '',+ `The Layered Intelligence loop identified a TRIVIAL, SAFE improvement for **${app?.name || app?.id || 'this app'}** and filed it as ${ref}.`,+ '',+ '## Task',+ `Implement the change described in ${ref} end-to-end: read the issue, make the fix, run the app's tests, and open a PR that closes ${ref}.`,+ 'If — once you dig in — the change turns out to be non-trivial or carries any regression/data-loss risk, STOP and leave a comment on the issue explaining why instead of forcing it. Filing was the safe fallback; a half-done risky change is worse than none.',+ '',+ '## Proposal',+ `- **Title:** ${proposal?.title || ''}`,+ `- **Value:** ${proposal?.value || '(not provided)'}`,+ '',+ proposal?.body || ''+ ].join('\n');+ const task = {+ description: `LI hand-off: ${proposal?.title || ref}`,+ priority: 'MEDIUM',+ context,+ app: app?.id,+ approvalRequired: true+ };+ // Per-proposal-domain execution tracking (#2765): stamp the proposal's identity ++ // domain onto the task so, when this agent run completes, recordTaskCompletion can+ // attribute the execution success/failure back to the proposal's DOMAIN (not the+ // generic `internal-task` bucket this hand-off would otherwise land in). addTask+ // allowlists this top-level field into `metadata.liProposal`, and registerAgent+ // projects it onto `agent.metadata.taskLiProposal`. Kept a dedicated key (not any of+ // the extractTaskType-recognized metadata fields) so it never reclassifies the task's+ // own byTaskType bucket.+ //+ // Gated on `recordExecution` — the caller passes true ONLY when the outcomes source is+ // on AND the tracker is outcomes-capable, the SAME gate that governs recordFiledProposal.+ // Without this, a hand-off filed while outcomes-tracking is OFF would still carry the+ // marker, and recordProposalExecution's missing-record fallback would create an outcome+ // row — recording a proposal the source toggle says isn't tracked (codex P2). Omitting+ // the marker keeps filing and execution-recording consistent with the one toggle.+ if (recordExecution) {+ task.liProposal = {+ appId: app?.id ?? null,+ slug: proposal?.slug ?? null,+ scope: proposal?.scope ?? null+ };+ }+ return task;+}++/**+ * Which filing path a resolved work tracker uses. Branches the handler up front+ * so a `plan` app never hits the forge-only label/issue paths.+ * github / gitlab → 'forge' (gh / glab issue create + labels)+ * jira → 'jira' (createTicket + description slug marker)+ * plan (fallback) → 'plan' (append slug-tagged PLAN.md checklist item)+ */+export function filerForTracker(resolved) {+ if (resolved === 'github' || resolved === 'gitlab') return 'forge';+ if (resolved === 'jira') return 'jira';+ return 'plan';+}++/** Whether a resolved tracker supports pause (an issue to block on). `plan` doesn't. */+export function trackerSupportsPause(resolved) {+ return filerForTracker(resolved) !== 'plan';+}diff --git a/server/services/layeredIntelligence/runCli.js b/server/services/layeredIntelligence/runCli.jsnew file mode 100644index 0000000000..7919322222--- /dev/null+++ b/server/services/layeredIntelligence/runCli.js@@ -0,0 +1,19 @@+/**+ * Layered Intelligence — shared CLI spawn primitive (#2842 split of+ * layeredIntelligence.js). Its own module so the source gatherer and the forge+ * filer can both use it without an import cycle.+ */++import { spawn } from 'child_process';++/** Run a CLI, resolving `{ code, stdout, stderr }` (never rejects). */+export function runCli(cmd, args, options = {}) {+ return new Promise((resolve) => {+ const child = spawn(cmd, args, { shell: false, windowsHide: true, ...options });+ let stdout = '', stderr = '';+ child.stdout?.on('data', d => { stdout += d.toString(); });+ child.stderr?.on('data', d => { stderr += d.toString(); });+ child.on('close', code => resolve({ code, stdout, stderr }));+ child.on('error', err => resolve({ code: -1, stdout: '', stderr: err.message }));+ });+}diff --git a/server/services/layeredIntelligence/semanticDedup.js b/server/services/layeredIntelligence/semanticDedup.jsnew file mode 100644index 0000000000..745a575a85--- /dev/null+++ b/server/services/layeredIntelligence/semanticDedup.js@@ -0,0 +1,70 @@+/**+ * Layered Intelligence — embedding-backed semantic dedup (#2842 split of+ * layeredIntelligence.js). The I/O half of `./dedup.js`'s pure cosine helpers:+ * lazily resolves the embedder and scores a proposal against recent issues.+ */++import { SEMANTIC_DEDUP_THRESHOLD, SEMANTIC_DEDUP_MAX_CANDIDATES } from './constants.js';+import { isIssueWithinDedupWindow, issueEmbedSeed, findSemanticDuplicate } from './dedup.js';++/** Lazily resolve the default embedder so the pure module doesn't statically pull+ * in the embeddings/settings/provider graph (matches the handler's dynamic-import+ * pattern for heavy deps). Only reached in production — tests inject `embed`. */+async function defaultEmbed(text) {+ const { embedText } = await import('../embeddings.js');+ return embedText(text);+}++/**+ * SEMANTIC dedup guard — the embedding-similarity layer ON TOP OF the exact+ * slug/label dedup (`isProposalDuplicate`). Catches a proposal that describes the+ * same work as an existing issue but was worded differently (so its slug differs).+ * Runs only AFTER slug dedup passes, so it's a best-effort extra catch.+ *+ * Returns `{ available, duplicate, match }`:+ * - `available:false` when semantic dedup couldn't run (no embeddable candidates,+ * or the embeddings provider is off / the proposal embed failed). This is a+ * SENTINEL, distinct from `available:true, duplicate:false` ("checked, no+ * near-dup"): the handler treats unavailable as "proceed to file" because slug+ * dedup already guarded the exact case — losing the semantic catch just+ * restores pre-feature behavior, it never files a slug-duplicate.+ * - `duplicate:true` with `match` = the highest-scoring near-duplicate issue.+ *+ * No cold-bootstrap risk: `embed` degrades to `{ skipped:true }` when no+ * embeddings provider is configured, and this only runs inside the user-enabled+ * scheduled sweep. `embed` is injectable for tests.+ */+export async function checkSemanticDuplicate({ proposal, existingIssues = [], now = Date.now(), embed = defaultEmbed, threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {+ const unavailable = { available: false, duplicate: false, match: null };+ if (!proposal || typeof proposal !== 'object') return unavailable;++ // Only issues still within the dedup window with SOMETHING to embed are worth+ // comparing; a plan-tracked slug-only issue (no title/body) can't be embedded.+ const candidates = existingIssues+ .filter(i => isIssueWithinDedupWindow(i, now) && (i.body || i.title))+ .slice(0, SEMANTIC_DEDUP_MAX_CANDIDATES);+ if (candidates.length === 0) return unavailable;++ // A failing embed (transient provider blip, malformed response) must degrade to+ // the available:false sentinel — NOT reject through processApp and mark the+ // whole app run 'error'. Deferring the call into a promise chain then catching+ // absorbs BOTH an async rejection AND a synchronous throw from the (injectable)+ // embedder, mirroring this file's fetchHttpSource / jira-search failure idiom+ // (no non-boundary try/catch).+ const safeEmbed = (text) => Promise.resolve().then(() => embed(text)).catch(() => null);++ const proposalRes = await safeEmbed(issueEmbedSeed({ title: proposal.title, body: proposal.body }));+ if (!proposalRes?.success || !Array.isArray(proposalRes.embedding)) return unavailable;++ const embedded = [];+ for (const c of candidates) {+ const res = await safeEmbed(issueEmbedSeed({ title: c.title, body: c.body }));+ if (res?.success && Array.isArray(res.embedding)) {+ embedded.push({ slug: c.slug || null, number: c.number ?? null, title: c.title || '', embedding: res.embedding });+ }+ }+ if (embedded.length === 0) return unavailable;++ const match = findSemanticDuplicate({ proposalEmbedding: proposalRes.embedding, candidates: embedded, threshold });+ return { available: true, duplicate: !!match, match };+}diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.jsnew file mode 100644index 0000000000..cc818bd6b5--- /dev/null+++ b/server/services/layeredIntelligence/sources.js@@ -0,0 +1,439 @@+/**+ * Layered Intelligence — source gathering I/O (#2842 split of layeredIntelligence.js).+ *+ * Reads each configured source (planned work, files, HTTP, shell, LI task metrics)+ * with injectable deps so tests drive them without a live filesystem, network or+ * forge CLI. Also owns the shared `runCli` primitive used by the forge filer.+ */++import { join, resolve, relative, isAbsolute } from 'path';+import { existsSync } from 'fs';+import { realpath } from 'fs/promises';+import { tryReadFile, readJSONFile, PATHS } from '../../lib/fileUtils.js';+import { bufferedSpawn } from '../../lib/bufferedSpawn.js';+import { fetchPublicText } from '../../lib/safeUrlFetch.js';+import { validateCommand } from '../../lib/commandSecurity.js';+import { getSettings } from '../settings.js';+import { computeWindowedStats } from '../taskLearning/store.js';+import {+ PLANNED_WORK_LABEL, PLANNED_WORK_NONE, PLANNED_WORK_UNAVAILABLE_PREFIX,+ PLANNED_WORK_MAX_ITEMS, PLANNED_WORK_MAX_CHARS, LI_TASK_TYPE,+} from './constants.js';+import { computeScopeAwareness } from './awareness.js';+import { listForgeIssues, extractIssuePriority } from './forgeFiler.js';+import { listJiraIssues, plannedWorkJql } from './jiraFiler.js';++// ---------------------------------------------------------------------------+// I/O layer — gather + filers. Injectable deps keep these testable.+// ---------------------------------------------------------------------------+++/**+ * Why a planned-work read came back empty-handed. Rendered INSTEAD of a listing so+ * a failed tracker read can never be mistaken for "this app has nothing planned" —+ * the two are opposite instructions to the reasoner (be conservative vs. the field+ * is wide open), and collapsing them is exactly the failure the sentinel rule in+ * CLAUDE.md exists to prevent.+ */+export function plannedWorkUnavailable(why) {+ return `${PLANNED_WORK_UNAVAILABLE_PREFIX} (${why}). Do NOT treat this as "nothing is planned" — this app may well have a committed backlog that simply could not be listed this run. Be conservative: prefer proposal: null over filing work that might already be in scope.`;+}++/**+ * Whether a gathered plannedWork string is an actual LISTING of committed work —+ * i.e. something the reasoner can be told to go read — as opposed to one of the+ * two sentinels ("nothing is planned" / "could not be read"). Both sentinels are+ * meaningful in the prompt and still render, but neither is a backlog: telling+ * the reasoner its proposals "may be overlapping with committed work — review the+ * plannedWork source above" directly beneath a block stating no planned work+ * exists is a contradiction that just biases it toward filing nothing.+ */+export function hasPlannedWorkListing(plannedWork) {+ if (typeof plannedWork !== 'string') return false;+ const text = plannedWork.trim();+ if (!text || text === PLANNED_WORK_NONE) return false;+ return !text.startsWith(PLANNED_WORK_UNAVAILABLE_PREFIX);+}++/**+ * Render a planned-work item list into the prompt block. Pure.+ *+ * Reports the count of everything it was HANDED even when the rendered list is+ * truncated to `maxItems`, so the reasoner knows it is seeing the top of a larger+ * backlog rather than all of it — 15 shown out of 100 must not read as "there are+ * only 15". Note the caller's own read is capped too (the tracker lists cap at+ * 100), so on a very large backlog this count is itself a floor, not a census.+ */+export function formatPlannedWork(items, { maxItems = PLANNED_WORK_MAX_ITEMS, maxChars = PLANNED_WORK_MAX_CHARS } = {}) {+ const list = (Array.isArray(items) ? items : []).filter(i => i && typeof i === 'object' && (i.title || i.number != null));+ if (list.length === 0) return PLANNED_WORK_NONE;+ const top = list.slice(0, maxItems);+ const lines = top.map(i => {+ const ref = i.number != null ? `#${i.number} ` : '';+ const meta = [+ i.priority ? `priority: ${i.priority}` : null,+ Array.isArray(i.labels) && i.labels.length ? `labels: ${i.labels.join(', ')}` : null+ ].filter(Boolean).join('; ');+ return `- ${ref}${(i.title || '').trim()}${meta ? ` (${meta})` : ''}`;+ });+ const header = list.length > top.length+ ? `${list.length} items of actively-planned work the user has already committed to (showing the top ${top.length}):`+ : `${list.length} item(s) of actively-planned work the user has already committed to:`;+ return [header, ...lines].join('\n').slice(0, maxChars);+}++/**+ * Extract a PLAN.md's UNCHECKED (`- [ ]`) items — the plan tracker's equivalent of+ * a `plan`-labeled issue. A `- [x]` item is finished work, not committed-and-+ * pending, so it is excluded: proposing something already done is a different+ * (and already-handled) problem than proposing something already scheduled.+ */+export function extractPlannedPlanItems(planContent) {+ if (typeof planContent !== 'string') return [];+ const items = [];+ const re = /^[ \t]*[-*][ \t]+\[ \][ \t]*(\S.*)$/gm;+ let m;+ while ((m = re.exec(planContent))) {+ const title = m[1].replace(/\s+/g, ' ').trim();+ if (title) items.push({ number: null, title: title.slice(0, 200), labels: [], priority: null });+ }+ return items;+}++/**+ * Gather the app's actively-planned work — the backlog the user has ALREADY+ * committed to — so the reasoner can cross-reference a proposal against it before+ * filing (#2698). A deterministic tracker read: files + `gh`/`glab`/Jira REST, and+ * NO LLM call (the no-cold-bootstrap rule).+ *+ * Returns a prompt-ready string, or `null` when the source does not apply at all+ * (an unresolvable tracker: no forge CLI, no Jira coords, no repo path) — three+ * distinct states, never collapsed:+ * - `null` → nothing to say; buildPrompt omits the block+ * - `plannedWorkUnavailable()` → the read FAILED; be conservative+ * - a listing / PLANNED_WORK_NONE → the read SUCCEEDED and is trustworthy+ * (a plan-tracked app with no PLAN.md at all is a real PLANNED_WORK_NONE)+ *+ * Deps are injectable so tests drive every branch without a live tracker.+ */+export async function gatherPlannedWork({+ filer,+ forgeCli,+ cwd,+ jira,+ listForge = listForgeIssues,+ listJira = listJiraIssues,+ readFileFn = tryReadFile+} = {}) {+ if (filer === 'forge' && forgeCli && cwd) {+ const { ok, issues } = await listForge({ cli: forgeCli, cwd, label: PLANNED_WORK_LABEL, state: 'open' });+ if (!ok) return plannedWorkUnavailable(`the ${forgeCli} issue list failed`);+ // gh honors --state open, but glab's label list can still surface a closed+ // issue depending on version — re-filter so a done item never reads as pending.+ const open = issues.filter(i => i.state === 'open');+ return formatPlannedWork(open.map(i => ({+ number: i.number,+ title: i.title,+ labels: i.labels || [],+ priority: extractIssuePriority(i.labels)+ })));+ }++ if (filer === 'jira' && jira?.instanceId && jira?.projectKey) {+ const { ok, issues } = await listJira({+ instanceId: jira.instanceId,+ projectKey: jira.projectKey,+ jql: plannedWorkJql(jira.projectKey),+ // Jira's priority field is not in searchIssues' default `fields` set — ask+ // for it explicitly, or every item would report a null priority.+ searchOptions: { fields: 'summary,status,labels,updated,description,resolutiondate,priority' }+ });+ if (!ok) return plannedWorkUnavailable('the Jira search failed');+ const open = issues.filter(i => i.state === 'open');+ return formatPlannedWork(open.map(i => ({+ number: i.number,+ title: i.title,+ labels: i.labels || [],+ // Prefer Jira's real priority field; fall back to a priority-ish label.+ priority: i.priority || extractIssuePriority(i.labels)+ })));+ }++ if (filer === 'plan' && cwd) {+ const planPath = join(cwd, 'PLAN.md');+ // No PLAN.md at all is a real "nothing is planned" for a plan-tracked app —+ // distinguish it from a PLAN.md that EXISTS but could not be read (a genuine+ // failure), which tryReadFile's null would otherwise conflate.+ if (!existsSync(planPath)) return PLANNED_WORK_NONE;+ const content = await readFileFn(planPath);+ if (typeof content !== 'string') return plannedWorkUnavailable('PLAN.md exists but could not be read');+ return formatPlannedWork(extractPlannedPlanItems(content));+ }++ return null;+}++/**+ * Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.+ * Deterministic reads only (files + CoS metric JSON + tracker lists); NO LLM calls.+ * Missing files degrade to omitted keys, never throws. `openIssues` is gathered+ * separately by the handler (it shells out to the forge). `tracker`+ * (`{ filer, forgeCli, cwd, jira }`, resolved by the caller) enables the+ * plannedWork source — absent, that source is simply skipped.+ */+export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShellSources, tracker = null, isPortos = false } = {}) {+ const out = {};+ const src = config.sources || {};+ const repo = app.repoPath;++ // Resolve the install-level shell-trust opt-in lazily and once — only when a+ // `cmd` source is actually present — so apps with no shell sources never read+ // settings. Injected value (tests) wins; otherwise fall back to settings.json.+ let trustShell = trustShellSources;+ const resolveTrustShell = async () => {+ if (trustShell === undefined) trustShell = await getTrustShellSources();+ return trustShell;+ };++ if (src.goals && repo) {+ const goals = await tryReadFile(join(repo, 'GOALS.md'));+ if (goals) out.goals = goals.slice(0, 8000);+ }+ if (src.appMetrics && repo) {+ // The app's own success/performance metrics doc (the METRICS.md convention,+ // see docs/METRICS.md) — where a managed app records what "performing well"+ // means. Absent → omitted (the reasoner may then propose adding one).+ const metrics = await tryReadFile(join(repo, 'METRICS.md'));+ if (metrics) out.appMetrics = metrics.slice(0, 8000);+ }+ if (src.planMd && repo) {+ const plan = await tryReadFile(join(repo, 'PLAN.md'));+ if (plan) out.planMd = plan.slice(0, 8000);+ }+ if (src.healthReport && repo) {+ const health = await tryReadFile(join(repo, 'HEALTH_REPORT.md'));+ if (health) out.healthReport = health.slice(0, 8000);+ }+ if (src.plannedWork && tracker) {+ // The committed backlog (#2698). Unlike the file sources above, an EMPTY or+ // FAILED result still emits a key — each renders a distinct sentence, and+ // both are meaningful instructions to the reasoner (see gatherPlannedWork).+ const planned = await gatherPlannedWork(tracker);+ if (planned) out.plannedWork = planned.slice(0, PLANNED_WORK_MAX_CHARS);+ }+ if (src.cosMetrics) {+ // This install's own autonomous-agent run stats (per task type), NOT scoped to+ // the app being analyzed — see the default-config note for the PortOS-vs-managed+ // rationale (default-off for managed apps).+ const learning = await readJSONFile(join(cosPath, 'learning.json'), null);+ if (learning?.byTaskType) {+ // Surface BOTH the lifetime rate (the cumulative dashboard/telemetry truth)+ // AND a recency-windowed rate (issue #2460) per task type, labeled distinctly+ // so the reasoner doesn't conflate them. The windowed rate lets a+ // since-resolved failure burst age out of the "is work needed" signal instead+ // of permanently depressing it; `recentSuccessRate` is null when there are no+ // in-window runs, in which case the reasoner leans on the lifetime rate.+ // Note the intentional rename: computeWindowedStats' internal `windowed*`+ // fields are surfaced to the reasoner as `recent*` (reads more naturally in+ // the prompt context) — same concept, deliberately different label here.+ const summary = {};+ for (const [type, m] of Object.entries(learning.byTaskType)) {+ const windowed = computeWindowedStats(m?.recentOutcomes);+ summary[type] = {+ lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,+ lifetimeCompleted: m?.completed || 0,+ recentSuccessRate: windowed.windowedSuccessRate,+ recentCompleted: windowed.windowedCompleted,+ avgDurationMs: m?.avgDurationMs || 0+ };+ }+ out.cosMetrics = JSON.stringify(summary).slice(0, 4000);+ // Scope-awareness guidance (#2760): a deterministic low/high-completion split+ // derived from the SAME per-type rates above, so the reasoner gets an interpreted+ // signal alongside the raw JSON instead of being asked to spot the pattern itself.+ // Rendered as its own prompt block (see buildPrompt). Gated on isPortos (codex P2):+ // these are THIS install's own CoS completion rates, meaningless to a managed app —+ // and a managed app CAN enable the cosMetrics source, so the cosMetrics toggle+ // alone is not the PortOS boundary. buildPrompt re-checks isPortos as defense in+ // depth; deriving it here only for PortOS also avoids the wasted work.+ if (isPortos) {+ const scopeGuidance = computeScopeAwareness({ metricsByType: summary });+ if (scopeGuidance) out.scopeGuidance = scopeGuidance;+ }+ }+ }+ for (const custom of src.custom || []) {+ const key = customSourceKey(custom);+ if (!key) continue;+ if (custom.type === 'file' && typeof custom.ref === 'string' && repo) {+ const safe = await confineToRepo(repo, custom.ref);+ if (!safe) {+ console.warn(`⚠️ Layered Intelligence: custom source "${custom.ref}" escapes repo — skipped`);+ continue;+ }+ const content = await tryReadFile(safe);+ if (content) out[key] = content.slice(0, 8000);+ } else if (custom.type === 'http' && typeof custom.url === 'string') {+ const content = await fetchHttpSource(custom.url);+ if (content) out[key] = content.slice(0, 8000);+ } else if (custom.type === 'cmd' && typeof custom.cmd === 'string' && repo) {+ const content = await runShellCommand(custom.cmd, { cwd: repo, trustShellSources: await resolveTrustShell() });+ if (content) out[key] = content.slice(0, 8000);+ }+ }+ return out;+}++/**+ * Read the LI loop's OWN agent-run metrics out of the CoS learning store (#2700).+ * Deterministic file read; no LLM call. Feeds computeSelfEvalSummary's execution-+ * health signal.+ *+ * Returns a discriminated result rather than a bare bucket-or-null, because the two+ * empty cases are NOT the same fact and the reasoner is told them differently:+ * `{ read: false, metrics: null }` — the store is missing/unreadable/malformed:+ * we do not know how LI's runs are going.+ * `{ read: true, metrics: null }` — the store is fine, LI has simply never run.+ * `{ read: true, metrics: {...} }` — real history.+ * Collapsing these to one `null` would let "cannot read the store" masquerade as+ * "healthy loop with no history" (or vice versa) — the sentinel rule.+ */+export async function readLiTaskMetrics({ cosPath = PATHS.cos } = {}) {+ const file = join(cosPath, 'learning.json');+ // An ABSENT store is a fresh install, not a broken read: learning.json is created+ // lazily on the first recorded task outcome. readJSONFile returns its default for+ // ENOENT, I/O errors, and parse failures ALIKE, so leaning on it alone would tell+ // every fresh install "your learning store could not be read" when the truth is+ // "nothing has run here yet" — the exact conflation this function exists to+ // prevent, just inverted. Check existence first so the two stay distinct.+ if (!existsSync(file)) return { read: true, metrics: null };+ const learning = await readJSONFile(file, null);+ const byTaskType = learning?.byTaskType;+ if (!byTaskType || typeof byTaskType !== 'object' || Array.isArray(byTaskType)) {+ return { read: false, metrics: null };+ }+ const bucket = byTaskType[LI_TASK_TYPE];+ return {+ read: true,+ metrics: (bucket && typeof bucket === 'object' && !Array.isArray(bucket)) ? bucket : null+ };+}++/**+ * Stable map key for a custom source. Namespaced by type so a `file` ref and an+ * `http` url that share a string can't collide, and so the prompt's source block+ * labels are self-describing. Returns null for a malformed/unknown source.+ */+export function customSourceKey(custom) {+ if (!custom || typeof custom !== 'object') return null;+ if (custom.type === 'file' && custom.ref) return `custom:${custom.ref}`;+ if (custom.type === 'http' && custom.url) return `custom:http:${custom.url}`;+ if (custom.type === 'cmd' && custom.cmd) return `custom:cmd:${custom.cmd}`;+ return null;+}++/**+ * Fetch an http(s) custom source for the loop's prompt. Deterministic read, no+ * LLM. Rejects any non-http(s) scheme (defense in depth over the Zod refine),+ * bounds the request with a 10s timeout, and returns null on any failure so a+ * dead URL just omits the key rather than throwing.+ *+ * SSRF-guarded via `fetchPublicText` (default posture): loopback, link-local,+ * and the cloud-metadata endpoint (127.0.0.1, 169.254.169.254,+ * metadata.google.internal, ::1) are blocked so a hand-edited/hostile config+ * can't exfiltrate them into the reasoner prompt, and redirects are revalidated+ * against the same gate. LAN/private hosts (Tailscale peers, a home wiki) stay+ * ALLOWED intentionally — PortOS is a single-user tool where a custom source+ * legitimately points at the home network, and the URL is operator-configured.+ * `throwOnUnsafe: false` makes a blocked host omit the key like any other dead+ * URL instead of bubbling a 400. `fetchText` is injectable for tests.+ */+export async function fetchHttpSource(url, { timeoutMs = 10_000, fetchText = fetchPublicText } = {}) {+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null;+ const text = await fetchText(url, { timeoutMs, throwOnUnsafe: false }).catch(() => null);+ return text || null;+}++/**+ * THREAT MODEL — a `cmd` custom source is attacker-reachable persistent config.+ *+ * The `sources.custom` array lives in each app's stored `layeredIntelligence`+ * config, written through the validated `PUT /api/apps/:id` route. A `cmd` entry+ * is executed here on the Layered Intelligence SCHEDULE (Engine-B autonomous job),+ * with the PortOS process's own privileges and cwd = the app repo. So any path+ * that can land a string in that config (a hand-edited config, a hostile sync+ * payload, a future config-writing feature, an XSS-driven same-origin POST) gets+ * *persistent, unattended* code execution — not a one-shot the operator watched.+ *+ * Historically this ran the full command string with `shell: true`, capped only+ * by length + a 15s timeout. That is arbitrary RCE: `; rm -rf ~`, `$(curl … | sh)`,+ * pipes to `sh`, etc. all execute. Issue #2515.+ *+ * Defense: by default we DENY the shell. The command is parsed and checked+ * against the shared binary allowlist (`validateCommand` in commandSecurity.js —+ * same gate the manual command runner uses), which rejects shell metacharacters+ * (`;|&$(){}` …) and any binary not on the allowlist, then we spawn the base+ * binary with parsed args and `shell: false` — so no shell ever interprets the+ * string. A non-allowlisted / metacharacter command is dropped (key omitted) with+ * a warning, exactly like any other failed source read.+ *+ * Escape hatch: an operator who genuinely needs a pipeline (`git log … | head`)+ * can set the install-level `settings.layeredIntelligence.trustShellSources`+ * flag, which restores the full `shell: true` behavior for THIS install only.+ * It is an explicit, install-wide opt-in — off by default — so a fresh install+ * (or a synced-in app config) can never execute an un-allowlisted command.+ *+ * `exec` is injectable for tests; `trustShellSources` is resolved by the caller+ * (`gatherSources`) from install settings and threaded in.+ *+ * Returns null on rejection / non-zero exit / timeout / no output so a failing or+ * denied command just omits the source key rather than throwing.+ */+export async function runShellCommand(cmd, { cwd, timeoutMs = 15_000, exec = bufferedSpawn, trustShellSources = false } = {}) {+ if (typeof cmd !== 'string' || !cmd.trim()) return null;+ if (trustShellSources) {+ // Operator has explicitly opted this install into full-shell custom sources.+ const { code, stdout } = await exec(cmd, [], { cwd, timeoutMs, shell: true });+ if (code !== 0) return null;+ return (stdout || '').trim() || null;+ }+ const check = validateCommand(cmd);+ if (!check.valid) {+ console.warn(`⚠️ Layered Intelligence: custom cmd source "${cmd}" rejected — ${check.error} (enable settings.layeredIntelligence.trustShellSources to allow arbitrary shell commands)`);+ return null;+ }+ const { code, stdout } = await exec(check.baseCommand, check.args, { cwd, timeoutMs, shell: false });+ if (code !== 0) return null;+ return (stdout || '').trim() || null;+}++/**+ * Resolve the install-level "trust shell sources" opt-in from settings.json.+ * `null`/absent/non-true all read as OFF (the safe default) — only an explicit+ * `true` unlocks full-shell custom `cmd` sources. Injectable read for tests.+ */+export async function getTrustShellSources(read = getSettings) {+ const settings = await read();+ return settings?.layeredIntelligence?.trustShellSources === true;+}++/**+ * Confine a custom file `ref` to within `repo` so a hostile/hand-edited config+ * can't read arbitrary files into the LLM prompt. Returns the safe absolute path,+ * or null when it escapes. Guards BOTH lexical traversal (`..` / absolute) AND+ * symlink escape — a symlink inside the repo pointing outside is resolved via+ * realpath and rejected. Missing files return null (nothing to read).+ */+export async function confineToRepo(repo, ref) {+ const abs = resolve(repo, ref);+ const rel = relative(repo, abs);+ if (rel.startsWith('..') || isAbsolute(rel)) return null;+ // Resolve symlinks on both sides; a link inside the repo that points outside+ // is caught here (lexical check above only sees the link's own path).+ const realRepo = await realpath(repo).catch(() => null);+ const realAbs = await realpath(abs).catch(() => null);+ if (!realRepo || !realAbs) return null;+ const realRel = relative(realRepo, realAbs);+ if (realRel.startsWith('..') || isAbsolute(realRel)) return null;+ return realAbs;+}diff --git a/server/services/layeredIntelligenceBarrel.test.js b/server/services/layeredIntelligenceBarrel.test.jsnew file mode 100644index 0000000000..e275eaeb77--- /dev/null+++ b/server/services/layeredIntelligenceBarrel.test.js@@ -0,0 +1,82 @@+import { describe, it, expect } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++import * as barrel from './layeredIntelligence.js';++const HERE = dirname(fileURLToPath(import.meta.url));+const BARREL_SRC = readFileSync(join(HERE, 'layeredIntelligence.js'), 'utf8');+const MODULE_FILES = readdirSync(join(HERE, 'layeredIntelligence'))+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))+ .sort();++// Issue #2842 split the 2,631-line layeredIntelligence.js into+// ./layeredIntelligence/* with the original file kept as a re-exporting barrel+// (the same treatment #1152 gave arcPlanner.js). This pins that contract so the+// handler, routes and the existing suites keep importing from one path.+describe('layeredIntelligence barrel re-exports (issue #2842)', () => {+ it('re-exports every module in ./layeredIntelligence/', () => {+ for (const f of MODULE_FILES) {+ expect(BARREL_SRC, `missing barrel re-export for layeredIntelligence/${f}`)+ .toContain(`'./layeredIntelligence/${f}'`);+ }+ });++ it.each(MODULE_FILES)('%s exports are reachable from the barrel as the same objects', async (f) => {+ const mod = await import(`./layeredIntelligence/${f}`);+ const keys = Object.keys(mod);+ expect(keys.length, `${f} exports nothing`).toBeGreaterThan(0);+ for (const key of keys) {+ expect(barrel[key], `barrel re-export of '${key}' (from ${f})`).toBe(mod[key]);+ }+ });++ it('no symbol collides across the split modules', async () => {+ const seen = new Map();+ const collisions = [];+ for (const f of MODULE_FILES) {+ const mod = await import(`./layeredIntelligence/${f}`);+ for (const key of Object.keys(mod)) {+ if (seen.has(key) && seen.get(key).value !== mod[key]) {+ collisions.push(`${key}: ${seen.get(key).file} vs ${f}`);+ } else if (!seen.has(key)) {+ seen.set(key, { file: f, value: mod[key] });+ }+ }+ }+ expect(collisions).toEqual([]);+ });++ it('keeps the public surface the handler + routes depend on', () => {+ for (const fn of [+ 'defaultLayeredIntelligenceConfig', 'getEffectiveConfig', 'isScopeAllowed',+ 'slugMarker', 'extractSlugFromBody', 'normalizeSlug', 'isProposalDuplicate',+ 'findSemanticDuplicate', 'checkSemanticDuplicate', 'isAppParked',+ 'validateReasonerResponse', 'resolveBlockOnIssue', 'isHandoffEligible',+ 'buildHandoffTask', 'filerForTracker', 'trackerSupportsPause',+ 'deriveOutcome', 'computeOutcomesReport', 'computeSelfEvalSummary',+ 'computeScopeAwareness', 'computeProposalExecutionAwareness',+ 'computeCrossReferenceAnalysis', 'computeHandoffRouting',+ 'computeHardExclusionGate', 'computeHardExclusionNotice', 'buildPrompt',+ 'gatherSources', 'gatherPlannedWork', 'readLiTaskMetrics',+ 'listForgeIssues', 'fileProposalToForge', 'listJiraIssues',+ 'fileProposalToJira', 'appendProposalToPlan', 'extractPlanSlugs',+ ]) {+ expect(typeof barrel[fn], fn).toBe('function');+ }+ for (const c of [+ 'LI_LABEL', 'LI_BLOCKING_LABEL', 'PLANNED_WORK_LABEL', 'LI_JOB_ID',+ 'PROPOSAL_SCOPES', 'PORTOS_ONLY_SCOPES', 'PROPOSAL_COMPLEXITIES',+ 'LI_SCHEDULED_TASK_TYPE', 'LI_TASK_TYPE', 'PROPOSAL_OUTCOMES',+ 'SELF_IMPROVE_SCOPES',+ ]) {+ expect(barrel[c], c).toBeDefined();+ }+ // The playbook is read synchronously at module load from a path relative to+ // the module file — the split moved the module a directory deeper, so this+ // guards the `..` hop back to server/services/.+ expect(typeof barrel.LI_PROPOSAL_PLAYBOOK).toBe('string');+ expect(barrel.LI_PROPOSAL_PLAYBOOK.length).toBeGreaterThan(100);+ });+});diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 3d9646bbaa..16bd4eb8f9 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -63,2479 +63,34 @@* billable cos action and is budget-gated individually (a comic is many GPU* jobs), and already-enqueued slots are skipped so a resumed run doesn't* re-render. Gated behind `options.includeVisual`.- */--import { randomUUID } from 'crypto';-import { EventEmitter } from 'events';-import { sleep } from '../../lib/fileUtils.js';-import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';-import { getDomainMode } from '../../lib/domainAutonomy.js';-import { parseComicScript } from '../../lib/comicScriptParser.js';-import { loadState } from '../cosState.js';-import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';-import * as cosTaskStore from '../cosTaskStore.js';-import { getSeries, updateSeries } from './series.js';-import { listIssues, getIssue, isStageReady, updateStageWithLatest } from './issues.js';-import { compareIssuesByPosition } from './arcPlanner.js';-import { enqueueComicCover, enqueueComicBackCover, enqueueVisualComicPage } from './visualStages.js';-import { slotKeyForVariant } from './owners.js';-import { buildRenderSlot } from '../../lib/renderSlot.js';-import {- generateArcOverview,- commitSeasonsWithRemap,- generateSeasonEpisodes,- commitEpisodesToIssues,- verifyArc,- resolveVerifyIssues,- analyzeBeatContinuity,- resolveBeatContinuity,- analyzeManuscriptCompleteness,-} from './arcPlanner.js';-import * as volumeBeatsRunner from './volumeBeatsRunner.js';-import * as autoRunner from './autoRunner.js';-import { seedReviewFromFindings, getReview } from './manuscriptReview.js';-import { runEditorialChecks, buildEditorialCheckPlan, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors } from './editorial/checkRunner.js';-import { generateReverseOutline, getReverseOutline } from './reverseOutline.js';-import { computeHealth, openBlockers, READINESS_GATES, resolveReadinessGate, summarizeEditorialBlockers, formatBlockerSummary } from './editorialScore.js';-import { getSettings } from '../settings.js';-import { readReadinessGate, mergeSeverityWeights, resolveBlockingSet } from '../../lib/editorial/index.js';-import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';-import { judgeIssue, getIssueJudge, getSeriesJudge } from './pipelineJudge.js';-import { applyCuts, filterSafeCutComments } from './applyCuts.js';-import { eligibleIssues, getComparativeRank } from './editorial/comparativeRank.js';-import { buildRevisionBrief } from './editorial/revisionBrief.js';-import { evaluateRevisionStop, decideKeepRevert } from './editorial/revisionStop.js';-import { verifyComicScript } from './scriptVerify.js';-import { checkSeriesCanonReadiness } from './canonReadiness.js';-import { judgeFoundation, applyFoundationFix, weakestDimension, residualFindings, DEFAULT_FOUNDATION_THRESHOLD } from './foundationJudge.js';-import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';--// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished,-// cleanupTimer, startedAt, mode, options, runState, activeChild }>-const runs = new Map();--// In-process progress bus (CDO Phase 3, #2185). Every SSE frame the run-// broadcasts to attached HTTP clients is ALSO emitted here keyed by seriesId, so-// a SERVER-SIDE consumer — the Creative Director plan-advance loop running an-// autopilot as one plan step — can observe progress/pause/terminal frames-// without opening an HTTP/SSE client. SSE behavior is unchanged; this is a-// parallel tap, not a replacement. Listeners are per-seriesId and short-lived-// (attached for the life of one plan step), but a busy install could run several-// concurrently, so lift the default 10-listener cap to avoid a spurious leak-// warning. The payloads are the exact SSE frames (they carry `type`).-export const autopilotEvents = new EventEmitter();-autopilotEvents.setMaxListeners(0);--// The frame `type`s that mean the run reached a terminal/paused state — a-// server-side consumer settles its plan step on any of these. `complete` (or a-// dry-run `complete`), `paused` (convergence/budget/child pause), `canceled`-// (user stop), and `error` (run-ending throw) are exhaustive of the run's exit-// frames (see the fire-and-forget coordinator in startSeriesAutopilot).-export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled', 'error']);--// Bounded convergence loops — re-verify/re-review at most this many rounds, then-// pause for human review with the residual findings (see module header). These-// are the floor defaults; an install can raise them persistently via-// pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds} (or a single-// run can override per-run through the autopilot start options).-export const MAX_ARC_VERIFY_ROUNDS = 3;-export const MAX_EDITORIAL_ROUNDS = 2;-// Whole-manuscript beat-continuity convergence (#1510). The corpus is the-// compact per-issue beat sheets, so this gate sits between beat generation and-// the expensive text/script stage — bounded like the others, then pauses with-// the residual findings for human review.-export const MAX_BEAT_CONTINUITY_ROUNDS = 2;--// Foundation-quality gate (CWQE Phase 11, #2176). Before drafting, judge the-// whole foundation (world / characters / arc) against a weighted rubric and-// iterate on the weakest dimension until it clears a threshold — bounded like-// the other convergence loops, then pause with the residual per-dimension-// findings for human review. Defaults ON for autopilot runs (the point of the-// phase) but overridable per-run + via the persisted setting. 0 rounds skips-// the gate entirely (accept the foundation as-is).-export const MAX_FOUNDATION_ROUNDS = 3;-export const DEFAULT_FOUNDATION_GATE_ENABLED = true;--// Bounded retry budget for a delegated child runner (#1574). A child (volume-// beats / text auto-run) can finish with its target stage(s) still empty when-// the underlying LLM call failed. Before #1574 the autopilot marked the work-// attempted and advanced regardless — so a transient failure was caught only-// later (text) or not at all until a downstream emptiness check (beats). Now a-// child whose readiness check fails is retried up to MAX_CHILD_RETRIES more-// times (skip-existing, so a retry only fills the gap) before the work is-// marked attempted, an escalation frame is emitted, and the run pauses with the-// residual. 0 = single attempt, no retry (the legacy behavior). A per-run-// `maxChildRetries` option overrides it (plumbed through runOptions).-export const MAX_CHILD_RETRIES = 1;--// Resolve the effective round bounds for a run: an explicit per-run option wins,-// then the persisted pipelineEditorialChecks setting, then the module default.-// Returns integers only — a non-integer at any layer falls through to the next.-// Centralized so the loops, the dry-run plan, and the resume path all agree.-export function resolveAutopilotRounds(options = {}, settings = null) {- const pec = settings?.pipelineEditorialChecks || {};- const pick = (optKey, setKey, fallback) => {- if (Number.isInteger(options?.[optKey])) return options[optKey];- if (Number.isInteger(pec?.[setKey])) return pec[setKey];- return fallback;- };- return {- maxArcVerifyRounds: pick('maxArcVerifyRounds', 'maxArcVerifyRounds', MAX_ARC_VERIFY_ROUNDS),- maxEditorialRounds: pick('maxEditorialRounds', 'maxEditorialRounds', MAX_EDITORIAL_ROUNDS),- maxBeatContinuityRounds: pick('maxBeatContinuityRounds', 'maxBeatContinuityRounds', MAX_BEAT_CONTINUITY_ROUNDS),- maxFoundationRounds: pick('maxFoundationRounds', 'maxFoundationRounds', MAX_FOUNDATION_ROUNDS),- };-}--// Foundation-gate config (#2176): whether the gate runs, and the weighted [0,10]-// threshold the foundation must clear. Mirror resolveAutopilotRounds — per-run-// option wins, then the persisted pipelineEditorialChecks setting, then the-// default. The enable flag defaults ON (the point of the phase); the threshold-// falls through to DEFAULT_FOUNDATION_THRESHOLD in the loop when unset. Stamped-// onto run options once at start so the loop, the dry-run plan, and a resume all-// read the same effective values.-export function resolveAutopilotFoundationGate(options = {}, settings = null) {- if (typeof options?.foundationGate === 'boolean') return options.foundationGate;- const pec = settings?.pipelineEditorialChecks || {};- if (typeof pec?.foundationGate === 'boolean') return pec.foundationGate;- return DEFAULT_FOUNDATION_GATE_ENABLED;-}-export function resolveAutopilotFoundationThreshold(options = {}, settings = null) {- if (Number.isFinite(options?.foundationThreshold)) return options.foundationThreshold;- const pec = settings?.pipelineEditorialChecks || {};- if (Number.isFinite(pec?.foundationThreshold)) return pec.foundationThreshold;- return null;-}--// Resolve the effective editorial-health readiness gate for a run (#1580): an-// explicit per-run option wins, then the persisted-// pipelineEditorialChecks.readinessGate, then null — the caller resolves null to-// DEFAULT_READINESS_GATE via resolveReadinessGate. Mirrors resolveAutopilotRounds-// so the gate is overridable per-run exactly like the round bounds; stamped onto-// the run options once at start so the loop, the dry-run plan, and a later resume-// all read the same effective gate.-export function resolveAutopilotReadinessGate(options = {}, settings = null) {- if (READINESS_GATES.includes(options?.readinessGate)) return options.readinessGate;- return readReadinessGate(settings);-}--// Editorial-checks pause threshold (#1613): pause the run when the checks pass-// surfaces ≥ N high-severity findings. 0 = off (the default), so the gate is-// opt-in and existing installs are unchanged. Mirrors resolveAutopilotRounds —-// per-run option wins, then the persisted setting, then 0. A non-integer at any-// layer falls through to the next. Stamped onto run options once at start so the-// loop and a later resume read the same effective threshold.-export const DEFAULT_CHECK_FINDINGS_PAUSE_THRESHOLD = 0;-export function resolveAutopilotCheckPauseThreshold(options = {}, settings = null) {- if (Number.isInteger(options?.checkFindingsPauseThreshold)) return options.checkFindingsPauseThreshold;- const pec = settings?.pipelineEditorialChecks || {};- if (Number.isInteger(pec?.checkFindingsPauseThreshold)) return pec.checkFindingsPauseThreshold;- return DEFAULT_CHECK_FINDINGS_PAUSE_THRESHOLD;-}--// Pause escalation (#1615): post an in-app notification (notification center,-// surfaced in the header dropdown) when a run pauses, so a paused run doesn't sit-// unnoticed until the user happens to open the status page. Unlike the other-// gates this defaults ON — it's a zero-cost informational signal that directly-// addresses the "paused runs go unnoticed" problem — but stays overridable per-// run and via the persisted setting for users who don't want the noise. Boolean-// at every layer: per-run option wins, then the persisted setting, then true.-export const DEFAULT_NOTIFY_ON_PAUSE = true;-export function resolveAutopilotNotifyOnPause(options = {}, settings = null) {- if (typeof options?.notifyOnPause === 'boolean') return options.notifyOnPause;- const pec = settings?.pipelineEditorialChecks || {};- if (typeof pec?.notifyOnPause === 'boolean') return pec.notifyOnPause;- return DEFAULT_NOTIFY_ON_PAUSE;-}--// Autopilot → CD teaser deliverable (CDO Phase 3, #2185). Once a comic issue is-// text-ready + drafted, the autopilot can OPTIONALLY mint + start a Creative-// Director video project (a teaser/trailer) seeded from the issue — the reverse-// of the CD→autopilot bridge. Defaults OFF: producing video is a fresh burst of-// LLM + render spend the user must opt into, so existing runs are unchanged.-// Per-run option wins, then the persisted setting, then false. Stamped onto run-// options once at start so the resolver, the dry-run plan, and a later resume-// all read the same effective flag.-export const DEFAULT_PRODUCE_TEASER = false;-export function resolveAutopilotProduceTeaser(options = {}, settings = null) {- if (typeof options?.produceTeaser === 'boolean') return options.produceTeaser;- const pec = settings?.pipelineEditorialChecks || {};- if (typeof pec?.produceTeaser === 'boolean') return pec.produceTeaser;- return DEFAULT_PRODUCE_TEASER;-}--// Does THIS run want to produce a teaser deliverable? Gated on the resolved-// `produceTeaser` flag AND that visuals ran (a teaser is a visual deliverable —-// pointless on a text-only run).-export function wantsTeaser(options = {}) {- return options.produceTeaser === true && wantsVisual(options);-}--// Iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in per run; when-// enabled the autopilot cycles the weakest issue through adversarial cuts +-// judge-gated keep/revert instead of stopping at the editorial-health gate.-// Defaults OFF — it is a fresh burst of judge + cut LLM spend the user must-// opt into. minCycles floors the plateau/hedge stops so the loop always runs at-// least once; maxCycles is the cost ceiling; plateauDelta is the mean-score-// movement below which the series counts as converged. Per-run option wins, then-// the persisted pipelineEditorialChecks.revision* setting, then the default.-export const DEFAULT_REVISION_ENABLED = false;-export const DEFAULT_REVISION_MIN_CYCLES = 1;-export const DEFAULT_REVISION_MAX_CYCLES = 2;-export const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;-export function resolveAutopilotRevision(options = {}, settings = null) {- const pec = settings?.pipelineEditorialChecks || {};- const bool = (o, s, fallback) => {- if (typeof o === 'boolean') return o;- if (typeof s === 'boolean') return s;- return fallback;- };- const int = (o, s, fallback) => {- if (Number.isInteger(o)) return o;- if (Number.isInteger(s)) return s;- return fallback;- };- const num = (o, s, fallback) => {- if (Number.isFinite(o)) return o;- if (Number.isFinite(s)) return s;- return fallback;- };- const minCycles = int(options?.revisionMinCycles, pec?.revisionMinCycles, DEFAULT_REVISION_MIN_CYCLES);- const maxCycles = int(options?.revisionMaxCycles, pec?.revisionMaxCycles, DEFAULT_REVISION_MAX_CYCLES);- return {- revisionEnabled: bool(options?.revisionEnabled, pec?.revisionEnabled, DEFAULT_REVISION_ENABLED),- revisionMinCycles: Math.max(1, minCycles),- // maxCycles never below minCycles — a misconfig can't strand the loop unable to run.- revisionMaxCycles: Math.max(Math.max(1, minCycles), maxCycles),- revisionPlateauDelta: Math.max(0, num(options?.revisionPlateauDelta, pec?.revisionPlateauDelta, DEFAULT_REVISION_PLATEAU_DELTA)),- };-}--// Per-gate copy for the non-convergence pause — shared by the arc-verify and-// editorial loops so the two messages can't drift.-const PAUSE_GATES = {- arc: { label: 'Arc verification', fix: 'Edit the arc/volumes to address them', limit: 'verify-rounds' },- beatContinuity: { label: 'Beat continuity', fix: 'Edit the affected issue beats', limit: 'beat-continuity-rounds' },- editorial: { label: 'Editorial review', fix: 'Address them in the manuscript editor', limit: 'editorial-rounds' },- foundation: { label: 'Foundation quality', fix: 'Strengthen the world / characters / arc, or lower the threshold', limit: 'foundation-rounds' },-};-function convergencePauseReason(gate, maxRounds, blockingCount) {- const { label, fix, limit } = PAUSE_GATES[gate];- const plural = maxRounds === 1 ? 'round' : 'rounds';- return `${label} couldn't auto-resolve ${blockingCount} blocking finding(s) in ${maxRounds} ${plural} — `- + `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;-}--// Divergence/oscillation guard for the bounded convergence loops (#1571). A-// verify→resolve round is "profitable" only when the next verify shows STRICTLY-// FEWER blocking findings. When the count fails to drop (stays equal, or rises —-// a resolve pass that introduced a new break while fixing another) for-// DIVERGENCE_PATIENCE consecutive rounds, the loop is no longer converging:-// stop early and pause with a `divergence` kind instead of burning the rest of-// the daily cos budget down to maxRounds. The terminal maxRounds pause keeps its-// own `maxRounds` kind — the two are distinguished in the pause SSE frame so the-// UI can tell "needs a human" (diverging) from "just ran out of rounds".-//-// With the default caps (arc 3 / beat 2 / editorial 2) the loop hits maxRounds-// before the streak can reach patience, so default runs are unaffected; the-// guard only bites when a user RAISES a cap and the loop then stalls.-export const DIVERGENCE_PATIENCE = 2;--// Convergence tracker for one verify→resolve round. `state` is-// { best, sinceBest }: `best` is the FEWEST blocking findings seen so far this-// loop (null before the first measured round), `sinceBest` the count of-// consecutive rounds since that minimum last STRICTLY improved. A round that-// reaches a new low is progress (sinceBest → 0); a stall, a regression (a fix-// that introduced a new break), OR an oscillation that merely revisits an old-// count all accrue sinceBest. The loop diverges once sinceBest reaches-// DIVERGENCE_PATIENCE. Tracking the running minimum (not just the previous-// round) is what lets this catch a 2-cycle oscillation — e.g. 5→4→5→4 never-// sets a new low after round 2, so it's caught — which a naive-// "compare to the previous round" check would miss. Pure + unit-tested.-export function trackConvergence(state, curr) {- if (state.best === null || curr < state.best) {- return { best: curr, sinceBest: 0 };- }- return { best: state.best, sinceBest: state.sinceBest + 1 };-}--// Pause reason for a gate that stopped converging early (#1571) — distinct-// wording from convergencePauseReason's "ran out of rounds".-function divergencePauseReason(gate, blockingCount, rounds) {- const { label, fix } = PAUSE_GATES[gate];- const plural = rounds === 1 ? 'round' : 'rounds';- return `${label} stopped converging — ${blockingCount} blocking finding(s) and no net progress over `- + `${rounds} consecutive ${plural} of auto-resolve. Paused for review. ${fix}, then resume.`;-}--// Foundation gate pause reasons (#2176) — the gate converges on a WEIGHTED-// SCORE, not a finding count, so it needs its own wording (score vs. threshold)-// rather than the finding-count phrasing of convergencePauseReason. Shares-// PAUSE_GATES.foundation so the copy stays aligned with the other gates.-function foundationPauseReason(maxRounds, score, threshold) {- const { label, fix, limit } = PAUSE_GATES.foundation;- const plural = maxRounds === 1 ? 'round' : 'rounds';- return `${label} couldn't reach the threshold (weighted ${score} < ${threshold}) in ${maxRounds} ${plural} — `- + `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;-}-function foundationDivergenceReason(score, threshold, rounds) {- const { label, fix } = PAUSE_GATES.foundation;- const plural = rounds === 1 ? 'round' : 'rounds';- return `${label} stopped improving — weighted ${score} still below ${threshold} with no net gain over `- + `${rounds} consecutive ${plural} of auto-fix. Paused for review. ${fix}, then resume.`;-}--// Dry-run plan note for a bounded gate: "skipped (0 rounds)" or "up to N rounds".-const roundsNote = (rounds) => (rounds === 0 ? 'skipped (0 rounds)' : `up to ${rounds} rounds`);--// Dry-run cost model (#1576) — each planned step carries an estimated-// `estActions`: the number of cos actions it bills via recordDomainUsage('cos',-// { actions }), i.e. the unit the daily budget cap gates on. Surfacing it lets a-// user see, before starting, whether a large series will exhaust the cap on-// text/verify and never reach editorial. Estimates are approximate and lean-// toward the high end — convergence loops counted at their max rounds (they-// usually converge sooner), per-item steps at one action per item (retries-// excluded). A few steps cost nothing against the cap (editorialHealthGate,-// canonVerify) and carry estActions: 0. One known UNDER-count: the editorial-// review's per-comment auto-fixes each bill an extra action and scale with the-// number of blocking findings, which isn't knowable at plan time — so a heavy-// editorial pass can exceed its estimate.-//-// A bounded verify→resolve convergence loop (arc, beat-continuity, editorial)-// bills one action per verify plus (roughly) one per resolve; the final round-// never resolves (it converges or pauses). Estimate: rounds verifies +-// (rounds-1) resolves.-const convergenceLoopActions = (rounds) => (rounds <= 0 ? 0 : 2 * rounds - 1);--// Sum a dry-run plan's per-step estimates into run totals. `estActions` is the-// budget-relevant total (cos daily-cap units); `estLlmCalls` aggregates the-// check-pass fan-out (editorialChecks bills a single cos action but issues many-// LLM calls — see the rough proxy at its plan.push). Pure — safe to call at-// broadcast time and in tests.-function summarizePlanCost(plan) {- return (Array.isArray(plan) ? plan : []).reduce(- (acc, step) => ({- estActions: acc.estActions + (Number.isFinite(step?.estActions) ? step.estActions : 0),- estLlmCalls: acc.estLlmCalls + (Number.isFinite(step?.estLlmCalls) ? step.estLlmCalls : 0),- }),- { estActions: 0, estLlmCalls: 0 },- );-}--// When true, a comic-target run with `includeVisual` proceeds past the text +-// editorial terminal into draft cover/page rendering (see runVisualDraft).-export const VISUAL_DRAFT_ENABLED = true;--// Which severities block each verify/review gate (low is informational) is now-// PER-SERIES configurable (#1616): the defaults (arc/beatContinuity → high+medium,-// editorial → high) live in `lib/editorial/severityConfig.js` and a series may-// override any gate. `startSeriesAutopilot` resolves each gate's blocking Set-// once via `resolveBlockingSet(series.blockingSeverities, gate)` and stamps it on-// `record.options.blockingSets` so every read site uses the same resolved set.--// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).-const CHILD_POLL_MS = 750;--// ----------------------------------------------------------------------------// Pure next-step resolver — the heart of the conductor (no I/O; unit-tested).-// -----------------------------------------------------------------------------const setHas = (s, v) => (s instanceof Set ? s.has(v) : Array.isArray(s) ? s.includes(v) : false);--const byNumber = (a, b) => (a?.number ?? 9999) - (b?.number ?? 9999);--// The script stages a series must have drafted to be "story-ready", derived-// from its targetFormat. prose is the intermediate source the scripts adapt-// from — we gate on the final scripts so a script-first import (prose empty,-// script authored) is already considered ready and never regenerated.-export function requiredScriptStages(series, options = {}) {- const fmt = series?.targetFormat || 'comic+tv';- // Per-run format restriction: a multi-format (comic+tv) series can be driven- // to just one format's scripts in a single autopilot run — e.g. "produce the- // comic draft only, skip the 24 teleplays." `options.targetFormats` is a- // subset of ['comic','tv']; absent/empty means "all formats the series wants".- const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length- ? options.targetFormats- : null;- const wantComic = fmt.includes('comic') && (!restrict || restrict.includes('comic'));- const wantTv = fmt.includes('tv') && (!restrict || restrict.includes('tv'));- const stages = [];- if (wantComic) stages.push('comicScript');- if (wantTv) stages.push('teleplay');- // Never strand the run with zero required script stages (which would mark every- // issue text-ready with no script authored). If the restriction excludes- // everything this series supports, ignore it and fall back to the series' own- // formats.- if (stages.length === 0) return requiredScriptStages(series);- return stages;-}--export function isComicTarget(series) {- return (series?.targetFormat || 'comic+tv').includes('comic');-}--// Does THIS run want the comic format? `isComicTarget` alone keys off the-// series' declared format, but a per-run `options.targetFormats` restriction can-// scope a comic+tv series to TV only — in which case the comic-only steps-// (scriptVerify, visual draft) must NOT run, or a TV-only pass would enter-// comic-script verification with no comicScript and pause on an unparseable-// script. Mirrors the restriction logic in requiredScriptStages: an empty/absent-// restriction (or one that excludes everything the series supports) means "all-// formats the series wants", so this stays true for the default whole-series run.-export function wantsComic(series, options = {}) {- if (!isComicTarget(series)) return false;- const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length- ? options.targetFormats- : null;- if (!restrict) return true;- // If the restriction excludes every format the series supports, requiredScriptStages- // ignores it (never strand the run) — match that here so the gates agree.- const wantComic = restrict.includes('comic');- const wantTv = restrict.includes('tv') && (series?.targetFormat || '').includes('tv');- if (!wantComic && !wantTv) return true; // restriction is a no-op → whole series- return wantComic;-}--// Effective "produce draft visuals?" decision. The `target` option overrides-// the `includeVisual` flag: 'text' forces text-only (no canon gate, no render),-// 'visual' forces visuals, and 'auto' (the default) honors `includeVisual`-// (which itself defaults true). Without this, a `target:'text'` request on a-// comic series would still run canonVerify + queue draft renders.-export function wantsVisual(options = {}) {- if (options.target === 'text') return false;- if (options.target === 'visual') return true;- return options.includeVisual !== false;-}--function orderedIssues(issues) {- return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesByPosition);-}--function textReady(issue, series, options = {}) {- return requiredScriptStages(series, options).every((stageId) => isStageReady(issue.stages?.[stageId]));-}--// An issue "has beats" once its idea stage carries expanded beat text-// (idea.output) — the unit the whole-manuscript beat-continuity pass (#1510)-// reads. isStageReady(idea) is exactly that: status ready/edited AND non-empty-// output.-function issueHasBeats(issue) {- return isStageReady(issue?.stages?.idea);-}--// Structural script gate (pure): does the comic script parse into >=1 page with-// >=1 panel? Cheap, no LLM — this is the Phase-1 "verify the scripts work".-export function scriptStructurallyReady(issue) {- const output = issue.stages?.comicScript?.output || '';- if (!output.trim()) return false;- const { pages } = parseComicScript(output);- if (!Array.isArray(pages) || pages.length === 0) return false;- return pages.some((p) => Array.isArray(p.panels) && p.panels.length > 0);-}--// A render slot counts as "enqueued" once it carries a jobId or a stamped-// filename (proof or final). Draft rendering only kicks off proof renders, but-// we accept either so a re-run never re-renders a slot the user already-// finalized manually.-// Include the legacy pre-proof/final fields (`imageJobId`/`filename`) the-// sanitizer still preserves on upgraded projects — otherwise an-// already-rendered legacy slot reads as un-enqueued and gets re-rendered.-const slotEnqueued = (slot) => !!(- slot && (slot.proofImage?.jobId || slot.proofImage?.filename- || slot.finalImage?.jobId || slot.finalImage?.filename- || slot.imageJobId || slot.filename)-);-const pageEnqueued = (page) => !!(- page && (page.proofImage?.jobId || page.proofImage?.filename- || page.finalImage?.jobId || page.finalImage?.filename- || page.imageJobId || page.filename)-);--/**- * Has an issue's comic art been drafted? True once pages exist, the front cover- * is enqueued, any authored back cover is enqueued, and every page that HAS- * panels is enqueued. Pages with no panels can't be rendered, so they don't- * block readiness.- */-export function visualReady(issue) {- const cp = issue.stages?.comicPages;- const pages = Array.isArray(cp?.pages) ? cp.pages : [];- if (pages.length === 0) return false;- if (!slotEnqueued(cp?.cover)) return false;- if (!slotEnqueued(cp?.backCover)) return false; // always drafted (renderer has a fallback)- return pages.every((p) => (Array.isArray(p.panels) && p.panels.length > 0 ? pageEnqueued(p) : true));-}--/**- * Return the first unmet step for a series given its canonical records and the- * in-run accumulator (`runState`). Pure — caller supplies fresh state.*- * runState fields consulted (all optional): arcVerified, editorialReviewed,- * reverseOutlineRefreshed (booleans); beatsAttempted, textAttempted, scriptChecked (Set|array of ids).- * The *attempted* sets stop a perpetually-failing step (an issue whose LLM run- * keeps erroring) from looping forever — the conductor records an attempt even- * on failure, so the resolver moves past it within one run.+ * This file had grown to 2,541 lines mixing config resolution, pure step+ * resolution, session/SSE plumbing, a dozen step runners, dry-run planning and+ * the orchestrator. Issue #2842 split it into ./seriesAutopilot/* the same way+ * #1152 split `arcPlanner.js`; this barrel re-exports everything so existing+ * `from './seriesAutopilot.js'` imports keep working. New code may import the+ * focused module directly.*/-export function resolveNextStep(series, issues, runState = {}, options = {}) {- const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];- const ordered = orderedIssues(issues);-- // STEP 1 — arc. Also (re)generate when there are no seasons at all: an- // arc-only series (arc text present, seasons: []) has nothing for the- // episode/issue steps to expand, and would otherwise sail through verify/- // review of an empty issue list and be marked done with no volumes. The- // attempted-guard stops a re-loop if arc generation yields no seasons (the- // dispatch pauses in that case).- const noArc = !series?.arc?.logline && !series?.arc?.summary;- if (!runState.arcAttempted && (noArc || seasons.length === 0)) {- return { kind: 'generateArc', reason: seasons.length === 0 && !noArc ? 'series has no volumes' : 'series has no arc' };- }-- // STEP 2 — a season with zero issues (in season order). Skip volumes already- // attempted this run so an empty episode generation can't re-loop (the- // dispatch pauses when it produces no issues).- for (const season of seasons) {- if (setHas(runState.episodesAttempted, season.id)) continue;- const inSeason = ordered.filter((i) => i.seasonId === season.id);- if (inSeason.length === 0) {- return { kind: 'generateEpisodes', seasonId: season.id, reason: `volume ${season.number ?? '?'} has no issues` };- }- }-- // STEP 3 — arc verification (once per run; bounded loop happens in dispatch).- if (!runState.arcVerified) {- return { kind: 'verifyArc', reason: 'arc not yet verified this run' };- }-- // STEP 3.5 — foundation-quality gate (#2176). After the arc/volumes exist and- // arc structure is verified, judge the whole foundation (world / characters /- // arc) BEFORE the expensive beat/text stages and iterate on the weakest- // dimension until it clears the threshold. Once per run (bounded loop happens- // in dispatch). Gated on `foundationGate` being enabled AND a non-zero round- // budget — a disabled/0-round gate is treated as already satisfied so the- // resolver falls straight through to beats (the dispatch never runs).- if (!runState.foundationGated- && options.foundationGate !== false- && options.maxFoundationRounds !== 0) {- return { kind: 'foundationGate', reason: 'foundation not yet judged this run' };- }-- // STEP 4a — per-volume beat sheets (skip volumes already attempted this run).- for (const season of seasons) {- if (setHas(runState.beatsAttempted, season.id)) continue;- const inSeason = ordered.filter((i) => i.seasonId === season.id);- if (inSeason.some((i) => !isStageReady(i.stages?.idea))) {- return { kind: 'beatSheet', seasonId: season.id, reason: `beats missing in volume ${season.number ?? '?'}` };- }- }-- // STEP 4a.5 — whole-manuscript beat continuity (#1510). Once every volume's- // beats exist (the 4a loop above is exhausted), run ONE cross-issue beat-level- // pass BEFORE the expensive text/script generation — catching dropped- // cliffhangers, finale drift, unlanded through-lines, and duplicated "firsts"- // at the cheap beat altitude instead of after 24 full scripts exist. Only- // meaningful when at least one issue actually carries beats; a synopsis-only- // run has nothing beat-level to check (and would just duplicate arc verify),- // so it's skipped without ever marking the gate.- if (!runState.beatContinuityChecked && ordered.some(issueHasBeats)) {- return { kind: 'beatContinuity', reason: 'whole-manuscript beat continuity not yet checked this run' };- }-- // STEP 4b — per-issue text stages (prose + required scripts).- for (const issue of ordered) {- if (setHas(runState.textAttempted, issue.id)) continue;- if (!textReady(issue, series, options)) {- return { kind: 'textStages', issueId: issue.id, reason: 'prose / scripts not ready' };- }- }-- // STEP 4c — structural script gate (comic targets only). Gate on wantsComic,- // not bare isComicTarget, so a TV-only run of a comic+tv series doesn't enter- // comic-script verification with no comicScript (which would pause on an- // unparseable script).- if (wantsComic(series, options)) {- for (const issue of ordered) {- if (setHas(runState.scriptChecked, issue.id)) continue;- return { kind: 'scriptVerify', issueId: issue.id, reason: 'comic script not yet structurally verified' };- }- }-- // STEP 5 — series-level editorial review via the manuscript editor (once).- if (!runState.editorialReviewed) {- return { kind: 'editorialReview', reason: 'editorial review not yet run this run' };- }-- // STEP 5.1 — refresh the reverse-outline scene segmentation (#1349). Runs AFTER- // the editorial completeness pass (STEP 5, which may edit the manuscript) and- // BEFORE the registry checks (5.2) so the scene-consuming checks read fresh- // scenes. The handler self-gates: a no-op (no budget) when no enabled check- // reads the outline or the stored outline is already fresh.- if (!runState.reverseOutlineRefreshed) {- return { kind: 'reverseOutline', reason: 'reverse-outline segmentation not yet refreshed this run' };- }-- // STEP 5.2 — registry-driven editorial checks (#1284). Runs the enabled- // editorial checks once per run and seeds their findings into the same- // manuscript-review comment set. A no-op when no checks are enabled.- if (!runState.editorialChecksReviewed) {- return { kind: 'editorialChecks', reason: 'editorial checks not yet run this run' };- }-- // STEP 5.3 — editorial health convergence gate (#1316). After BOTH editorial- // passes have seeded their findings, read the aggregate "ready" signal (no open- // findings above the configured readiness gate). The completeness loop only- // gates on its OWN high findings; the registry checks (5.2) can surface fresh- // blockers after it converged, so this final gate reconciles the whole review- // before visuals. Pauses with the residual blockers when not clean.- if (!runState.editorialHealthReady) {- return { kind: 'editorialHealthGate', reason: 'editorial health not yet confirmed clean this run' };- }-- // STEP 5.4 — iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in.- // Runs AFTER the editorial health gate is clean (so the manuscript is- // structurally sound) and BEFORE canon/visuals — each cycle judges every- // drafted issue, revises the weakest through adversarial cuts under a- // keep/revert score gate, and stops on plateau / hedged-convergence / maxCycles.- // Pure-function-of-state like every other step: cycle counters + convergence- // live in runState (revisionCyclesRun / revisionConverged), so a resume picks up- // mid-loop with no stored cursor. `revisionConverged` is set by the dispatch- // once a stop condition fires; until then we route back here while cycles remain.- if (options.revisionEnabled- && !runState.revisionConverged- && (runState.revisionCyclesRun || 0) < (options.revisionMaxCycles ?? 1)) {- return { kind: 'revisionCycle', reason: `iterate-to-quality revision cycle ${(runState.revisionCyclesRun || 0) + 1}` };- }-- // STEP 5.5 — canon descriptive integrity. Before ANY visual production, every- // canon noun that appears where it'd be drawn must be described (an artist- // can't render a name). Runs once per run; the gate blocks (pauses) on- // undescribed drawn nouns. Only relevant when visuals will be produced.- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options) && !runState.canonVerified) {- return { kind: 'canonVerify', reason: 'canon descriptive integrity not yet verified this run' };- }-- // STEP 6 — draft visuals (cover + back + all interior pages).- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {- for (const issue of ordered) {- if (setHas(runState.visualDrafted, issue.id)) continue;- if (visualReady(issue)) continue;- return { kind: 'visualDraft', issueId: issue.id, reason: 'comic pages not yet drafted' };- }- }-- // STEP 7 — teaser video deliverable (CDO Phase 3, #2185, opt-in, default off).- // After every issue is text-ready + drafted, OPTIONALLY mint + start a Creative- // Director video project seeded from each issue. Gated on wantsTeaser (which- // itself requires visuals). Attempted-once per issue this run so a started (or- // failed) teaser can't re-loop the resolver back here.- if (VISUAL_DRAFT_ENABLED && wantsTeaser(options) && wantsComic(series, options)) {- for (const issue of ordered) {- if (setHas(runState.teaserProduced, issue.id)) continue;- return { kind: 'produceTeaser', issueId: issue.id, reason: 'teaser video not yet produced' };- }- }-- return { kind: 'done' };-}--// ----------------------------------------------------------------------------// Run registry helpers (mirror editorialAnalysisRunner.js).-// -----------------------------------------------------------------------------export function isAutopilotActive(seriesId) {- const run = runs.get(seriesId);- return !!run && !run.finished;-}--export function attachClient(seriesId, res) {- return attachSseClient(runs, seriesId, res);-}--export function cancelSeriesAutopilot(seriesId) {- const run = runs.get(seriesId);- if (!run || run.finished) return false;- run.cancelRequested = true;- // Emit an immediate acknowledgement frame so the UI can switch to a- // "cancelling…" state right away. Cancellation is cooperative and checked- // between steps (the terminal `canceled` frame follows once the active- // step/LLM call returns) — without this ack the user sees no feedback until- // the loop unwinds, which can be the length of a long in-flight LLM call (#1617).- broadcastSse(run, { type: 'cancel:acknowledged', runId: run.runId, requestedAt: new Date().toISOString() });- // Propagate to the currently-delegated child so cancel is responsive- // mid-step instead of only between steps.- const child = run.activeChild;- if (child?.kind === 'beats') volumeBeatsRunner.cancelVolumeBeatsRun(child.id);- else if (child?.kind === 'text') autoRunner.cancelAutoRun(child.id);- return true;-}--function broadcast(seriesId, payload) {- const run = runs.get(seriesId);- if (!run) return;- broadcastSse(run, payload);- // Mirror every frame onto the in-process bus (CDO Phase 3, #2185) so a- // server-side consumer (CD plan step) sees the same progress/pause/terminal- // frames as an SSE client. Emit is best-effort — a listener throw must never- // abort the run (this runs inside the fire-and-forget coordinator).- try {- autopilotEvents.emit(seriesId, payload);- } catch (err) {- console.log(`⚠️ autopilot: event emit failed for ${seriesId.slice(0, 12)}: ${err.message}`);- }-}--function scheduleCleanup(seriesId, record) {- record.cleanupTimer = setTimeout(() => {- if (runs.get(seriesId) !== record) return;- for (const c of record.clients) c.end();- runs.delete(seriesId);- }, SSE_CLEANUP_DELAY_MS);-}--// Thin persisted marker for resume/paused UI + boot recovery. NOT a step-// cursor — see module header. Best-effort; a marker write must never abort a run.-async function persistMarker(seriesId, patch) {- await updateSeries(seriesId, {- autopilot: { ...patch, updatedAt: new Date().toISOString() },- }).catch((err) => {- console.log(`⚠️ autopilot: marker write failed for ${seriesId.slice(0, 12)}: ${err.message}`);- });-}--// File a CoS task for a capability/quality gap the autopilot can't resolve on-// its own (a script that won't parse, a render that keeps failing, a stalled-// verify, a run-ending error). Opt-in via `options.fileGaps`; never fires in-// dry-run. The first description line is kept STABLE per (series, gapKind,-// issue) so cosTaskStore.addTask's pending/in_progress dedup collapses repeats-// instead of spamming a task per page / per run. Best-effort — a task-store-// failure must never abort the autopilot.-async function fileGap(record, sId, { gapKind, issueId = null, summary, context = '' }) {- if (!record.options.fileGaps || record.mode !== 'execute') return;- const idTag = `series ${sId}${issueId ? ` issue ${issueId}` : ''}`;- const description = `Autopilot ${gapKind} gap — ${idTag}\n\n${summary}`;- const result = await cosTaskStore.addTask({ description, context, app: 'pipeline' }, 'user')- .catch((err) => { console.log(`⚠️ autopilot: fileGap (${gapKind}) failed: ${err.message}`); return null; });- if (result && !result.duplicate) {- broadcast(sId, { type: 'gap:filed', gapKind, issueId, taskId: result.id });- }-}--// Pause escalation (#1615): post an in-app notification when a run pauses so the-// user is told actively, not only when they happen to open the status page. The-// SSE `paused` frame still fires for an attached client; this is the persistent-// out-of-band signal for a user who isn't watching. Opt-out via-// `options.notifyOnPause` / the persisted setting (default on); never fires in-// dry-run. Prior pause notifications for this series are cleared first so a-// resume→pause cycle leaves exactly one current banner instead of a stack, and-// the metadata field is series-scoped so removeByMetadata can't touch unrelated-// notifications. Best-effort — a notification failure must never abort the run.-// Drop any pause banner for this series. Called before posting a fresh one (so a-// resume→pause cycle leaves exactly one) AND when a new execute run starts (so a-// run resumed from a pause that then completes/errors doesn't leave a stale-// "paused" banner + dead resume link). Series-scoped metadata so it can't touch-// unrelated notifications. Best-effort.-async function clearPauseNotice(sId) {- await removeByMetadata('autopilotPauseSeriesId', sId).catch(() => {});-}--async function notifyPause(record, sId, { reason, pauseKind = null, currentStep = null }) {- if (record.options.notifyOnPause === false || record.mode !== 'execute') return;- const series = await getSeries(sId).catch(() => null);- const seriesName = series?.name || 'a series';- await clearPauseNotice(sId);- await addNotification({- type: NOTIFICATION_TYPES.AUTOPILOT_PAUSED,- title: `Autopilot paused — ${seriesName}`,- description: reason || 'The run paused and needs human review before it can continue.',- priority: PRIORITY_LEVELS.HIGH,- link: `/pipeline/series/${sId}`,- metadata: { autopilotPauseSeriesId: sId, runId: record.runId, pauseKind, currentStep },- }).catch((err) => { console.log(`⚠️ autopilot: pause notification failed for ${sId.slice(0, 12)}: ${err.message}`); });-}-// Series Autopilot threads BOTH its run provider AND its run model as SOFT-// defaults, NOT hard overrides — so a deliberate per-stage pin (Prompts page /-// stage-config.json) still wins for that stage, matching what verifyComicScript-// already does (#1514 for provider; #1558 for model). Each run-level value lands-// on stageRunner's soft channel (`providerDefault` tier 3 / `modelDefault`): it-// applies only to UNPINNED stages and soft-falls-through (to the active provider-// / the provider's default model) when unavailable, rather than throwing-// PROVIDER_OVERRIDE_UNAVAILABLE or beating a stage's deliberate pin the way a-// hard override would. For the model dimension "unpinned" means a stage carrying-// only a *tier* value (default/quick/coding/heavy) — the run model overrides the-// tier but still loses to a deliberate explicit-model pin (see-// stageRunner.resolveModelHint). Before #1558 the model was threaded as a hard-// `modelOverride`, which let the run model beat even an explicit stage pin.-//-// Two shapes because the delegated services disagree on field names: the-// arc/episode/verify passes take `providerDefault`/`modelDefault`; the child-// runners (volumeBeatsRunner, autoRunner) and the `providerId`-style services-// take `providerIdDefault`/`modelIdDefault`. Each maps its incoming defaults to-// stageRunner's `providerDefault`/`modelDefault` at the leaf call while keeping-// its existing hard `providerOverride`/`providerId` + `modelOverride`/`model`-// params untouched for manual route callers.-const providerOverrideOpts = (record) => ({- providerDefault: record.options.providerOverride,- modelDefault: record.options.modelOverride,-});-const providerIdOpts = (record) => ({- providerIdDefault: record.options.providerOverride,- modelIdDefault: record.options.modelOverride,- // Multi-candidate draft gate (#2169): bill one cos action per re-roll and stop- // re-rolling when the daily budget is spent. Only ever invoked by- // generateStage's runDraftGate on a judgeable stage with draftAttempts > 1 — a- // no-op for every other stage/run. Check-then-bill so a skipped (budget-out)- // attempt isn't charged. Returns false to halt further attempts (keep the best- // so far); true when the attempt may proceed.- chargeAction: async () => {- const budget = await getDomainBudgetStatus('cos');- if (!budget.withinBudget) return false;- await recordDomainUsage('cos', { actions: 1 });- return true;- },-});--// Pause result when the cos action budget is exhausted, else null. Used to gate-// EACH billable call inside the multi-call verify/editorial convergence loops —-// the conductor's per-step budget check only fires once before the step, so-// without this a single step could bill several actions past the daily cap.-// gapFiled:true so a budget pause doesn't also file a generic stalled gap-// (mirrors the conductor's own loop-level budget pause, which files none).-async function budgetPause() {- const budget = await getDomainBudgetStatus('cos');- if (budget.withinBudget) return null;- return { pause: true, gapFiled: true, reason: `daily cos ${budget.exceeded || 'actions'} budget reached` };-}--// ----------------------------------------------------------------------------// Step dispatch.-// -----------------------------------------------------------------------------async function waitForChild(isActive, record) {- while (isActive()) {- if (record.cancelRequested) return;- await sleep(CHILD_POLL_MS);- }-}--async function runArcVerify(seriesId, record) {- const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)- ? record.options.maxArcVerifyRounds- : MAX_ARC_VERIFY_ROUNDS;- // maxRounds === 0 means "skip verification entirely" — accept the arc as-is.- if (maxRounds === 0) {- record.runState.arcVerified = true;- return {};- }- let convergence = { best: null, sinceBest: 0 };- for (let round = 1; round <= maxRounds; round += 1) {- if (record.cancelRequested) return { canceled: true };- const beforeVerify = await budgetPause();- if (beforeVerify) return beforeVerify;- const { issues } = await verifyArc(seriesId, providerOverrideOpts(record));- await recordDomainUsage('cos', { actions: 1 });- const blocking = issues.filter((i) => record.options.blockingSets.arc.has(i.severity));- broadcast(seriesId, {- type: 'verify:round', scope: 'arc', round, findings: issues.length, blocking: blocking.length,- });- if (blocking.length === 0) {- record.runState.arcVerified = true;- return {};- }- if (round === maxRounds) {- return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };- }- // Divergence guard (#1571): if the resolve passes stop reducing blocking- // findings, bail now rather than burning the remaining rounds + budget.- convergence = trackConvergence(convergence, blocking.length);- if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {- return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('arc', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };- }- if (record.cancelRequested) return { canceled: true };- // resolveVerifyIssues bills another action — recheck the budget so a single- // step can't overspend the daily cap mid-loop.- const beforeResolve = await budgetPause();- if (beforeResolve) return beforeResolve;- const resolved = await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });- await recordDomainUsage('cos', { actions: 1 });- broadcast(seriesId, {- type: 'resolve:round', scope: 'arc', round,- episodesEdited: Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0,- });- }- return {};-}--// Whole-manuscript beat-continuity convergence loop (#1510). Mirrors-// runArcVerify one altitude down: verify the whole-book beat corpus, and on-// blocking findings resolve them by rewriting the offending issues' beats in-// place (resolveBeatContinuity → applyBeatResolutions, no beat-sheet-// regeneration), then re-verify. Bounded; pauses with the residual on-// non-convergence. Each verify + each resolve is budget-gated and bills one cos-// action, like the arc loop.-async function runBeatContinuity(seriesId, record) {- const maxRounds = Number.isInteger(record.options.maxBeatContinuityRounds)- ? record.options.maxBeatContinuityRounds- : MAX_BEAT_CONTINUITY_ROUNDS;- // maxRounds === 0 means "skip the beat-continuity gate entirely".- if (maxRounds === 0) {- record.runState.beatContinuityChecked = true;- return {};- }- let convergence = { best: null, sinceBest: 0 };- for (let round = 1; round <= maxRounds; round += 1) {- if (record.cancelRequested) return { canceled: true };- const beforeVerify = await budgetPause();- if (beforeVerify) return beforeVerify;- const { issues } = await analyzeBeatContinuity(seriesId, providerOverrideOpts(record));- await recordDomainUsage('cos', { actions: 1 });- const blocking = issues.filter((i) => record.options.blockingSets.beatContinuity.has(i.severity));- broadcast(seriesId, {- type: 'verify:round', scope: 'beatContinuity', round, findings: issues.length, blocking: blocking.length,- });- if (blocking.length === 0) {- record.runState.beatContinuityChecked = true;- return {};- }- if (round === maxRounds) {- return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('beatContinuity', maxRounds, blocking.length), residual: blocking };- }- // Divergence guard (#1571): bail when the resolve passes stop reducing blocking findings.- convergence = trackConvergence(convergence, blocking.length);- if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {- return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('beatContinuity', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };- }- if (record.cancelRequested) return { canceled: true };- // resolveBeatContinuity bills another action — recheck the budget so a- // single step can't overspend the daily cap mid-loop.- const beforeResolve = await budgetPause();- if (beforeResolve) return beforeResolve;- const resolved = await resolveBeatContinuity(seriesId, { findings: blocking, ...providerOverrideOpts(record) });- await recordDomainUsage('cos', { actions: 1 });- broadcast(seriesId, {- type: 'resolve:round', scope: 'beatContinuity', round,- episodesEdited: Array.isArray(resolved?.episodesResolved)- ? resolved.episodesResolved.filter((e) => e?.corrected).length- : 0,- });- }- return {};-}--// Foundation-quality convergence loop (#2176). Mirrors runArcVerify but gates on-// a WEIGHTED SCORE (not a blocking-findings count): judge the whole foundation,-// and while it's below the threshold, target the weakest dimension, apply the-// fix through the owning service (universe refine / character expand / arc-// resolve — force:false, never a raw write), then re-judge. The re-judge is-// content-hash-cached, so an unchanged foundation short-circuits (no LLM) and-// can't loop. Bounded; pauses with the residual per-dimension findings on-// non-convergence. Each judge + each fix bills one cos action, budget-gated like-// the arc loop. The improve-loop convergence is tracked on the weighted score-// (higher = better), so divergence = the score failing to reach a NEW HIGH.-async function runFoundationGate(seriesId, record) {- const maxRounds = Number.isInteger(record.options.maxFoundationRounds)- ? record.options.maxFoundationRounds- : MAX_FOUNDATION_ROUNDS;- // 0 rounds (or disabled) means "skip the gate entirely" — accept the- // foundation as-is. The resolver already routes past a disabled gate, but a- // dispatch that arrives here with 0 rounds still short-circuits cleanly.- if (maxRounds === 0 || record.options.foundationGate === false) {- record.runState.foundationGated = true;- return {};- }- const threshold = Number.isFinite(record.options.foundationThreshold)- ? record.options.foundationThreshold- : DEFAULT_FOUNDATION_THRESHOLD;- const providerId = record.options.providerOverride;- const model = record.options.modelOverride;-- // Convergence tracker keyed on the weighted score (higher is better) — invert- // to a "distance below 10" so trackConvergence's fewer-is-better minimum logic- // applies unchanged (a new low distance = a new high score = progress).- let convergence = { best: null, sinceBest: 0 };- for (let round = 1; round <= maxRounds; round += 1) {- if (record.cancelRequested) return { canceled: true };- const beforeJudge = await budgetPause();- if (beforeJudge) return beforeJudge;- // Never force: judgeFoundation is content-hash-cached, so an unchanged- // foundation (a clean verdict from a prior run, or a fix that changed- // nothing) returns the cached score with no LLM call — this IS the fast-pass- // that stops an already-clean foundation looping. A real change (any fix, or- // a user edit) flips the pinned hash and re-judges automatically.- const snap = await judgeFoundation(seriesId, { providerId, model });- // A cached (content-hash unchanged) verdict did no LLM work — don't bill it.- if (!snap.cached) await recordDomainUsage('cos', { actions: 1 });- const score = snap.weightedScore ?? 0;- const weak = weakestDimension(snap.dimensions);- broadcast(seriesId, {- type: 'foundation:round', round, weightedScore: score, threshold, weakest: weak?.dimension || null,- });- if (score >= threshold) {- record.runState.foundationGated = true;- return {};- }- if (round === maxRounds || !weak) {- return {- pause: true,- pauseKind: 'maxRounds',- reason: foundationPauseReason(maxRounds, score, threshold),- residual: residualFindings(snap.dimensions),- };- }- // Divergence guard (#1571): bail when fixes stop improving the score.- convergence = trackConvergence(convergence, 10 - score);- if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {- return {- pause: true,- pauseKind: 'divergence',- reason: foundationDivergenceReason(score, threshold, DIVERGENCE_PATIENCE),- residual: residualFindings(snap.dimensions),- };- }- if (record.cancelRequested) return { canceled: true };- const beforeFix = await budgetPause();- if (beforeFix) return beforeFix;- const fix = await applyFoundationFix(seriesId, weak.dimension, {- finding: snap.dimensions?.[weak.dimension] || {},- providerOverride: providerId,- modelOverride: model,- });- await recordDomainUsage('cos', { actions: 1 });- broadcast(seriesId, {- type: 'foundation:fix', round, dimension: weak.dimension, applied: fix?.applied === true, reason: fix?.reason || null,- });- // A dimension whose owning service can't apply a fix (no linked universe, a- // fully-locked cast, nothing left to fill) would loop unproductively — treat- // an inapplicable fix as immediate non-convergence and pause for human- // review rather than burning the remaining rounds re-judging an unchanged- // foundation.- if (fix?.applied !== true) {- return {- pause: true,- pauseKind: 'inapplicable',- reason: `Foundation gate can't auto-fix the weakest dimension (${weak.dimension}): ${fix?.reason || 'no change applied'}. Strengthen it manually, or lower the threshold, and resume.`,- residual: residualFindings(snap.dimensions),- };- }- }- return {};-}--// Resolve the effective retry budget for a delegated child runner this run: a-// per-run `maxChildRetries` option wins, else the module default. Negative-// values clamp to 0 (single attempt).-function childRetryBudget(record) {- const v = record.options.maxChildRetries;- return Number.isInteger(v) ? Math.max(0, v) : MAX_CHILD_RETRIES;-}--// Delegate to a child SSE runner, block until it finishes, then VERIFY the child-// actually produced its target output before advancing (#1574). Shared by the-// beats and text steps. `checkReady` returns null when the output landed, or a-// `{ reason, residual }` describing what's still missing. On a miss the child is-// retried (skip-existing, so a retry only fills the gap) up to the run's retry-// budget; each attempt is budget-gated and bills one cos action. When the budget-// is exhausted the retries stop. If the output is still missing after the last-// attempt the work is marked attempted (so the resolver can't loop back here), an-// escalation frame is emitted, and a pause result is returned for human review —-// instead of the pre-#1574 silent skip that let a failed child reach 'done'.-async function runChildToCompletion(seriesId, record, {- attemptedSet, kind, id, start, isActive, checkReady,-}) {- const maxAttempts = childRetryBudget(record) + 1;- let miss = null;- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {- if (record.cancelRequested) return { canceled: true };- // Each child run bills one cos action — budget-gate every attempt so a- // retry can't overspend the daily cap (mirrors the verify loops).- const beforeStart = await budgetPause();- if (beforeStart) return beforeStart;- await start();- record.activeChild = { kind, id };- await waitForChild(() => isActive(id), record);- record.activeChild = null;- await recordDomainUsage('cos', { actions: 1 });- if (record.cancelRequested) return { canceled: true };- miss = checkReady ? await checkReady() : null;- if (!miss) {- attemptedSet.add(id);- return {};- }- if (attempt < maxAttempts) {- broadcast(seriesId, {- type: 'child:retry', kind, id, attempt, maxAttempts, reason: miss.reason,- });- }- }- // Output still missing after every attempt — escalate and pause. `pauseKind`- // keeps this pause classifiable alongside the verify/editorial loops'- // 'maxRounds'/'divergence' kinds (a child runner that couldn't produce output,- // distinct from a convergence gate that ran out of rounds).- attemptedSet.add(id);- broadcast(seriesId, {- type: 'child:escalate', kind, id, attempts: maxAttempts, reason: miss.reason,- });- return { pause: true, pauseKind: 'childFailed', reason: miss.reason, residual: miss.residual };-}--const runBeats = (seriesId, seasonId, record) => runChildToCompletion(seriesId, record, {- attemptedSet: record.runState.beatsAttempted,- kind: 'beats',- id: seasonId,- start: () => volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, { mode: 'skip-existing', ...providerIdOpts(record) }),- isActive: volumeBeatsRunner.isVolumeBeatsRunActive,- // Beats succeeded when every issue in the volume has a ready `idea` stage —- // the same predicate the resolver uses to decide a volume still needs beats.- // Before #1574 a failed beats run was silently marked attempted and only- // surfaced (if at all) when a downstream stage found `idea` empty.- checkReady: async () => {- const inSeason = (await listIssues({ seriesId })).filter((i) => i.seasonId === seasonId);- const missing = inSeason.filter((i) => !isStageReady(i.stages?.idea));- if (missing.length === 0) return null;- return {- reason: `beat generation for volume ${seasonId} did not produce beats for ${missing.length} issue(s)`,- residual: missing.map((i) => ({ severity: 'high', location: `issue ${i.number ?? '?'} / idea`, problem: 'beat sheet (idea stage) is still empty after the beats run (likely an LLM failure)' })),- };- },-});--const runText = (seriesId, issueId, record) => runChildToCompletion(seriesId, record, {- attemptedSet: record.runState.textAttempted,- kind: 'text',- id: issueId,- start: async () => {- // Only adapt the target format's script(s) — a single-format series shouldn't- // spend LLM calls populating the off-target script across every issue.- const preIssue = await getIssue(issueId);- const preSeries = await getSeries(preIssue.seriesId).catch(() => null);- const scripts = requiredScriptStages(preSeries, record.options);- // Forward the run's provider/model override so prose + scripts honor it like- // every other step (autoRunner threads these into generateStage).- await autoRunner.startAutoRunTextStages(issueId, { force: false, scripts, ...providerIdOpts(record) });- },- isActive: autoRunner.isAutoRunActive,- // A delegated text run can end with required stages still empty (the child's- // LLM call failed) — verify the required stages landed before advancing.- checkReady: async () => {- const issue = await getIssue(issueId);- const series = await getSeries(issue.seriesId).catch(() => null);- if (textReady(issue, series, record.options)) return null;- const missing = requiredScriptStages(series, record.options).filter((s) => !isStageReady(issue.stages?.[s]));- return {- reason: `text generation for issue ${issue.number ?? issueId} did not produce required stage(s): ${missing.join(', ')}`,- residual: missing.map((s) => ({ severity: 'high', location: `issue ${issue.number ?? '?'} / ${s}`, problem: 'stage is still empty after the text run (likely an LLM failure)' })),- };- },-});--async function runScriptVerify(sId, issueId, record) {- record.runState.scriptChecked.add(issueId);- const issue = await getIssue(issueId);-- // Gate 1 — STRUCTURAL (pure, cheap): does the script parse into pages/panels?- // This is the only structural validation before completion in text-only /- // visual-disabled comic runs, so a failure must BLOCK (pause), not just mark- // the issue checked — otherwise the run could report done with a script that- // can't become pages.- if (!scriptStructurallyReady(issue)) {- await fileGap(record, sId, {- gapKind: 'script-unparseable',- issueId,- summary: 'The comic script for this issue does not parse into pages/panels, so comic pages can\'t be extracted. It likely needs a manual fix or regeneration of the comicScript stage.',- context: `issueId=${issueId}`,- });- return {- pause: true,- gapFiled: true,- reason: `comic script for issue ${issue.number ?? issueId} does not parse into pages/panels`,- residual: [{ severity: 'high', location: `issue ${issue.number ?? '?'} / comicScript`, problem: 'script did not parse into pages/panels — cannot extract comic pages' }],- };- }-- // Gate 2 — CRAFT (LLM): does the script function as a comic script? This is- // ADVISORY — unlike arc continuity, script craft is subjective and the- // gating quality pass is the series-level editorial review, so blocking- // findings are surfaced + filed (not auto-rewritten, not a hard pause) and- // the autopilot keeps moving toward a draft. Wrapped so an LLM failure- // downgrades to a skip instead of aborting the whole run.- let issues = [];- try {- const result = await verifyComicScript(issueId, providerIdOpts(record));- issues = result.issues || [];- await recordDomainUsage('cos', { actions: 1 });- } catch (err) {- broadcast(sId, { type: 'step:skip', kind: 'scriptVerify', issueId, reason: `craft verify unavailable: ${(err?.message || err).toString().slice(0, 200)}` });- return {};- }- const blocking = issues.filter((i) => i.severity === 'high');- broadcast(sId, { type: 'verify:round', scope: 'script', issueId, round: 1, findings: issues.length, blocking: blocking.length });- if (blocking.length) {- await fileGap(record, sId, {- gapKind: 'script-craft',- issueId,- summary: `Comic script craft review found ${blocking.length} blocking issue(s): ${blocking.map((b) => b.problem).join(' | ').slice(0, 600)}`,- context: JSON.stringify(blocking).slice(0, 1000),- });- // #1572 — fileGap is advisory and only persists a gap task when fileGaps is- // on (mirror its predicate). Tally what was actually FILED so the terminal- // "complete" frame can qualify itself instead of silently reporting clean.- if (record.options.fileGaps && record.mode === 'execute') {- record.runState.scriptCraftGapIssues.add(issueId);- record.runState.scriptCraftBlocking += blocking.length;- }- }- return {};-}--async function runEditorial(sId, record) {- const maxRounds = Number.isInteger(record.options.maxEditorialRounds)- ? record.options.maxEditorialRounds- : MAX_EDITORIAL_ROUNDS;- // maxRounds === 0 means "skip the editorial gate entirely" — which includes- // the registry-driven editorial checks (the default info-dumping check is- // LLM-backed, so a skip run must not spend budget on it). Mark both reviewed- // so the resolver advances past editorialChecks too; the user can still run- // checks on demand via the route.- if (maxRounds === 0) {- record.runState.editorialReviewed = true;- // The reverse-outline refresh (#1349) only feeds the registry checks, so a run- // that skips the whole editorial gate must skip it too — mark it refreshed so- // the resolver advances past STEP 5.1 without spending budget.- record.runState.reverseOutlineRefreshed = true;- record.runState.editorialChecksReviewed = true;- // Skipping the editorial gate also skips its health convergence check (#1316)- // — the resolver must advance past editorialHealthGate too.- record.runState.editorialHealthReady = true;- return {};- }- let convergence = { best: null, sinceBest: 0 };- for (let round = 1; round <= maxRounds; round += 1) {- if (record.cancelRequested) return { canceled: true };- const beforeAnalyze = await budgetPause();- if (beforeAnalyze) return beforeAnalyze;- const { issues, runId } = await analyzeManuscriptCompleteness(sId, {- withEdits: true,- ...providerOverrideOpts(record),- });- await recordDomainUsage('cos', { actions: 1 });- const blocking = (issues || []).filter((i) => record.options.blockingSets.editorial.has(i.severity));- broadcast(sId, {- type: 'verify:round', scope: 'editorial', round, findings: (issues || []).length, blocking: blocking.length,- });- // Seed the manuscript-review comment set so the findings are visible in the- // manuscript editor regardless of auto-fix outcome.- await seedReviewFromFindings(sId, issues || [], { runId, mode: 'fresh' }).catch((err) => {- console.log(`⚠️ autopilot: seed editorial review failed for ${sId.slice(0, 12)}: ${err.message}`);- });- if (blocking.length === 0) {- record.runState.editorialReviewed = true;- return {};- }- if (round === maxRounds) {- return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('editorial', maxRounds, blocking.length), residual: blocking };- }- // Divergence guard (#1571): bail when the auto-fix passes stop reducing blocking findings.- convergence = trackConvergence(convergence, blocking.length);- if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {- return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('editorial', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };- }- // Bounded auto-fix: apply a fix for each open high-severity comment, then- // the loop re-analyzes. Each fix is wrapped so one bad anchor doesn't abort- // the pass (boundary use of try/catch — these call into LLM/file paths).- const review = await getReview(sId).catch(() => ({ comments: [] }));- const open = (review.comments || []).filter((c) => c.status === 'open' && record.options.blockingSets.editorial.has(c.severity));- for (const comment of open) {- if (record.cancelRequested) return { canceled: true };- // Each generated fix is its own LLM call — gate AND bill per comment so a- // multi-comment pass can't overspend or under-count the daily budget.- const beforeFix = await budgetPause();- if (beforeFix) return beforeFix;- try {- // Thread the run's provider/model override into fix GENERATION (an LLM- // call) so it honors the same provider as the review — without this the- // fix silently runs on the active/default provider (and its runtime- // fallback), which diverges from the run's chosen model and, when the- // default is rate-limited, degrades fixes onto a weak fallback. Accept- // is a deterministic edit application (no LLM), so it needs no override.- if (!comment.fix) await generateManuscriptFix(sId, { commentId: comment.id, ...providerOverrideOpts(record) });- await acceptManuscriptFix(sId, { commentId: comment.id });- await recordDomainUsage('cos', { actions: 1 });- } catch (err) {- console.log(`⚠️ autopilot: editorial fix ${comment.id} failed: ${(err?.message || err)}`);- }- }- }- return {};-}--// STEP 5.1 — refresh the reverse-outline scene segmentation (#1349) before the-// registry-driven editorial checks (5.2), so the scene-consuming checks read the-// current draft's scenes rather than a segmentation staled by this run's editorial-// edits. Two cheap pre-gates keep this from spending budget needlessly:-// 1. skip entirely when no enabled editorial check declares a reverse-outline-// source (mirrors the runner's own needsReverseOutline gate), and-// 2. skip when the stored outline is already fresh — using getReverseOutline's-// canonical `stale` flag, NOT a stale-check reimplemented here.-// Only when a regenerate will actually occur do we gate the daily budget and bill a-// cos action — the same shape as runEditorialChecksPass, which gates+bills only when-// an enabled LLM check will actually run. `force:false`-// is a belt-and-suspenders second guard against the stored outline going fresh-// between the pre-check and the call. Failures are advisory (logged), never block.--// #1575 — the per-run editorial-check subset (null = all enabled). Absent/empty-// is normalized to null so EVERY consumer (this reverse-outline gate, the budget-// plan, the checks run) resolves the identical set — otherwise a subset of checks-// that skip the outline could still trigger/bill the refresh keyed off the global-// enabled set, or the gate could bill against checks the run skips.-const editorialSubsetIds = (options) =>- Array.isArray(options?.editorialCheckIds) && options.editorialCheckIds.length- ? options.editorialCheckIds- : null;--async function runReverseOutlineRefresh(sId, record) {- if (record.cancelRequested) return { canceled: true };- const settings = await getSettings();- const checkIds = editorialSubsetIds(record.options);- // Gate 1 — sources-only pre-filter: does any enabled check (narrowed to this- // run's subset) even DECLARE the outline as a source? If not, nothing to do —- // and a subset that skips outline-consuming checks must not pay for a refresh- // those checks would have triggered.- if (!enabledChecksConsumeReverseOutline(settings, checkIds)) {- record.runState.reverseOutlineRefreshed = true;- return {};- }- // Gate 2 — is the stored outline stale (or never generated against a draftable- // manuscript)? `no-content` (nothing drafted) needs no outline; `none` (draftable- // but never segmented) and a `complete`-but-`stale` outline both need a regen.- const current = await getReverseOutline(sId).catch(() => null);- const needsRegen = !!current- && current.status !== 'no-content'- && (current.status === 'none' || current.stale === true);- if (!needsRegen) {- record.runState.reverseOutlineRefreshed = true;- return {};- }- // Gate 3 (#1614) — gate-aware consumption. A check that DECLARES the outline as- // a source still won't run if its runtime gate declines for this series (e.g. a- // canon-less roster). Evaluate each consumer's gate against the current outline- // and skip the refresh when none would run. Gate on SCENE PRESENCE, not- // `status`: the precondition is "there's scene content to evaluate gates- // against" — a never-generated (`status:'none'`) or empty outline has none, so- // we bootstrap the first generation unconditionally rather than chicken-and-egg- // ourselves out of it. enabledChecksConsumeReverseOutline only trusts a- // DECLINING gate that didn't read the outline (the refresh regenerates it, so- // an outline-content gate's stale verdict can't be trusted and keeps the check- // a consumer) — so a scoped run of only outline-gated checks still refreshes.- if (Array.isArray(current.scenes) && current.scenes.length > 0) {- const gateCtx = await buildReverseOutlineGateContext(sId, { outline: current }).catch(() => null);- if (gateCtx && !enabledChecksConsumeReverseOutline(settings, checkIds, gateCtx)) {- record.runState.reverseOutlineRefreshed = true;- return {};- }- }- // A regenerate WILL spend one LLM call — gate the budget and bill, like the- // other LLM passes. Bridge autopilot cancellation into the stage's AbortSignal.- const beforeRefresh = await budgetPause();- if (beforeRefresh) return beforeRefresh;- const signal = { get aborted() { return record.cancelRequested; } };- const regen = (force) => generateReverseOutline(sId, { ...providerIdOpts(record), force, signal })- .catch((err) => {- console.log(`⚠️ autopilot: reverse-outline refresh failed for ${sId.slice(0, 12)}: ${err.message}`);- return null;- });- let result = await regen(false);- // Canceled mid-pass — don't bill, don't mark refreshed; let the loop unwind.- if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };- // (#1614) A `cached:true` result means the manuscript hash still matched the- // stored outline at generate time. Re-confirm staleness against the LIVE- // manuscript within this run: if a concurrent edit moved the manuscript again- // after that cache check, the cached outline is now stale and the downstream- // checks would read it — force exactly one regen so they don't.- if (result?.cached === true) {- const after = await getReverseOutline(sId).catch(() => null);- if (after?.stale === true) {- result = await regen(true);- if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };- }- }- // Bill ONLY when the call actually regenerated (an LLM run). A `cached` result- // (outline still fresh in the race window) or a `no-content` series spent nothing.- // No verify:round broadcast here — a refresh isn't a review round (it produces- // scenes, not findings); the conductor's generic step:start/step:complete already- // surface "Refreshing scene segmentation…" / "done" to the UI.- if (result && result.cached !== true && result.status !== 'no-content') {- await recordDomainUsage('cos', { actions: 1 });- }- record.runState.reverseOutlineRefreshed = true;- return {};-}--// STEP 5.2 — run the registry-driven editorial checks once per run, seeding-// their findings into the same manuscript-review comment set. Only LLM-kind-// checks cost tokens, so gate the daily budget AND bill a cos action only when-// an enabled LLM check will actually run — a deterministic-only (or all-checks--// disabled) run does cheap local work and must neither pause on an exhausted-// budget nor consume quota. Failures are surfaced (logged) but never block the-// run — editorial checks are advisory.-async function runEditorialChecksPass(sId, record) {- if (record.cancelRequested) return { canceled: true };- const settings = await getSettings();- // #1575 — narrow the pass + its budget gate to this run's subset (null = all- // enabled). The gate (buildEditorialCheckPlan) and the run (runEditorialChecks)- // must resolve the SAME set so billing and execution agree.- const checkIds = editorialSubsetIds(record.options);- const plan = await buildEditorialCheckPlan(sId, { checkIds, settings });- const hasLlmCheck = plan.checks.some((c) => c.kind === 'llm');- if (hasLlmCheck) {- const beforeChecks = await budgetPause();- if (beforeChecks) return beforeChecks;- }- // Bridge autopilot cancellation into the runner's cooperative AbortSignal so a- // mid-pass /autopilot/cancel stops before the next check and skips seeding- // (the runner re-checks `signal.aborted` after each check). A live getter- // reflects `record.cancelRequested` without a separate controller to manage.- const signal = { get aborted() { return record.cancelRequested; } };- // #1578 — forward the runner's per-check check:start/check:complete frames up- // the autopilot SSE stream (tagged scope:'editorialChecks' so the UI groups- // them with the editorialChecks verify:round). Without this the only signal- // during a long (issues × checks) pass is the single terminal verify:round- // total — no per-check progress or severity breakdown.- const onProgress = (event) => broadcast(sId, { ...event, scope: 'editorialChecks' });- const result = await runEditorialChecks(sId, { ...providerOverrideOpts(record), checkIds, settings, signal, onProgress }).catch((err) => {- console.log(`⚠️ autopilot: editorial checks failed for ${sId.slice(0, 12)}: ${err.message}`);- return null;- });- // Canceled mid-pass — don't bill, don't mark the step reviewed; let the loop- // unwind via its canceled branch.- if (result?.canceled || record.cancelRequested) return { canceled: true };- if (result) {- if (hasLlmCheck) await recordDomainUsage('cos', { actions: 1 });- // #1573 — a check whose run() threw is recorded in perCheck.error but the- // pass otherwise looks clean. Surface the errored count + failing checkIds on- // the round frame and accumulate them onto the run so the terminal summary- // can flag a partial failure (no silent "complete").- const { errored, erroredCheckIds } = summarizeCheckErrors(result.perCheck);- erroredCheckIds.forEach((id) => record.runState.editorialCheckErroredIds.add(id));- // #1613 — count the high-severity findings this pass surfaced. The round frame- // previously hardcoded `blocking: 0`, which made a 50-high-finding pass look- // "complete" — the misleading per-step signal the issue calls out. Report the- // real high count so the step's `blocking` matches what it found, whether or- // not the optional pause gate is armed.- const highFindings = result.findings.filter((f) => f.severity === 'high');- broadcast(sId, { type: 'verify:round', scope: 'editorialChecks', round: 1, findings: result.findings.length, blocking: highFindings.length, errored, erroredCheckIds });- if (errored) {- console.error(`❌ autopilot: ${errored} editorial check(s) errored — series=${sId.slice(0, 12)} ${erroredCheckIds.join(', ')}`);- }- // #1613 — optional gate: when armed (threshold > 0) and the pass surfaced at- // least that many high findings, PAUSE for human review instead of silently- // proceeding to the health gate. Off by default (threshold 0), so existing- // runs are unchanged. Do NOT mark the step reviewed — a resume re-runs the- // checks and reconciles (like the health gate), so once the human reduces the- // high findings below the threshold (or lowers it) the run continues.- const threshold = record.options.checkFindingsPauseThreshold || 0;- if (threshold > 0 && highFindings.length >= threshold) {- // Editorial findings already carry severity/location/problem (manuscriptReview- // sanitizes them), so the residual uses the same shape as the other pauses;- // keep checkId so the UI can link a residual back to the check that raised it.- const residual = highFindings.map((f) => ({- severity: f.severity, // already filtered to 'high' — carry it rather than re-asserting- location: f.location || (f.checkId ? `check ${f.checkId}` : 'manuscript'),- problem: f.problem || 'high-severity editorial finding',- checkId: f.checkId,- }));- console.log(`🚦 editorial checks gate — series=${sId.slice(0, 12)} ${highFindings.length} high finding(s) ≥ threshold ${threshold}, pausing for review`);- return {- pause: true,- pauseKind: 'checkFindings',- reason: `Editorial checks surfaced ${highFindings.length} high-severity finding(s) (≥ threshold ${threshold}) — paused for review. Address them in the manuscript editor, or raise the editorial-check pause threshold above ${highFindings.length} (set it to 0 to disable) in Options and resume.`,- residual,- };- }- }- record.runState.editorialChecksReviewed = true;- return {};-}--// STEP 5.3 — editorial health convergence gate (#1316). A cheap, no-LLM gate:-// read the persisted review, compute the aggregate health under the configured-// readiness gate, and either mark the run clean (proceed to visuals) or PAUSE-// with the open blockers for human triage. This is the consolidated "ready"-// signal — distinct from the completeness loop's own per-round high-only gate —-// so a blocker the registry checks (5.2) surfaced after completeness converged-// still stops the run. No auto-fix here: the completeness loop already attempted-// fixes; remaining blockers need a human (or a re-run after edits).-async function runEditorialHealthGate(sId, record) {- if (record.cancelRequested) return { canceled: true };- // The effective gate (per-run override → persisted setting → null) was resolved- // and stamped onto record.options at start (#1580), mirroring the round bounds —- // so the loop and the dry-run plan can't disagree on which gate applied. null- // falls through to DEFAULT_READINESS_GATE inside computeHealth/openBlockers.- const gate = record.options.readinessGate || undefined;- // Do NOT swallow a getReview error into an empty review — that would fail OPEN- // (the gate would pass on a corrupt/unreadable store and let the run proceed to- // visuals without verifying health). Let it bubble to the coordinator's- // top-level catch, which records a clean `error` terminal state.- const review = await getReview(sId);- const comments = review.comments || [];- // Per-series severity-weight override (#1616) resolved + stamped at start, so- // the health score the gate reads matches the live + persisted scores.- const health = computeHealth(comments, gate, { weights: record.options.severityWeights });- broadcast(sId, {- type: 'verify:round', scope: 'editorialHealth', round: 1,- findings: health.open, blocking: health.ready ? 0 : health.open, score: health.score,- });- if (health.ready) {- record.runState.editorialHealthReady = true;- return {};- }- // Not clean — surface the open blockers (via the shared helper, so the residual- // can't disagree with computeHealth's `ready` verdict) for the human triage.- // No pauseKind (#1571): this is a single-pass gate, not a bounded verify→resolve- // loop, so it has no maxRounds/divergence distinction — leave it null. If this- // ever gains a retry loop, thread pauseKind through trackConvergence then.- const blockers = openBlockers(comments, gate);- // Surface the per-check / per-issue breakdown that drove the pause (#1579) —- // a single emoji-prefixed line so "why did health reject my 50-issue series?"- // is answerable from the logs, and the same breakdown on the marker so the UI- // / resume banner can render it without re-hitting the health API.- const healthBreakdown = summarizeEditorialBlockers(health);- console.log(`🩺 editorial health gate not clean — series=${sId.slice(0, 12)} score=${health.score}, ${health.open} open: ${formatBlockerSummary(healthBreakdown)}`);- return { pause: true, reason: `editorial health not clean (score ${health.score}, ${health.open} open finding(s))`, residual: blockers, healthBreakdown };-}--// Turn a render-enqueue result into the { slotKey, slot } pair the render-// routes persist (proof → proofImage, final → finalImage).-const slotFromRenderResult = (result) => {- const slotKey = slotKeyForVariant(result.variant);- return { slotKey, slot: buildRenderSlot({ slotKey, jobId: result.jobId, prompt: result.prompt, fromProof: result.fromProof }) };-};--// Persist an in-flight render slot the way the render routes do: enqueue the-// proof render, then splice the returned jobId onto the freshest persisted-// cover/backCover slot via updateStageWithLatest.-async function enqueueCoverDraft(issueId, slotField, enqueueFn) {- const { slotKey, slot } = slotFromRenderResult(await enqueueFn(issueId, { target: 'proof' }));- await updateStageWithLatest(issueId, 'comicPages', (current) => {- const currentSlot = current?.[slotField] || {};- return { [slotField]: { ...currentSlot, [slotKey]: slot } };- });-}--async function enqueuePageDraft(issueId, pageIndex) {- const { slotKey, slot } = slotFromRenderResult(await enqueueVisualComicPage(issueId, { pageIndex, target: 'proof' }));- await updateStageWithLatest(issueId, 'comicPages', (current) => {- const pages = Array.isArray(current?.pages) ? current.pages : [];- if (!pages[pageIndex]) return {};- const next = [...pages];- next[pageIndex] = { ...pages[pageIndex], [slotKey]: slot };- return { status: 'edited', pages: next };- });-}--async function runVisualDraft(sId, issueId, record) {- let issue = await getIssue(issueId);- let cp = issue.stages?.comicPages;-- // Respect an explicit lock — the user froze this stage, so don't seed pages- // or render. Skip (intentional, not a gap) and mark drafted so we don't loop.- if (cp?.locked === true) {- broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, reason: 'comicPages stage is locked — skipping draft render' });- record.runState.visualDrafted.add(issueId);- return {};- }-- // 1. Seed pages + cover concepts from the comic script if not already done- // (mirrors the extract-pages route; pure parse, no LLM).- if (!(Array.isArray(cp?.pages) && cp.pages.length > 0)) {- const source = (issue.stages?.comicScript?.output || '').trim();- if (source) {- const { pages, coverConcept, backCoverConcept } = parseComicScript(source);- await updateStageWithLatest(issueId, 'comicPages', (current) => {- const coverScript = current?.cover?.script || '';- const backScript = current?.backCover?.script || '';- return {- status: pages.length ? 'ready' : 'empty',- pages,- cover: coverConcept && !coverScript ? { script: coverConcept, imageJobId: null, prompt: null } : (current?.cover ?? null),- backCover: backCoverConcept && !backScript ? { script: backCoverConcept, imageJobId: null, prompt: null } : (current?.backCover ?? null),- errorMessage: '',- };- });- issue = await getIssue(issueId);- cp = issue.stages?.comicPages;- }- }-- const pageCount = Array.isArray(cp?.pages) ? cp.pages.length : 0;- if (pageCount === 0) {- // Nothing to draw — the comic script never parsed into pages. This is a real- // production blocker, so pause for review rather than marking the issue done.- await fileGap(record, sId, {- gapKind: 'visual-no-pages',- issueId,- summary: 'Cannot draft comic art — the comic script did not parse into any pages. Fix the comicScript stage (PAGE/PANEL structure) first.',- context: `issueId=${issueId}`,- });- return { pause: true, gapFiled: true, reason: `issue ${issue.number ?? issueId} has no comic pages to render — the script did not parse`, residual: [{ severity: 'high', location: `issue ${issue.number ?? '?'} / comicPages`, problem: 'comic script did not parse into pages' }] };- }-- // Budget-gate + bill each render individually — a comic is many GPU jobs.- // A failed enqueue (e.g. a page with no panels) is surfaced and skipped.- const enqueueOne = async (target, fn) => {- const budget = await getDomainBudgetStatus('cos');- if (!budget.withinBudget) return { pause: true, reason: `daily cos ${budget.exceeded} budget reached` };- try {- await fn();- await recordDomainUsage('cos', { actions: 1 });- broadcast(sId, { type: 'render:queued', issueId, target });- } catch (err) {- const reason = (err?.message || String(err)).slice(0, 200);- broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, target, reason });- // Dedups to one task per issue (idTag has no target), so a broken page- // doesn't file a task per page.- await fileGap(record, sId, {- gapKind: 'render-failed',- issueId,- summary: `A draft render failed for this issue (first failure: ${target} — ${reason}). The comic page/panel structure may be incomplete.`,- context: `issueId=${issueId} target=${target}`,- });- }- return {};- };-- // 2. Front cover.- if (!slotEnqueued(cp?.cover)) {- const r = await enqueueOne('cover', () => enqueueCoverDraft(issueId, 'cover', enqueueComicCover));- if (r.pause) return r;- }- // 3. Back cover — always queue it (like the front cover); the back-cover- // renderer has a fallback prompt when no concept script is set, so a- // "complete" draft shouldn't silently omit it.- issue = await getIssue(issueId);- cp = issue.stages?.comicPages;- if (!slotEnqueued(cp?.backCover)) {- const r = await enqueueOne('backCover', () => enqueueCoverDraft(issueId, 'backCover', enqueueComicBackCover));- if (r.pause) return r;- }- // 4. Every interior page (re-read per page so each splice merges fresh state).- for (let i = 0; i < pageCount; i += 1) {- if (record.cancelRequested) return { canceled: true };- const fresh = await getIssue(issueId);- const page = fresh.stages?.comicPages?.pages?.[i];- if (!page || !Array.isArray(page.panels) || page.panels.length === 0) continue;- if (pageEnqueued(page)) continue;- const r = await enqueueOne(`page ${i + 1}`, () => enqueuePageDraft(issueId, i));- if (r.pause) return r;- }- // Only consider the issue drafted once every drawable slot is actually- // enqueued. If a render errored (e.g. an un-renderable page), visualReady is- // still false — mark it attempted so the resolver doesn't re-loop, but pause- // for review instead of letting the run report a complete draft.- const after = await getIssue(issueId);- if (!visualReady(after)) {- record.runState.visualDrafted.add(issueId);- await fileGap(record, sId, {- gapKind: 'visual-incomplete',- issueId,- summary: `Issue ${after.number ?? issueId} could not be fully drafted — some cover/page renders did not enqueue (likely an un-renderable page or missing panels). Review the comic page/panel structure.`,- context: `issueId=${issueId}`,- });- return {- pause: true,- gapFiled: true,- reason: `issue ${after.number ?? issueId} could not be fully drafted — some cover/page renders did not enqueue`,- residual: [{ severity: 'high', location: `issue ${after.number ?? '?'} / comicPages`, problem: 'not every drawable cover/page render was enqueued (likely an un-renderable page or missing panels)' }],- };- }- record.runState.visualDrafted.add(issueId);- return {};-}--// Canon descriptive-integrity gate — deterministic (no LLM), so not billable.-// Pauses for human review when a canon noun that appears in the visual source-// has no description (it can't be drawn). Marks canonVerified when clean so the-// run proceeds to visual drafting.-async function runCanonVerify(sId, record) {- const report = await checkSeriesCanonReadiness(sId);- broadcast(sId, {- type: 'verify:round', scope: 'canon', round: 1,- findings: report.undescribed.length, blocking: report.undescribed.length,- });- if (report.ready) {- record.runState.canonVerified = true;- return {};- }- const residual = report.undescribed.map((n) => ({- severity: 'high',- location: `${n.kind} "${n.name}"`,- problem: 'Appears where it would be drawn but has no description — can\'t be rendered.',- }));- await fileGap(record, sId, {- gapKind: 'canon-undescribed',- summary: `${report.undescribed.length} canon noun(s) appear in panels/scenes with no description: ${report.undescribed.map((n) => n.name).join(', ').slice(0, 400)}. Describe them on the Nouns stage before generating pages.`,- context: JSON.stringify(report.undescribed).slice(0, 1000),- });- return {- pause: true,- reason: `${report.undescribed.length} canon noun(s) referenced in panels/scenes are undescribed — describe them before visual production`,- residual,- gapFiled: true,- };-}--// Teaser deliverable (CDO Phase 3, #2185, opt-in). Mint + start a Creative-// Director video project seeded from this issue — the autopilot→CD direction of-// the bridge. Attempted-once per issue (marked up front so a failure can't-// re-loop the resolver). Bills one cos action like every other autopilot step-// (the CD project's own downstream render spend is gated by the creative/cos-// budget on its side). A teaser is an OPTIONAL, terminal-phase deliverable, so a-// failure is ADVISORY: it broadcasts a skip + files a gap, but does NOT pause the-// whole run (the story is already done — a failed trailer shouldn't strand it).-// bridgeFromIssue is imported dynamically to keep the pipeline↔creative-director-// module graph acyclic (it transitively pulls the CD plan loop + tool registry).-async function runProduceTeaser(sId, issueId, record) {- record.runState.teaserProduced.add(issueId);- const issue = await getIssue(issueId).catch(() => null);- try {- const { produceVideoFromIssue } = await import('../creativeDirector/bridgeFromIssue.js');- // The treatment-from-prose LLM call runs through stageRunner's soft channel,- // so thread the run's provider/model as providerDefault/modelDefault.- const { project } = await produceVideoFromIssue(issueId, providerOverrideOpts(record));- await recordDomainUsage('cos', { actions: 1 });- broadcast(sId, { type: 'teaser:produced', issueId, projectId: project?.id });- console.log(`🎬 autopilot teaser — series=${sId.slice(0, 12)} issue=${issue?.number ?? issueId} → CD project ${project?.id?.slice(0, 8) ?? '?'}`);- return {};- } catch (err) {- const message = (err?.message || String(err)).slice(0, 300);- broadcast(sId, { type: 'step:skip', kind: 'produceTeaser', issueId, reason: `teaser production failed: ${message}` });- await fileGap(record, sId, {- gapKind: 'teaser-failed',- issueId,- summary: `The optional teaser video for issue ${issue?.number ?? issueId} could not be produced: ${message}. The story is complete — this deliverable can be retried from the Creative Director.`,- context: `issueId=${issueId}`,- });- return {};- }-}--// Mean of the judged issues' composite qualityScore (null when nothing judged).-function meanQualityScore(seriesJudge) {- const vals = (seriesJudge?.scores || [])- .filter((s) => s.judged && Number.isFinite(Number(s.qualityScore)))- .map((s) => Number(s.qualityScore));- if (vals.length === 0) return null;- return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 100) / 100;-}--// Judge every drafted (eligible) issue that needs it — an unjudged or stale-// snapshot. Staleness is read from the persisted snapshots (getSeriesJudge, no-// LLM), so a fresh issue is skipped WITHOUT even a cache-reuse call and, crucially,-// the budget is gated BEFORE a fresh judge spends — never after. Each real judge-// bills one cos action. Returns a pause result when the budget is exhausted with-// judging still to do, a cancel result, or null on completion.-async function judgeAllEligible(sId, record, issues) {- const eligible = eligibleIssues(issues);- const { providerOverride, modelOverride } = record.options;- const pre = await getSeriesJudge(sId, { issues });- const scoreById = new Map((pre.scores || []).map((s) => [s.issueId, s]));- for (const issue of eligible) {- if (record.cancelRequested) return { canceled: true };- const score = scoreById.get(issue.id);- const needsJudge = !score || !score.judged || score.stale;- if (!needsJudge) continue; // already judged against the current content — free.- // A fresh judge WILL spend an LLM call — gate the budget first, then bill.- const gate = await budgetPause();- if (gate) return gate;- const snap = await judgeIssue(issue.id, { providerId: providerOverride, model: modelOverride }).catch((err) => {- console.log(`⚠️ revision: judge failed for issue ${issue.id.slice(0, 12)}: ${err.message}`);- return null;- });- if (snap && !snap.cached && snap.status === 'complete') {- await recordDomainUsage('cos', { actions: 1 });- }- }- return null;-}--// Run the adversarial-cuts editorial check for the series, seed the findings into-// the manuscript-review comment set, and return the freshly-seeded safe-cut-// comments (OVER-EXPLAIN + REDUNDANT). Force-enables the check for this pass so a-// user who disabled it globally still gets the loop's mechanical revision. One-// billed LLM pass; returns { safeComments } or a { pause }/{ canceled } result.-async function runAdversarialCuts(sId, record) {- const before = await budgetPause();- if (before) return before;- const settings = await getSettings().catch(() => null);- // Overlay a force-enable for the cut check so a globally-disabled check still- // runs inside the consented revision loop (never mutates persisted settings).- const merged = {- ...(settings || {}),- pipelineEditorialChecks: {- ...(settings?.pipelineEditorialChecks || {}),- checks: {- ...(settings?.pipelineEditorialChecks?.checks || {}),- 'prose.adversarial-cuts': {- ...(settings?.pipelineEditorialChecks?.checks?.['prose.adversarial-cuts'] || {}),- enabled: true,- },- },- },- };- const signal = { get aborted() { return record.cancelRequested; } };- const result = await runEditorialChecks(sId, {- checkIds: ['prose.adversarial-cuts'],- settings: merged,- signal,- ...providerOverrideOpts(record),- }).catch((err) => {- console.log(`⚠️ revision: adversarial cuts failed for ${sId.slice(0, 12)}: ${err.message}`);- return null;- });- if (record.cancelRequested) return { canceled: true };- if (!result || result.canceled) return { safeComments: [] };- await recordDomainUsage('cos', { actions: 1 });- await seedReviewFromFindings(sId, result.findings || [], { runId: result.runId, mode: 'merge' }).catch((err) => {- console.log(`⚠️ revision: seed cut findings failed for ${sId.slice(0, 12)}: ${err.message}`);- });- const review = await getReview(sId).catch(() => ({ comments: [] }));- return { safeComments: filterSafeCutComments(review.comments || []) };-}--// One iterate-to-quality revision cycle (CWQE Phase 7, #2171). Composes the-// judge (#2167), adversarial cuts (#2168), and — when a fresh ranking exists —-// the comparative Elo (#2169) to revise the WEAKEST drafted issue under a-// keep/revert score gate, then evaluates the stop conditions. Every LLM call is-// budget-gated + billed exactly like the other steps; a budget-exhausted cycle-// returns a pause the coordinator handles. Never routes here in dry-run (dispatch-// only runs in execute mode).-async function runRevisionCycle(sId, record) {- if (record.cancelRequested) return { canceled: true };- const issues0 = await listIssues({ seriesId: sId });- if (eligibleIssues(issues0).length === 0) {- // Nothing drafted to revise — converge so the resolver moves on.- record.runState.revisionConverged = true;- broadcast(sId, { type: 'revision:converged', reason: 'no-content', cycle: record.runState.revisionCyclesRun || 0 });- return {};- }-- // 1. Judge every eligible issue (cache-aware) → baseline mean + weakest.- const judged = await judgeAllEligible(sId, record, issues0);- if (judged?.canceled) return { canceled: true };- if (judged?.pause) return judged;-- const seriesJudge = await getSeriesJudge(sId, { issues: issues0 });- const preMean = meanQualityScore(seriesJudge);-- // 2. Pick the weakest issue — Elo ranking when a FRESH one exists (#2169),- // else the judge's weakest-first (lowest qualityScore).- let weakestId = null;- const rank = await getComparativeRank(sId).catch(() => null);- if (rank?.status === 'complete' && !rank.stale && Array.isArray(rank.weakest) && rank.weakest[0]) {- weakestId = rank.weakest[0].issueId;- }- if (!weakestId) weakestId = seriesJudge.weakest?.[0]?.issueId || null;- if (!weakestId) {- record.runState.revisionConverged = true;- broadcast(sId, { type: 'revision:converged', reason: 'no-weakest', cycle: record.runState.revisionCyclesRun || 0 });- return {};- }-- const preWeakest = seriesJudge.scores.find((s) => s.issueId === weakestId);- const preScore = preWeakest?.qualityScore ?? null;- const stageId = preWeakest?.stageId || 'prose';-- // 3. Adversarial cuts (series-wide seed) + collect this issue's safe cuts.- const cuts = await runAdversarialCuts(sId, record);- if (cuts?.canceled) return { canceled: true };- if (cuts?.pause) return cuts;- const issueSafeCuts = (cuts.safeComments || []).filter((c) => c.issueId === weakestId);-- // Capture the weakest issue's pre-revision stage state for the keep/revert gate- // (existing runHistory snapshotting handles the version event; we hold the exact- // text so a revert can restore it through the serialized write path — never a- // force over a concurrent human edit).- const preIssue = await getIssue(weakestId).catch(() => null);- const preStage = preIssue?.stages?.[stageId] || {};- const preState = { input: preStage.input || '', output: preStage.output || '', lastRunId: preStage.lastRunId || null };- // The full judge snapshot for the brief — a persisted-snapshot read (no LLM- // spend); judgeAllEligible above already judged this issue this cycle.- const weakestJudge = await getIssueJudge(weakestId).catch(() => null);-- // 4. Build the revision brief (pure) and broadcast it as the revision plan.- const brief = buildRevisionBrief({- issue: { number: preIssue?.number, title: preIssue?.title },- judge: weakestJudge && weakestJudge.status === 'complete' ? weakestJudge : (preWeakest || {}),- cutComments: issueSafeCuts,- currentChars: (preState.output || '').length || null,- });- broadcast(sId, { type: 'revision:brief', issueId: weakestId, cycle: (record.runState.revisionCyclesRun || 0) + 1, cuts: issueSafeCuts.length, brief: brief.slice(0, 2000) });-- // 5. Apply — mechanical safe cuts are the revision (autonovel: "the cuts ARE the- // plan"). applyCuts writes through the serialized stage path with a runHistory- // snapshot for undo. No safe cuts ⇒ nothing to apply this cycle.- let applied = 0;- if (issueSafeCuts.length > 0) {- const cutResult = await applyCuts(sId, issueSafeCuts, { safeTypesOnly: true }).catch((err) => {- console.log(`⚠️ revision: applyCuts failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);- return { applied: 0, sections: [] };- });- applied = cutResult.applied || 0;- }-- // 6. Keep/revert gate — re-judge the revised issue; keep only if the composite- // qualityScore did not regress, else restore the pre-revision text.- let decision = 'keep';- let postScore = preScore;- if (applied > 0) {- const postIssue = await getIssue(weakestId).catch(() => null);- const appliedOutput = postIssue?.stages?.[stageId]?.output || '';- const before = await budgetPause();- if (before) return before;- const reJudge = await judgeIssue(weakestId, { stageId, force: true, providerId: record.options.providerOverride, model: record.options.modelOverride }).catch((err) => {- console.log(`⚠️ revision: re-judge failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);- return null;- });- if (reJudge && reJudge.status === 'complete') await recordDomainUsage('cos', { actions: 1 });- postScore = reJudge?.status === 'complete' ? reJudge.qualityScore : preScore;- decision = decideKeepRevert(preScore, postScore);- if (decision === 'revert') {- // Restore through the serialized path, guarded so a concurrent human edit is- // never clobbered: revert ONLY when the stage still holds the cut output we- // produced. A `revert-` runId marks this as a fresh version event.- await updateStageWithLatest(weakestId, stageId, (cur) => {- if ((cur?.output || '') !== appliedOutput) return {};- return { status: 'edited', input: preState.input, output: preState.output, lastRunId: `revert-${randomUUID()}`, errorMessage: '' };- }).catch((err) => {- console.log(`⚠️ revision: revert failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);- });- // Re-judge the restored text so the persisted snapshot matches what's on- // disk (else it lingers pinned to the rejected cut version). Budget-gated +- // billed like every other judge; skipped (snapshot stays stale — the next- // cycle re-judges it) when the budget is spent.- const beforeRevertJudge = await budgetPause();- if (!beforeRevertJudge) {- const rj = await judgeIssue(weakestId, { stageId, force: true, providerId: record.options.providerOverride, model: record.options.modelOverride }).catch(() => null);- if (rj && rj.status === 'complete') await recordDomainUsage('cos', { actions: 1 });- }- }- }-- // 7. Record the cycle: post-cycle mean drives the plateau detector; the ledger- // line is the experiment log (single emoji line per the CLAUDE.md convention).- record.runState.revisionCyclesRun = (record.runState.revisionCyclesRun || 0) + 1;- const postSeriesJudge = await getSeriesJudge(sId, { issues: await listIssues({ seriesId: sId }) });- const postMean = meanQualityScore(postSeriesJudge);- if (Number.isFinite(postMean)) record.runState.revisionScoreHistory.push(postMean);- console.log(`🔁 revision cycle ${record.runState.revisionCyclesRun} — series=${sId.slice(0, 12)} issue=${preIssue?.number ?? weakestId} pre=${preScore ?? '?'} post=${postScore ?? '?'} → ${decision} (applied ${applied} cut(s), mean ${preMean ?? '?'}→${postMean ?? '?'})`);-- // 8. Stop conditions — plateau / hedged-convergence / maxCycles. The residual- // finding texts come from the weakest issue's judge (verdict + revisions):- // the reviewer will ALWAYS find something, so the stop is about qualification,- // not zero defects.- const findingTexts = [- postSeriesJudge.scores.find((s) => s.issueId === weakestId)?.oneLineVerdict || '',- ...((weakestJudge?.topRevisions) || []),- ].filter(Boolean);- const stop = evaluateRevisionStop({- cyclesRun: record.runState.revisionCyclesRun,- minCycles: record.options.revisionMinCycles,- maxCycles: record.options.revisionMaxCycles,- scoreHistory: record.runState.revisionScoreHistory,- plateauDelta: record.options.revisionPlateauDelta,- findingTexts,- });- broadcast(sId, {- type: 'revision:cycle', cycle: record.runState.revisionCyclesRun, issueId: weakestId,- preScore, postScore, decision, applied, preMean, postMean,- converged: stop.stop, stopReason: stop.reason,- });- if (stop.stop) {- record.runState.revisionConverged = true;- broadcast(sId, { type: 'revision:converged', reason: stop.reason, detail: stop.detail, cycle: record.runState.revisionCyclesRun });- console.log(`✅ revision converged (${stop.reason}) — series=${sId.slice(0, 12)}: ${stop.detail}`);- }- return {};-}--async function dispatchStep(sId, step, record) {- switch (step.kind) {- case 'generateArc': {- // Mark attempted up front so the resolver won't re-route here if arc- // generation yields no seasons (avoids an infinite generateArc loop).- record.runState.arcAttempted = true;- const r = await generateArcOverview(sId, providerOverrideOpts(record));- const committed = await commitSeasonsWithRemap(await getSeries(sId), { arc: r.arc, seasons: r.seasons });- await recordDomainUsage('cos', { actions: 1 });- const seasonCount = committed?.series?.seasons?.length ?? (await getSeries(sId)).seasons?.length ?? 0;- if (seasonCount === 0) {- // No specific gap filed here — let the conductor file generateArc-stalled.- return {- pause: true,- reason: 'arc generation produced no volumes — cannot create issues; review the series bible and regenerate the arc',- residual: [{ severity: 'high', location: 'arc', problem: 'arc overview returned zero seasons/volumes' }],- };- }- return {};- }- case 'generateEpisodes': {- // Mark attempted up front so an empty/invalid episode list can't re-loop- // the resolver back into generateEpisodes for the same still-empty volume.- record.runState.episodesAttempted.add(step.seasonId);- const r = await generateSeasonEpisodes(sId, step.seasonId, providerOverrideOpts(record));- const cur = await getSeries(sId);- const created = await commitEpisodesToIssues(sId, step.seasonId, r.episodes, { preloadedSeries: cur });- await recordDomainUsage('cos', { actions: 1 });- if (!Array.isArray(created) || created.length === 0) {- return {- pause: true,- reason: `episode generation produced no issues for volume ${step.seasonId} — review the volume outline and regenerate`,- residual: [{ severity: 'high', location: `volume ${step.seasonId}`, problem: 'episode breakdown returned zero episodes/issues' }],- };- }- return {};- }- case 'verifyArc':- return runArcVerify(sId, record);- case 'beatSheet':- return runBeats(sId, step.seasonId, record);- case 'beatContinuity':- return runBeatContinuity(sId, record);- case 'foundationGate':- return runFoundationGate(sId, record);- case 'textStages':- return runText(sId, step.issueId, record);- case 'scriptVerify':- return runScriptVerify(sId, step.issueId, record);- case 'editorialReview':- return runEditorial(sId, record);- case 'reverseOutline':- return runReverseOutlineRefresh(sId, record);- case 'editorialChecks':- return runEditorialChecksPass(sId, record);- case 'editorialHealthGate':- return runEditorialHealthGate(sId, record);- case 'revisionCycle':- return runRevisionCycle(sId, record);- case 'canonVerify':- return runCanonVerify(sId, record);- case 'visualDraft':- return runVisualDraft(sId, step.issueId, record);- case 'produceTeaser':- return runProduceTeaser(sId, step.issueId, record);- default:- return {};- }-}--// ----------------------------------------------------------------------------// Dry-run planning — enumerate what execute WOULD do, no side effects.-// -----------------------------------------------------------------------------// Mirrors resolveNextStep's step ordering, but enumerates the FULL remaining-// plan (counts of every unmet step) rather than returning only the next one —-// so it can't reuse the single-step resolver. Kept deliberately in sync by-// hand; they share the same predicates (textReady, isComicTarget, isStageReady).-// `costContext.editorialLlmCheckCount` (optional) is the resolved number of-// enabled LLM-kind editorial checks for this run's subset — supplied by the-// caller (which has loaded settings) so this stays a pure, synchronous function.-// When provided it drives the editorialChecks step's estLlmCalls (issues × LLM-// checks) and whether that pass bills a cos action at all; absent, the step-// estimates a single LLM check.-function buildDryRunPlan(series, issues, options, costContext = {}) {- const plan = [];- const ordered = orderedIssues(issues);- const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];- // Mirror the resolver: generateArc runs when arc text is missing OR there are- // no volumes at all (an arc-only series), so a dry-run plan must show it too.- const noArc = !series?.arc?.logline && !series?.arc?.summary;- if (noArc || seasons.length === 0) plan.push({ kind: 'generateArc', count: 1, estActions: 1 });- const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));- if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length, estActions: emptySeasons.length });- const arcRounds = Number.isInteger(options?.maxArcVerifyRounds) ? options.maxArcVerifyRounds : MAX_ARC_VERIFY_ROUNDS;- plan.push({ kind: 'verifyArc', count: 1, note: roundsNote(arcRounds), estActions: convergenceLoopActions(arcRounds) });- // foundationGate (#2176) runs once between arc verify and beats, unless- // disabled or 0-round. Bills judge + fix per round like the arc loop.- const foundationRounds = Number.isInteger(options?.maxFoundationRounds) ? options.maxFoundationRounds : MAX_FOUNDATION_ROUNDS;- if (options?.foundationGate !== false && foundationRounds !== 0) {- plan.push({ kind: 'foundationGate', count: 1, note: roundsNote(foundationRounds), estActions: convergenceLoopActions(foundationRounds) });- }- const beatsNeeded = seasons.filter((s) =>- ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;- if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded, estActions: beatsNeeded });- // beatContinuity (#1510) runs once when the run will have a beat corpus to- // check: beats already exist, OR beatSheet will generate them this run. Mirror- // the resolver's `ordered.some(issueHasBeats)` gate (post-generation), so a- // synopsis-only run that produces no beats doesn't advertise a pass it skips.- if (ordered.some(issueHasBeats) || beatsNeeded) {- const bcRounds = Number.isInteger(options?.maxBeatContinuityRounds)- ? options.maxBeatContinuityRounds- : MAX_BEAT_CONTINUITY_ROUNDS;- plan.push({ kind: 'beatContinuity', count: 1, note: roundsNote(bcRounds), estActions: convergenceLoopActions(bcRounds) });- }- const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;- if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded, estActions: textNeeded });- if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: ordered.length, estActions: ordered.length });- const edRounds = Number.isInteger(options?.maxEditorialRounds) ? options.maxEditorialRounds : MAX_EDITORIAL_ROUNDS;- // Editorial review is a verify→auto-fix convergence loop like the arc gate, so- // the per-round estimate mirrors it (analyze + one resolve batch / round). The- // per-comment auto-fixes within a round bill additionally and scale with the- // number of blocking findings, which isn't knowable at plan time.- plan.push({ kind: 'editorialReview', count: 1, note: roundsNote(edRounds), estActions: convergenceLoopActions(edRounds) });- // maxEditorialRounds === 0 skips the whole editorial gate in execute mode- // (runEditorial marks editorialReviewed + editorialChecksReviewed +- // editorialHealthReady), so the plan must not advertise the registry checks or- // the health gate that won't run.- if (edRounds !== 0) {- plan.push({ kind: 'reverseOutline', count: 1, note: 'refresh scene segmentation for editorial checks (#1349)', estActions: 1 });- // #1575 — when a per-run subset is set, the plan must say so rather than imply- // the full enabled set runs.- const editorialSubset = editorialSubsetIds(options);- // The checks pass bills a single cos action (only when an LLM check runs) but- // fans out to many LLM calls. The real call count depends on how each check- // chunks the stitched manuscript by provider context window, so it isn't- // knowable at plan time — `issues × enabled LLM checks` is a rough proxy that- // scales with both series size and check count, surfaced so a large series's- // check cost is visible. When the caller didn't resolve the enabled-check- // count, assume one LLM check runs.- const llmCheckCount = Number.isInteger(costContext?.editorialLlmCheckCount)- ? costContext.editorialLlmCheckCount- : 1;- const estLlmCalls = ordered.length * llmCheckCount;- const checksNote = editorialSubset- ? `per-run subset of ${editorialSubset.length} editorial check(s) (#1575)`- : 'enabled editorial checks (#1284)';- // Surface the optional pause threshold (#1613) when armed, mirroring how the- // readiness gate is exposed below — so a per-run override is visible in the plan.- const pauseThreshold = resolveAutopilotCheckPauseThreshold(options);- const pauseNote = pauseThreshold > 0 ? ` — pauses at ≥ ${pauseThreshold} high finding(s) (#1613)` : '';- plan.push({- kind: 'editorialChecks',- count: 1,- note: (llmCheckCount > 0 ? `${checksNote} — ~${estLlmCalls} LLM call(s)` : checksNote) + pauseNote,- estActions: llmCheckCount > 0 ? 1 : 0,- estLlmCalls,- });- // Surface the effective readiness gate (#1580) so a per-run override is- // visible in the dry-run plan, mirroring how roundsNote exposes the bounds.- const gate = resolveReadinessGate(options?.readinessGate);- plan.push({ kind: 'editorialHealthGate', count: 1, note: `editorial health readiness gate (#1316) — gate: ${gate}`, estActions: 0 });- }- // Iterate-to-quality revision loop (#2171, opt-in, default off). Each cycle- // judges every drafted issue (cache-aware — only stale/unjudged content bills),- // runs one adversarial-cut pass, and re-judges the revised issue: roughly- // (issues + 2) actions per cycle, capped at maxCycles. High-end estimate — a- // cycle stops early on plateau / hedged-convergence and cached judges are free.- if (options?.revisionEnabled) {- const rev = resolveAutopilotRevision(options);- plan.push({- kind: 'revisionCycle',- count: rev.revisionMaxCycles,- note: `iterate-to-quality (up to ${rev.revisionMaxCycles} cycle(s), min ${rev.revisionMinCycles}, plateau Δ ${rev.revisionPlateauDelta})`,- estActions: rev.revisionMaxCycles * (ordered.length + 2),- });- }- if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {- // canonVerify runs an LLM pass but bills no cos action (token-only) — 0 budget.- plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns (no budget cost)', estActions: 0 });- const visualNeeded = ordered.filter((i) => !visualReady(i)).length;- // Each draft render bills one cos action: cover + back per issue, plus one per- // interior page. The interior-page count isn't known until the script parses,- // so the estimate counts the two covers and notes the per-page additions.- if (visualNeeded) plan.push({ kind: 'visualDraft', count: visualNeeded, note: 'cover + back + all pages (draft) — +1 action per interior page', estActions: visualNeeded * 2 });- // Teaser deliverable (#2185, opt-in, default off): one CD video project per- // issue. Each mint+start bills one cos action for the treatment LLM call; the- // CD project's own render spend is gated on the creative/cos budget its side.- if (wantsTeaser(options)) plan.push({ kind: 'produceTeaser', count: ordered.length, note: 'mint + start a Creative Director teaser video per issue (opt-in)', estActions: ordered.length });- }- return plan;-}--// ----------------------------------------------------------------------------// Public entrypoint.-// -----------------------------------------------------------------------------/**- * Start (or no-op resume of) the autopilot for a series. Returns immediately;- * progress lands via SSE. When the cos domain is `off`, returns- * `{ rejected:true, mode:'off' }` WITHOUT starting (route maps to 409).- */-export async function startSeriesAutopilot(sId, options = {}) {- const existing = runs.get(sId);- if (existing && !existing.finished) {- return { runId: existing.runId, alreadyRunning: true, mode: existing.mode };- }-- const state = await loadState().catch(() => ({ config: {} }));- const mode = getDomainMode(state.config, 'cos');- if (mode === 'off') {- return { rejected: true, mode: 'off' };- }-- // Resolve the convergence-round bounds ONCE at start (per-run option →- // persisted setting → default) and stamp them onto the run's options so the- // synchronous loops, the dry-run plan, and a later resume all read the same- // effective values. A resume reuses this same path, so a raised persisted- // setting takes effect on the next Resume without re-specifying it.- const settings = await getSettings().catch(() => null);- // Per-series severity config (#1616): resolve the (possibly overridden) health- // severity weights + the per-gate blocking-severity Sets ONCE at start and- // stamp them onto run options, mirroring the round bounds / readiness gate —- // so every gate read site + the health gate use the same resolved values, and- // a resume re-reads them fresh. Loading the series here is cheap; a missing- // series (deleted mid-run) falls through to the frozen defaults.- const seriesRecord = await getSeries(sId).catch(() => null);- const runOptions = {- ...options,- ...resolveAutopilotRounds(options, settings),- foundationGate: resolveAutopilotFoundationGate(options, settings),- foundationThreshold: resolveAutopilotFoundationThreshold(options, settings),- readinessGate: resolveAutopilotReadinessGate(options, settings),- checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),- notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),- produceTeaser: resolveAutopilotProduceTeaser(options, settings),- ...resolveAutopilotRevision(options, settings),- severityWeights: mergeSeverityWeights(seriesRecord?.severityWeights),- blockingSets: {- arc: resolveBlockingSet(seriesRecord?.blockingSeverities, 'arc'),- beatContinuity: resolveBlockingSet(seriesRecord?.blockingSeverities, 'beatContinuity'),- editorial: resolveBlockingSet(seriesRecord?.blockingSeverities, 'editorial'),- },- };-- if (existing) {- // A finished run still in its replay window — evict it so this fresh run- // fully replaces it (mirrors editorialAnalysisRunner).- if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);- for (const c of existing.clients) c.end();- }-- const runId = randomUUID();- const record = {- runId,- clients: [],- lastPayload: null,- cancelRequested: false,- finished: false,- cleanupTimer: null,- startedAt: new Date().toISOString(),- mode,- options: runOptions,- runState: {- arcAttempted: false,- arcVerified: false,- // #2176 — foundation-quality gate satisfied this run (threshold cleared,- // or the gate disabled/0-round). Boolean like arcVerified so the resolver- // routes here at most once per run.- foundationGated: false,- beatContinuityChecked: false,- editorialReviewed: false,- reverseOutlineRefreshed: false,- editorialChecksReviewed: false,- editorialHealthReady: false,- canonVerified: false,- episodesAttempted: new Set(),- beatsAttempted: new Set(),- textAttempted: new Set(),- scriptChecked: new Set(),- visualDrafted: new Set(),- // #2185 — issues whose optional teaser deliverable has been produced (or- // attempted) this run, so the resolver can't re-loop into produceTeaser.- teaserProduced: new Set(),- // #1572 — issues whose ADVISORY craft gate filed a blocking gap task, and- // the total blocking-finding count. Carried into the terminal `complete`- // frame + persisted marker so a "clean complete" doesn't hide downstream- // render blockers the user still has to resolve.- scriptCraftGapIssues: new Set(),- scriptCraftBlocking: 0,- // #1573 — checkIds of editorial checks that threw during this run's checks- // pass. Surfaced on the terminal `complete` frame + persisted marker so a- // check that errors every run is visible instead of a silent "clean".- editorialCheckErroredIds: new Set(),- // #2171 — iterate-to-quality revision loop state (opt-in). `revisionCyclesRun`- // is the completed-cycle count (the resolver's cursor); `revisionScoreHistory`- // is the per-cycle mean series qualityScore the plateau detector reads;- // `revisionConverged` latches true once a stop condition fires so the resolver- // routes past the loop to canon/visuals.- revisionCyclesRun: 0,- revisionScoreHistory: [],- revisionConverged: false,- },- activeChild: null,- };- runs.set(sId, record);-- // Fire-and-forget coordinator. The try/catch is the permitted boundary use —- // an unhandled LLM rejection here would crash the process on Node ≥15.- (async () => {- try {- // DRY-RUN: enumerate the plan, no side effects.- if (mode === 'dry-run') {- const series = await getSeries(sId);- const issues = await listIssues({ seriesId: sId });- // Resolve the enabled LLM-check count (#1576) so the plan's editorialChecks- // step can estimate its issues × checks LLM fan-out. Mirrors the actual- // pass: same subset (editorialSubsetIds) and same settings the checks read.- const settings = await getSettings().catch(() => null);- const checkPlan = await buildEditorialCheckPlan(sId, { checkIds: editorialSubsetIds(runOptions), settings }).catch(() => null);- const editorialLlmCheckCount = checkPlan ? checkPlan.checks.filter((c) => c.kind === 'llm').length : undefined;- const plan = buildDryRunPlan(series, issues, runOptions, { editorialLlmCheckCount });- const planTotals = summarizePlanCost(plan);- broadcast(sId, { type: 'start', runId, mode, target: series.targetFormat, plan, planTotals });- // Carry the plan on the terminal frame too: a dry-run emits start +- // complete synchronously, often before the client attaches, and- // attachSseClient replays only the LAST frame — so the plan would be- // lost if it lived solely on the start frame.- broadcast(sId, { type: 'complete', runId, dryRun: true, steps: plan.length, plan, planTotals, completedAt: new Date().toISOString() });- console.log(`🧭 autopilot dry-run — series=${sId.slice(0, 12)} steps=${plan.length} est≈${planTotals.estActions} action(s) ${planTotals.estLlmCalls} LLM call(s)`);- return;- }-- // EXECUTE.- const series0 = await getSeries(sId);- broadcast(sId, { type: 'start', runId, mode, target: series0.targetFormat });- await persistMarker(sId, { status: 'running', runId, currentStep: null, residualFindings: [], lastError: null });- // A resume is a fresh start: drop any stale pause banner up front so a run- // that completes/errors without re-pausing doesn't leave a dead resume link.- await clearPauseNotice(sId);- if (runOptions.includeVisual && !VISUAL_DRAFT_ENABLED) {- broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });- }-- let ordinal = 0;- while (!record.cancelRequested) {- const series = await getSeries(sId);- const issues = await listIssues({ seriesId: sId });- const step = resolveNextStep(series, issues, record.runState, runOptions);-- if (step.kind === 'done') {- // #1572 — qualify "complete" when the advisory craft gate filed- // blocking script-craft gaps during this run: the run is done, but- // those gaps still block downstream visual rendering, so report them- // on both the persisted marker and the terminal frame.- const craftGapIssues = record.runState.scriptCraftGapIssues.size;- const craftGapFindings = record.runState.scriptCraftBlocking;- // #1573 — qualify "complete" when an editorial check threw this run: the- // run finished, but a check that errored produced no findings, so its- // dimension was never actually evaluated. Persist the count + carry the- // failing checkIds on the frame so the UI flags it instead of "clean".- const editorialCheckErroredIds = [...record.runState.editorialCheckErroredIds];- const editorialCheckErrors = editorialCheckErroredIds.length;- await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors });- broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, completedAt: new Date().toISOString() });- console.log(`✅ autopilot complete — series=${sId.slice(0, 12)} steps=${ordinal}${craftGapIssues ? ` (${craftGapIssues} issue(s) with filed script-craft gaps)` : ''}${editorialCheckErrors ? ` (${editorialCheckErrors} editorial check(s) errored: ${editorialCheckErroredIds.join(', ')})` : ''}`);- return;- }-- // Budget gate (mirrors cosJobScheduler) — pause when today's cos action- // budget is exhausted rather than burning past it. The editorialChecks- // step is exempt from this blanket pre-dispatch gate because it- // self-gates: runEditorialChecksPass only pauses/bills the budget when an- // enabled LLM check will actually run (returning a pause result this loop- // still handles), so a deterministic-only or all-disabled checks step can- // complete a text-ready series even with the budget exhausted. The- // editorialHealthGate (#1316) is likewise exempt — it's a pure read +- // score with no LLM cost, so a budget-exhausted run can still produce its- // readiness verdict (and pause on the findings, not the budget). The- // reverseOutline refresh is exempt for the SAME reason as editorialChecks:- // runReverseOutlineRefresh self-gates (it only calls budgetPause + bills- // when it will actually regenerate), and it no-ops when no enabled check —- // narrowed to this run's #1575 subset — consumes the outline. A blanket- // pre-dispatch pause here would wrongly stall a deterministic-only subset- // (whose refresh is a guaranteed no-op) on an exhausted budget. A gate- // whose resolved rounds is 0 ("skip") is also exempt: runArcVerify /- // runEditorial short-circuit with no LLM spend, so "0 skips the gate" must- // hold even when the budget is exhausted (otherwise the run pauses on- // budget instead of skipping).- const zeroRoundSkip = (step.kind === 'verifyArc' && runOptions.maxArcVerifyRounds === 0)- || (step.kind === 'beatContinuity' && runOptions.maxBeatContinuityRounds === 0)- || (step.kind === 'editorialReview' && runOptions.maxEditorialRounds === 0)- || (step.kind === 'foundationGate' && (runOptions.maxFoundationRounds === 0 || runOptions.foundationGate === false));- const selfGatingStep = step.kind === 'editorialChecks'- || step.kind === 'editorialHealthGate'- || step.kind === 'reverseOutline';- if (!selfGatingStep && !zeroRoundSkip) {- const budget = await getDomainBudgetStatus('cos');- if (!budget.withinBudget) {- const budgetReason = `daily cos ${budget.exceeded} budget reached`;- await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: budgetReason });- broadcast(sId, { type: 'paused', runId, reason: budgetReason, completedAt: new Date().toISOString() });- await notifyPause(record, sId, { reason: budgetReason, pauseKind: 'budget', currentStep: step.kind });- console.log(`⏸️ autopilot paused (budget) — series=${sId.slice(0, 12)} after ${ordinal} steps`);- return;- }- }-- ordinal += 1;- await persistMarker(sId, { status: 'running', runId, currentStep: step.kind });- broadcast(sId, { type: 'step:start', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal, reason: step.reason });-- const result = await dispatchStep(sId, step, record);-- if (result?.canceled || record.cancelRequested) break;- if (result?.pause) {- await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null });- broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, completedAt: new Date().toISOString() });- await notifyPause(record, sId, { reason: result.reason, pauseKind: result.pauseKind || null, currentStep: step.kind });- // Only file the generic stalled task when the step didn't already file- // a more specific gap (canon-undescribed, visual-no-pages, …) — else- // fileGaps would create two CoS tasks for one underlying problem (the- // differing gapKind defeats addTask's first-line dedup).- if (!result.gapFiled) {- await fileGap(record, sId, {- gapKind: `${step.kind}-stalled`,- issueId: step.issueId || null,- summary: `Autopilot paused: ${result.reason}. Needs human review of the residual findings before it can continue.`,- context: JSON.stringify(result.residual || []).slice(0, 1000),- });- }- console.log(`⏸️ autopilot paused (${step.kind}) — series=${sId.slice(0, 12)}: ${result.reason}`);- return;- }- broadcast(sId, { type: 'step:complete', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal });- }-- // Cancelled.- await persistMarker(sId, { status: 'paused', runId, currentStep: null, lastError: 'canceled by user' });- broadcast(sId, { type: 'canceled', runId, steps: ordinal, completedAt: new Date().toISOString() });- console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps`);- } catch (err) {- const message = (err?.message || String(err)).slice(0, 1000);- console.error(`❌ autopilot failed — series=${sId.slice(0, 12)} ${message}`);- await persistMarker(sId, { status: 'error', runId, lastError: message });- broadcast(sId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });- await fileGap(record, sId, {- gapKind: 'run-error',- summary: `The autonomous run failed and stopped: ${message}`,- context: message,- }).catch(() => {});- } finally {- record.finished = true;- scheduleCleanup(sId, record);- }- })();-- return { runId, alreadyRunning: false, mode };-}--/**- * Boot-time recovery: the in-memory run map is lost on restart, so any series- * whose persisted marker still says `running` is demoted to `paused` (the user- * can click Run to resume from the next missing step). Mirrors- * recoverStuckAutoRuns in autoRunner.js. Best-effort; never blocks boot.- */-export async function recoverStuckAutopilots() {- const { listSeries } = await import('./series.js');- const all = await listSeries().catch(() => []);- const stuck = all.filter((s) => s.autopilot?.status === 'running');- if (stuck.length === 0) return 0;- for (const s of stuck) {- await updateSeries(s.id, {- autopilot: { ...s.autopilot, status: 'paused', lastError: 'interrupted by server restart', updatedAt: new Date().toISOString() },- }).catch(() => null);- }- console.log(`📝 autopilot: recovered ${stuck.length} stuck run${stuck.length === 1 ? '' : 's'} on boot`);- return stuck.length;-}+export * from './seriesAutopilot/state.js';+export * from './seriesAutopilot/config.js';+export * from './seriesAutopilot/convergence.js';+export * from './seriesAutopilot/stepResolver.js';+export * from './seriesAutopilot/session.js';+export * from './seriesAutopilot/childRuns.js';+export * from './seriesAutopilot/editorialSteps.js';+export * from './seriesAutopilot/visualSteps.js';+export * from './seriesAutopilot/revisionSteps.js';+export * from './seriesAutopilot/dispatch.js';+export * from './seriesAutopilot/dryRun.js';+export * from './seriesAutopilot/orchestrator.js';++// Export internals for tests. Pulled back together from their new home modules+// so the existing `__testing` import contract survives the #2842 split.+import { runs } from './seriesAutopilot/state.js';+import { summarizePlanCost } from './seriesAutopilot/convergence.js';+import { providerOverrideOpts, providerIdOpts } from './seriesAutopilot/session.js';+import { meanQualityScore } from './seriesAutopilot/revisionSteps.js';+import { buildDryRunPlan } from './seriesAutopilot/dryRun.js';-// Export internals for tests.export const __testing = { runs, buildDryRunPlan, summarizePlanCost, providerOverrideOpts, providerIdOpts, meanQualityScore };diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsnew file mode 100644index 0000000000..43abed0060--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -0,0 +1,342 @@+/**+ * Series Autopilot — child-run drivers (#2842 split of seriesAutopilot.js):+ * the arc-verify, beat-continuity and foundation convergence gates plus the+ * generic `runChildToCompletion` harness the beats/text stages ride on.+ */++import { sleep } from '../../../lib/fileUtils.js';+import { recordDomainUsage } from '../../domainUsage.js';+import { getSeries } from '../series.js';+import { listIssues, getIssue, isStageReady } from '../issues.js';+import { verifyArc, resolveVerifyIssues, analyzeBeatContinuity, resolveBeatContinuity } from '../arcPlanner.js';+import { judgeFoundation, applyFoundationFix, weakestDimension, residualFindings, DEFAULT_FOUNDATION_THRESHOLD } from '../foundationJudge.js';+import * as volumeBeatsRunner from '../volumeBeatsRunner.js';+import * as autoRunner from '../autoRunner.js';+import { MAX_ARC_VERIFY_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_CHILD_RETRIES } from './config.js';+import {+ CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,+ divergencePauseReason, foundationPauseReason, foundationDivergenceReason,+} from './convergence.js';+import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts } from './session.js';+import { requiredScriptStages, textReady } from './stepResolver.js';++// ---------------------------------------------------------------------------+// Step dispatch.+// ---------------------------------------------------------------------------++async function waitForChild(isActive, record) {+ while (isActive()) {+ if (record.cancelRequested) return;+ await sleep(CHILD_POLL_MS);+ }+}++export async function runArcVerify(seriesId, record) {+ const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)+ ? record.options.maxArcVerifyRounds+ : MAX_ARC_VERIFY_ROUNDS;+ // maxRounds === 0 means "skip verification entirely" — accept the arc as-is.+ if (maxRounds === 0) {+ record.runState.arcVerified = true;+ return {};+ }+ let convergence = { best: null, sinceBest: 0 };+ for (let round = 1; round <= maxRounds; round += 1) {+ if (record.cancelRequested) return { canceled: true };+ const beforeVerify = await budgetPause();+ if (beforeVerify) return beforeVerify;+ const { issues } = await verifyArc(seriesId, providerOverrideOpts(record));+ await recordDomainUsage('cos', { actions: 1 });+ const blocking = issues.filter((i) => record.options.blockingSets.arc.has(i.severity));+ broadcast(seriesId, {+ type: 'verify:round', scope: 'arc', round, findings: issues.length, blocking: blocking.length,+ });+ if (blocking.length === 0) {+ record.runState.arcVerified = true;+ return {};+ }+ if (round === maxRounds) {+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };+ }+ // Divergence guard (#1571): if the resolve passes stop reducing blocking+ // findings, bail now rather than burning the remaining rounds + budget.+ convergence = trackConvergence(convergence, blocking.length);+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('arc', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };+ }+ if (record.cancelRequested) return { canceled: true };+ // resolveVerifyIssues bills another action — recheck the budget so a single+ // step can't overspend the daily cap mid-loop.+ const beforeResolve = await budgetPause();+ if (beforeResolve) return beforeResolve;+ const resolved = await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(seriesId, {+ type: 'resolve:round', scope: 'arc', round,+ episodesEdited: Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0,+ });+ }+ return {};+}++// Whole-manuscript beat-continuity convergence loop (#1510). Mirrors+// runArcVerify one altitude down: verify the whole-book beat corpus, and on+// blocking findings resolve them by rewriting the offending issues' beats in+// place (resolveBeatContinuity → applyBeatResolutions, no beat-sheet+// regeneration), then re-verify. Bounded; pauses with the residual on+// non-convergence. Each verify + each resolve is budget-gated and bills one cos+// action, like the arc loop.+export async function runBeatContinuity(seriesId, record) {+ const maxRounds = Number.isInteger(record.options.maxBeatContinuityRounds)+ ? record.options.maxBeatContinuityRounds+ : MAX_BEAT_CONTINUITY_ROUNDS;+ // maxRounds === 0 means "skip the beat-continuity gate entirely".+ if (maxRounds === 0) {+ record.runState.beatContinuityChecked = true;+ return {};+ }+ let convergence = { best: null, sinceBest: 0 };+ for (let round = 1; round <= maxRounds; round += 1) {+ if (record.cancelRequested) return { canceled: true };+ const beforeVerify = await budgetPause();+ if (beforeVerify) return beforeVerify;+ const { issues } = await analyzeBeatContinuity(seriesId, providerOverrideOpts(record));+ await recordDomainUsage('cos', { actions: 1 });+ const blocking = issues.filter((i) => record.options.blockingSets.beatContinuity.has(i.severity));+ broadcast(seriesId, {+ type: 'verify:round', scope: 'beatContinuity', round, findings: issues.length, blocking: blocking.length,+ });+ if (blocking.length === 0) {+ record.runState.beatContinuityChecked = true;+ return {};+ }+ if (round === maxRounds) {+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('beatContinuity', maxRounds, blocking.length), residual: blocking };+ }+ // Divergence guard (#1571): bail when the resolve passes stop reducing blocking findings.+ convergence = trackConvergence(convergence, blocking.length);+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('beatContinuity', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };+ }+ if (record.cancelRequested) return { canceled: true };+ // resolveBeatContinuity bills another action — recheck the budget so a+ // single step can't overspend the daily cap mid-loop.+ const beforeResolve = await budgetPause();+ if (beforeResolve) return beforeResolve;+ const resolved = await resolveBeatContinuity(seriesId, { findings: blocking, ...providerOverrideOpts(record) });+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(seriesId, {+ type: 'resolve:round', scope: 'beatContinuity', round,+ episodesEdited: Array.isArray(resolved?.episodesResolved)+ ? resolved.episodesResolved.filter((e) => e?.corrected).length+ : 0,+ });+ }+ return {};+}++// Foundation-quality convergence loop (#2176). Mirrors runArcVerify but gates on+// a WEIGHTED SCORE (not a blocking-findings count): judge the whole foundation,+// and while it's below the threshold, target the weakest dimension, apply the+// fix through the owning service (universe refine / character expand / arc+// resolve — force:false, never a raw write), then re-judge. The re-judge is+// content-hash-cached, so an unchanged foundation short-circuits (no LLM) and+// can't loop. Bounded; pauses with the residual per-dimension findings on+// non-convergence. Each judge + each fix bills one cos action, budget-gated like+// the arc loop. The improve-loop convergence is tracked on the weighted score+// (higher = better), so divergence = the score failing to reach a NEW HIGH.+export async function runFoundationGate(seriesId, record) {+ const maxRounds = Number.isInteger(record.options.maxFoundationRounds)+ ? record.options.maxFoundationRounds+ : MAX_FOUNDATION_ROUNDS;+ // 0 rounds (or disabled) means "skip the gate entirely" — accept the+ // foundation as-is. The resolver already routes past a disabled gate, but a+ // dispatch that arrives here with 0 rounds still short-circuits cleanly.+ if (maxRounds === 0 || record.options.foundationGate === false) {+ record.runState.foundationGated = true;+ return {};+ }+ const threshold = Number.isFinite(record.options.foundationThreshold)+ ? record.options.foundationThreshold+ : DEFAULT_FOUNDATION_THRESHOLD;+ const providerId = record.options.providerOverride;+ const model = record.options.modelOverride;++ // Convergence tracker keyed on the weighted score (higher is better) — invert+ // to a "distance below 10" so trackConvergence's fewer-is-better minimum logic+ // applies unchanged (a new low distance = a new high score = progress).+ let convergence = { best: null, sinceBest: 0 };+ for (let round = 1; round <= maxRounds; round += 1) {+ if (record.cancelRequested) return { canceled: true };+ const beforeJudge = await budgetPause();+ if (beforeJudge) return beforeJudge;+ // Never force: judgeFoundation is content-hash-cached, so an unchanged+ // foundation (a clean verdict from a prior run, or a fix that changed+ // nothing) returns the cached score with no LLM call — this IS the fast-pass+ // that stops an already-clean foundation looping. A real change (any fix, or+ // a user edit) flips the pinned hash and re-judges automatically.+ const snap = await judgeFoundation(seriesId, { providerId, model });+ // A cached (content-hash unchanged) verdict did no LLM work — don't bill it.+ if (!snap.cached) await recordDomainUsage('cos', { actions: 1 });+ const score = snap.weightedScore ?? 0;+ const weak = weakestDimension(snap.dimensions);+ broadcast(seriesId, {+ type: 'foundation:round', round, weightedScore: score, threshold, weakest: weak?.dimension || null,+ });+ if (score >= threshold) {+ record.runState.foundationGated = true;+ return {};+ }+ if (round === maxRounds || !weak) {+ return {+ pause: true,+ pauseKind: 'maxRounds',+ reason: foundationPauseReason(maxRounds, score, threshold),+ residual: residualFindings(snap.dimensions),+ };+ }+ // Divergence guard (#1571): bail when fixes stop improving the score.+ convergence = trackConvergence(convergence, 10 - score);+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {+ return {+ pause: true,+ pauseKind: 'divergence',+ reason: foundationDivergenceReason(score, threshold, DIVERGENCE_PATIENCE),+ residual: residualFindings(snap.dimensions),+ };+ }+ if (record.cancelRequested) return { canceled: true };+ const beforeFix = await budgetPause();+ if (beforeFix) return beforeFix;+ const fix = await applyFoundationFix(seriesId, weak.dimension, {+ finding: snap.dimensions?.[weak.dimension] || {},+ providerOverride: providerId,+ modelOverride: model,+ });+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(seriesId, {+ type: 'foundation:fix', round, dimension: weak.dimension, applied: fix?.applied === true, reason: fix?.reason || null,+ });+ // A dimension whose owning service can't apply a fix (no linked universe, a+ // fully-locked cast, nothing left to fill) would loop unproductively — treat+ // an inapplicable fix as immediate non-convergence and pause for human+ // review rather than burning the remaining rounds re-judging an unchanged+ // foundation.+ if (fix?.applied !== true) {+ return {+ pause: true,+ pauseKind: 'inapplicable',+ reason: `Foundation gate can't auto-fix the weakest dimension (${weak.dimension}): ${fix?.reason || 'no change applied'}. Strengthen it manually, or lower the threshold, and resume.`,+ residual: residualFindings(snap.dimensions),+ };+ }+ }+ return {};+}++// Resolve the effective retry budget for a delegated child runner this run: a+// per-run `maxChildRetries` option wins, else the module default. Negative+// values clamp to 0 (single attempt).+function childRetryBudget(record) {+ const v = record.options.maxChildRetries;+ return Number.isInteger(v) ? Math.max(0, v) : MAX_CHILD_RETRIES;+}++// Delegate to a child SSE runner, block until it finishes, then VERIFY the child+// actually produced its target output before advancing (#1574). Shared by the+// beats and text steps. `checkReady` returns null when the output landed, or a+// `{ reason, residual }` describing what's still missing. On a miss the child is+// retried (skip-existing, so a retry only fills the gap) up to the run's retry+// budget; each attempt is budget-gated and bills one cos action. When the budget+// is exhausted the retries stop. If the output is still missing after the last+// attempt the work is marked attempted (so the resolver can't loop back here), an+// escalation frame is emitted, and a pause result is returned for human review —+// instead of the pre-#1574 silent skip that let a failed child reach 'done'.+async function runChildToCompletion(seriesId, record, {+ attemptedSet, kind, id, start, isActive, checkReady,+}) {+ const maxAttempts = childRetryBudget(record) + 1;+ let miss = null;+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {+ if (record.cancelRequested) return { canceled: true };+ // Each child run bills one cos action — budget-gate every attempt so a+ // retry can't overspend the daily cap (mirrors the verify loops).+ const beforeStart = await budgetPause();+ if (beforeStart) return beforeStart;+ await start();+ record.activeChild = { kind, id };+ await waitForChild(() => isActive(id), record);+ record.activeChild = null;+ await recordDomainUsage('cos', { actions: 1 });+ if (record.cancelRequested) return { canceled: true };+ miss = checkReady ? await checkReady() : null;+ if (!miss) {+ attemptedSet.add(id);+ return {};+ }+ if (attempt < maxAttempts) {+ broadcast(seriesId, {+ type: 'child:retry', kind, id, attempt, maxAttempts, reason: miss.reason,+ });+ }+ }+ // Output still missing after every attempt — escalate and pause. `pauseKind`+ // keeps this pause classifiable alongside the verify/editorial loops'+ // 'maxRounds'/'divergence' kinds (a child runner that couldn't produce output,+ // distinct from a convergence gate that ran out of rounds).+ attemptedSet.add(id);+ broadcast(seriesId, {+ type: 'child:escalate', kind, id, attempts: maxAttempts, reason: miss.reason,+ });+ return { pause: true, pauseKind: 'childFailed', reason: miss.reason, residual: miss.residual };+}++export const runBeats = (seriesId, seasonId, record) => runChildToCompletion(seriesId, record, {+ attemptedSet: record.runState.beatsAttempted,+ kind: 'beats',+ id: seasonId,+ start: () => volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, { mode: 'skip-existing', ...providerIdOpts(record) }),+ isActive: volumeBeatsRunner.isVolumeBeatsRunActive,+ // Beats succeeded when every issue in the volume has a ready `idea` stage —+ // the same predicate the resolver uses to decide a volume still needs beats.+ // Before #1574 a failed beats run was silently marked attempted and only+ // surfaced (if at all) when a downstream stage found `idea` empty.+ checkReady: async () => {+ const inSeason = (await listIssues({ seriesId })).filter((i) => i.seasonId === seasonId);+ const missing = inSeason.filter((i) => !isStageReady(i.stages?.idea));+ if (missing.length === 0) return null;+ return {+ reason: `beat generation for volume ${seasonId} did not produce beats for ${missing.length} issue(s)`,+ residual: missing.map((i) => ({ severity: 'high', location: `issue ${i.number ?? '?'} / idea`, problem: 'beat sheet (idea stage) is still empty after the beats run (likely an LLM failure)' })),+ };+ },+});++export const runText = (seriesId, issueId, record) => runChildToCompletion(seriesId, record, {+ attemptedSet: record.runState.textAttempted,+ kind: 'text',+ id: issueId,+ start: async () => {+ // Only adapt the target format's script(s) — a single-format series shouldn't+ // spend LLM calls populating the off-target script across every issue.+ const preIssue = await getIssue(issueId);+ const preSeries = await getSeries(preIssue.seriesId).catch(() => null);+ const scripts = requiredScriptStages(preSeries, record.options);+ // Forward the run's provider/model override so prose + scripts honor it like+ // every other step (autoRunner threads these into generateStage).+ await autoRunner.startAutoRunTextStages(issueId, { force: false, scripts, ...providerIdOpts(record) });+ },+ isActive: autoRunner.isAutoRunActive,+ // A delegated text run can end with required stages still empty (the child's+ // LLM call failed) — verify the required stages landed before advancing.+ checkReady: async () => {+ const issue = await getIssue(issueId);+ const series = await getSeries(issue.seriesId).catch(() => null);+ if (textReady(issue, series, record.options)) return null;+ const missing = requiredScriptStages(series, record.options).filter((s) => !isStageReady(issue.stages?.[s]));+ return {+ reason: `text generation for issue ${issue.number ?? issueId} did not produce required stage(s): ${missing.join(', ')}`,+ residual: missing.map((s) => ({ severity: 'high', location: `issue ${issue.number ?? '?'} / ${s}`, problem: 'stage is still empty after the text run (likely an LLM failure)' })),+ };+ },+});diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.jsnew file mode 100644index 0000000000..ea309e7a1f--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/config.js@@ -0,0 +1,196 @@+/**+ * Series Autopilot — convergence-round ceilings, gate defaults and the+ * per-run/settings option resolvers (#2842 split of seriesAutopilot.js).+ */++import { readReadinessGate } from '../../../lib/editorial/index.js';+import { READINESS_GATES } from '../editorialScore.js';++// Bounded convergence loops — re-verify/re-review at most this many rounds, then+// pause for human review with the residual findings (see module header). These+// are the floor defaults; an install can raise them persistently via+// pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds} (or a single+// run can override per-run through the autopilot start options).+export const MAX_ARC_VERIFY_ROUNDS = 3;+export const MAX_EDITORIAL_ROUNDS = 2;+// Whole-manuscript beat-continuity convergence (#1510). The corpus is the+// compact per-issue beat sheets, so this gate sits between beat generation and+// the expensive text/script stage — bounded like the others, then pauses with+// the residual findings for human review.+export const MAX_BEAT_CONTINUITY_ROUNDS = 2;++// Foundation-quality gate (CWQE Phase 11, #2176). Before drafting, judge the+// whole foundation (world / characters / arc) against a weighted rubric and+// iterate on the weakest dimension until it clears a threshold — bounded like+// the other convergence loops, then pause with the residual per-dimension+// findings for human review. Defaults ON for autopilot runs (the point of the+// phase) but overridable per-run + via the persisted setting. 0 rounds skips+// the gate entirely (accept the foundation as-is).+export const MAX_FOUNDATION_ROUNDS = 3;+export const DEFAULT_FOUNDATION_GATE_ENABLED = true;++// Bounded retry budget for a delegated child runner (#1574). A child (volume+// beats / text auto-run) can finish with its target stage(s) still empty when+// the underlying LLM call failed. Before #1574 the autopilot marked the work+// attempted and advanced regardless — so a transient failure was caught only+// later (text) or not at all until a downstream emptiness check (beats). Now a+// child whose readiness check fails is retried up to MAX_CHILD_RETRIES more+// times (skip-existing, so a retry only fills the gap) before the work is+// marked attempted, an escalation frame is emitted, and the run pauses with the+// residual. 0 = single attempt, no retry (the legacy behavior). A per-run+// `maxChildRetries` option overrides it (plumbed through runOptions).+export const MAX_CHILD_RETRIES = 1;++// Resolve the effective round bounds for a run: an explicit per-run option wins,+// then the persisted pipelineEditorialChecks setting, then the module default.+// Returns integers only — a non-integer at any layer falls through to the next.+// Centralized so the loops, the dry-run plan, and the resume path all agree.+export function resolveAutopilotRounds(options = {}, settings = null) {+ const pec = settings?.pipelineEditorialChecks || {};+ const pick = (optKey, setKey, fallback) => {+ if (Number.isInteger(options?.[optKey])) return options[optKey];+ if (Number.isInteger(pec?.[setKey])) return pec[setKey];+ return fallback;+ };+ return {+ maxArcVerifyRounds: pick('maxArcVerifyRounds', 'maxArcVerifyRounds', MAX_ARC_VERIFY_ROUNDS),+ maxEditorialRounds: pick('maxEditorialRounds', 'maxEditorialRounds', MAX_EDITORIAL_ROUNDS),+ maxBeatContinuityRounds: pick('maxBeatContinuityRounds', 'maxBeatContinuityRounds', MAX_BEAT_CONTINUITY_ROUNDS),+ maxFoundationRounds: pick('maxFoundationRounds', 'maxFoundationRounds', MAX_FOUNDATION_ROUNDS),+ };+}++// Foundation-gate config (#2176): whether the gate runs, and the weighted [0,10]+// threshold the foundation must clear. Mirror resolveAutopilotRounds — per-run+// option wins, then the persisted pipelineEditorialChecks setting, then the+// default. The enable flag defaults ON (the point of the phase); the threshold+// falls through to DEFAULT_FOUNDATION_THRESHOLD in the loop when unset. Stamped+// onto run options once at start so the loop, the dry-run plan, and a resume all+// read the same effective values.+export function resolveAutopilotFoundationGate(options = {}, settings = null) {+ if (typeof options?.foundationGate === 'boolean') return options.foundationGate;+ const pec = settings?.pipelineEditorialChecks || {};+ if (typeof pec?.foundationGate === 'boolean') return pec.foundationGate;+ return DEFAULT_FOUNDATION_GATE_ENABLED;+}+export function resolveAutopilotFoundationThreshold(options = {}, settings = null) {+ if (Number.isFinite(options?.foundationThreshold)) return options.foundationThreshold;+ const pec = settings?.pipelineEditorialChecks || {};+ if (Number.isFinite(pec?.foundationThreshold)) return pec.foundationThreshold;+ return null;+}++// Resolve the effective editorial-health readiness gate for a run (#1580): an+// explicit per-run option wins, then the persisted+// pipelineEditorialChecks.readinessGate, then null — the caller resolves null to+// DEFAULT_READINESS_GATE via resolveReadinessGate. Mirrors resolveAutopilotRounds+// so the gate is overridable per-run exactly like the round bounds; stamped onto+// the run options once at start so the loop, the dry-run plan, and a later resume+// all read the same effective gate.+export function resolveAutopilotReadinessGate(options = {}, settings = null) {+ if (READINESS_GATES.includes(options?.readinessGate)) return options.readinessGate;+ return readReadinessGate(settings);+}++// Editorial-checks pause threshold (#1613): pause the run when the checks pass+// surfaces ≥ N high-severity findings. 0 = off (the default), so the gate is+// opt-in and existing installs are unchanged. Mirrors resolveAutopilotRounds —+// per-run option wins, then the persisted setting, then 0. A non-integer at any+// layer falls through to the next. Stamped onto run options once at start so the+// loop and a later resume read the same effective threshold.+export const DEFAULT_CHECK_FINDINGS_PAUSE_THRESHOLD = 0;+export function resolveAutopilotCheckPauseThreshold(options = {}, settings = null) {+ if (Number.isInteger(options?.checkFindingsPauseThreshold)) return options.checkFindingsPauseThreshold;+ const pec = settings?.pipelineEditorialChecks || {};+ if (Number.isInteger(pec?.checkFindingsPauseThreshold)) return pec.checkFindingsPauseThreshold;+ return DEFAULT_CHECK_FINDINGS_PAUSE_THRESHOLD;+}++// Pause escalation (#1615): post an in-app notification (notification center,+// surfaced in the header dropdown) when a run pauses, so a paused run doesn't sit+// unnoticed until the user happens to open the status page. Unlike the other+// gates this defaults ON — it's a zero-cost informational signal that directly+// addresses the "paused runs go unnoticed" problem — but stays overridable per+// run and via the persisted setting for users who don't want the noise. Boolean+// at every layer: per-run option wins, then the persisted setting, then true.+export const DEFAULT_NOTIFY_ON_PAUSE = true;+export function resolveAutopilotNotifyOnPause(options = {}, settings = null) {+ if (typeof options?.notifyOnPause === 'boolean') return options.notifyOnPause;+ const pec = settings?.pipelineEditorialChecks || {};+ if (typeof pec?.notifyOnPause === 'boolean') return pec.notifyOnPause;+ return DEFAULT_NOTIFY_ON_PAUSE;+}++// Autopilot → CD teaser deliverable (CDO Phase 3, #2185). Once a comic issue is+// text-ready + drafted, the autopilot can OPTIONALLY mint + start a Creative+// Director video project (a teaser/trailer) seeded from the issue — the reverse+// of the CD→autopilot bridge. Defaults OFF: producing video is a fresh burst of+// LLM + render spend the user must opt into, so existing runs are unchanged.+// Per-run option wins, then the persisted setting, then false. Stamped onto run+// options once at start so the resolver, the dry-run plan, and a later resume+// all read the same effective flag.+export const DEFAULT_PRODUCE_TEASER = false;+export function resolveAutopilotProduceTeaser(options = {}, settings = null) {+ if (typeof options?.produceTeaser === 'boolean') return options.produceTeaser;+ const pec = settings?.pipelineEditorialChecks || {};+ if (typeof pec?.produceTeaser === 'boolean') return pec.produceTeaser;+ return DEFAULT_PRODUCE_TEASER;+}++// Does THIS run want to produce a teaser deliverable? Gated on the resolved+// `produceTeaser` flag AND that visuals ran (a teaser is a visual deliverable —+// pointless on a text-only run).+export function wantsTeaser(options = {}) {+ return options.produceTeaser === true && wantsVisual(options);+}++// Iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in per run; when+// enabled the autopilot cycles the weakest issue through adversarial cuts ++// judge-gated keep/revert instead of stopping at the editorial-health gate.+// Defaults OFF — it is a fresh burst of judge + cut LLM spend the user must+// opt into. minCycles floors the plateau/hedge stops so the loop always runs at+// least once; maxCycles is the cost ceiling; plateauDelta is the mean-score+// movement below which the series counts as converged. Per-run option wins, then+// the persisted pipelineEditorialChecks.revision* setting, then the default.+export const DEFAULT_REVISION_ENABLED = false;+export const DEFAULT_REVISION_MIN_CYCLES = 1;+export const DEFAULT_REVISION_MAX_CYCLES = 2;+export const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;+export function resolveAutopilotRevision(options = {}, settings = null) {+ const pec = settings?.pipelineEditorialChecks || {};+ const bool = (o, s, fallback) => {+ if (typeof o === 'boolean') return o;+ if (typeof s === 'boolean') return s;+ return fallback;+ };+ const int = (o, s, fallback) => {+ if (Number.isInteger(o)) return o;+ if (Number.isInteger(s)) return s;+ return fallback;+ };+ const num = (o, s, fallback) => {+ if (Number.isFinite(o)) return o;+ if (Number.isFinite(s)) return s;+ return fallback;+ };+ const minCycles = int(options?.revisionMinCycles, pec?.revisionMinCycles, DEFAULT_REVISION_MIN_CYCLES);+ const maxCycles = int(options?.revisionMaxCycles, pec?.revisionMaxCycles, DEFAULT_REVISION_MAX_CYCLES);+ return {+ revisionEnabled: bool(options?.revisionEnabled, pec?.revisionEnabled, DEFAULT_REVISION_ENABLED),+ revisionMinCycles: Math.max(1, minCycles),+ // maxCycles never below minCycles — a misconfig can't strand the loop unable to run.+ revisionMaxCycles: Math.max(Math.max(1, minCycles), maxCycles),+ revisionPlateauDelta: Math.max(0, num(options?.revisionPlateauDelta, pec?.revisionPlateauDelta, DEFAULT_REVISION_PLATEAU_DELTA)),+ };+}++// Effective "produce draft visuals?" decision. The `target` option overrides+// the `includeVisual` flag: 'text' forces text-only (no canon gate, no render),+// 'visual' forces visuals, and 'auto' (the default) honors `includeVisual`+// (which itself defaults true). Without this, a `target:'text'` request on a+// comic series would still run canonVerify + queue draft renders.+export function wantsVisual(options = {}) {+ if (options.target === 'text') return false;+ if (options.target === 'visual') return true;+ return options.includeVisual !== false;+}diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.jsnew file mode 100644index 0000000000..e3bd4c3756--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/convergence.js@@ -0,0 +1,131 @@+/**+ * Series Autopilot — convergence tracking & pause-reason copy (#2842 split of+ * seriesAutopilot.js). The bounded-loop bookkeeping (`trackConvergence`,+ * `DIVERGENCE_PATIENCE`) and the human-readable reason strings each gate pauses+ * with, plus the dry-run cost arithmetic they share.+ */++// Per-gate copy for the non-convergence pause — shared by the arc-verify and+// editorial loops so the two messages can't drift.+const PAUSE_GATES = {+ arc: { label: 'Arc verification', fix: 'Edit the arc/volumes to address them', limit: 'verify-rounds' },+ beatContinuity: { label: 'Beat continuity', fix: 'Edit the affected issue beats', limit: 'beat-continuity-rounds' },+ editorial: { label: 'Editorial review', fix: 'Address them in the manuscript editor', limit: 'editorial-rounds' },+ foundation: { label: 'Foundation quality', fix: 'Strengthen the world / characters / arc, or lower the threshold', limit: 'foundation-rounds' },+};+export function convergencePauseReason(gate, maxRounds, blockingCount) {+ const { label, fix, limit } = PAUSE_GATES[gate];+ const plural = maxRounds === 1 ? 'round' : 'rounds';+ return `${label} couldn't auto-resolve ${blockingCount} blocking finding(s) in ${maxRounds} ${plural} — `+ + `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;+}++// Divergence/oscillation guard for the bounded convergence loops (#1571). A+// verify→resolve round is "profitable" only when the next verify shows STRICTLY+// FEWER blocking findings. When the count fails to drop (stays equal, or rises —+// a resolve pass that introduced a new break while fixing another) for+// DIVERGENCE_PATIENCE consecutive rounds, the loop is no longer converging:+// stop early and pause with a `divergence` kind instead of burning the rest of+// the daily cos budget down to maxRounds. The terminal maxRounds pause keeps its+// own `maxRounds` kind — the two are distinguished in the pause SSE frame so the+// UI can tell "needs a human" (diverging) from "just ran out of rounds".+//+// With the default caps (arc 3 / beat 2 / editorial 2) the loop hits maxRounds+// before the streak can reach patience, so default runs are unaffected; the+// guard only bites when a user RAISES a cap and the loop then stalls.+export const DIVERGENCE_PATIENCE = 2;++// Convergence tracker for one verify→resolve round. `state` is+// { best, sinceBest }: `best` is the FEWEST blocking findings seen so far this+// loop (null before the first measured round), `sinceBest` the count of+// consecutive rounds since that minimum last STRICTLY improved. A round that+// reaches a new low is progress (sinceBest → 0); a stall, a regression (a fix+// that introduced a new break), OR an oscillation that merely revisits an old+// count all accrue sinceBest. The loop diverges once sinceBest reaches+// DIVERGENCE_PATIENCE. Tracking the running minimum (not just the previous+// round) is what lets this catch a 2-cycle oscillation — e.g. 5→4→5→4 never+// sets a new low after round 2, so it's caught — which a naive+// "compare to the previous round" check would miss. Pure + unit-tested.+export function trackConvergence(state, curr) {+ if (state.best === null || curr < state.best) {+ return { best: curr, sinceBest: 0 };+ }+ return { best: state.best, sinceBest: state.sinceBest + 1 };+}++// Pause reason for a gate that stopped converging early (#1571) — distinct+// wording from convergencePauseReason's "ran out of rounds".+export function divergencePauseReason(gate, blockingCount, rounds) {+ const { label, fix } = PAUSE_GATES[gate];+ const plural = rounds === 1 ? 'round' : 'rounds';+ return `${label} stopped converging — ${blockingCount} blocking finding(s) and no net progress over `+ + `${rounds} consecutive ${plural} of auto-resolve. Paused for review. ${fix}, then resume.`;+}++// Foundation gate pause reasons (#2176) — the gate converges on a WEIGHTED+// SCORE, not a finding count, so it needs its own wording (score vs. threshold)+// rather than the finding-count phrasing of convergencePauseReason. Shares+// PAUSE_GATES.foundation so the copy stays aligned with the other gates.+export function foundationPauseReason(maxRounds, score, threshold) {+ const { label, fix, limit } = PAUSE_GATES.foundation;+ const plural = maxRounds === 1 ? 'round' : 'rounds';+ return `${label} couldn't reach the threshold (weighted ${score} < ${threshold}) in ${maxRounds} ${plural} — `+ + `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;+}+export function foundationDivergenceReason(score, threshold, rounds) {+ const { label, fix } = PAUSE_GATES.foundation;+ const plural = rounds === 1 ? 'round' : 'rounds';+ return `${label} stopped improving — weighted ${score} still below ${threshold} with no net gain over `+ + `${rounds} consecutive ${plural} of auto-fix. Paused for review. ${fix}, then resume.`;+}++// Dry-run plan note for a bounded gate: "skipped (0 rounds)" or "up to N rounds".+export const roundsNote = (rounds) => (rounds === 0 ? 'skipped (0 rounds)' : `up to ${rounds} rounds`);++// Dry-run cost model (#1576) — each planned step carries an estimated+// `estActions`: the number of cos actions it bills via recordDomainUsage('cos',+// { actions }), i.e. the unit the daily budget cap gates on. Surfacing it lets a+// user see, before starting, whether a large series will exhaust the cap on+// text/verify and never reach editorial. Estimates are approximate and lean+// toward the high end — convergence loops counted at their max rounds (they+// usually converge sooner), per-item steps at one action per item (retries+// excluded). A few steps cost nothing against the cap (editorialHealthGate,+// canonVerify) and carry estActions: 0. One known UNDER-count: the editorial+// review's per-comment auto-fixes each bill an extra action and scale with the+// number of blocking findings, which isn't knowable at plan time — so a heavy+// editorial pass can exceed its estimate.+//+// A bounded verify→resolve convergence loop (arc, beat-continuity, editorial)+// bills one action per verify plus (roughly) one per resolve; the final round+// never resolves (it converges or pauses). Estimate: rounds verifies ++// (rounds-1) resolves.+export const convergenceLoopActions = (rounds) => (rounds <= 0 ? 0 : 2 * rounds - 1);++// Sum a dry-run plan's per-step estimates into run totals. `estActions` is the+// budget-relevant total (cos daily-cap units); `estLlmCalls` aggregates the+// check-pass fan-out (editorialChecks bills a single cos action but issues many+// LLM calls — see the rough proxy at its plan.push). Pure — safe to call at+// broadcast time and in tests.+export function summarizePlanCost(plan) {+ return (Array.isArray(plan) ? plan : []).reduce(+ (acc, step) => ({+ estActions: acc.estActions + (Number.isFinite(step?.estActions) ? step.estActions : 0),+ estLlmCalls: acc.estLlmCalls + (Number.isFinite(step?.estLlmCalls) ? step.estLlmCalls : 0),+ }),+ { estActions: 0, estLlmCalls: 0 },+ );+}++// When true, a comic-target run with `includeVisual` proceeds past the text ++// editorial terminal into draft cover/page rendering (see runVisualDraft).+export const VISUAL_DRAFT_ENABLED = true;++// Which severities block each verify/review gate (low is informational) is now+// PER-SERIES configurable (#1616): the defaults (arc/beatContinuity → high+medium,+// editorial → high) live in `lib/editorial/severityConfig.js` and a series may+// override any gate. `startSeriesAutopilot` resolves each gate's blocking Set+// once via `resolveBlockingSet(series.blockingSeverities, gate)` and stamps it on+// `record.options.blockingSets` so every read site uses the same resolved set.++// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).+export const CHILD_POLL_MS = 750;diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.jsnew file mode 100644index 0000000000..6b011ddee5--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/dispatch.js@@ -0,0 +1,83 @@+/**+ * Series Autopilot — step dispatch table (#2842 split of seriesAutopilot.js).+ * Maps a resolved step kind onto the runner that executes it.+ */++import { recordDomainUsage } from '../../domainUsage.js';+import { getSeries } from '../series.js';+import { generateArcOverview, commitSeasonsWithRemap, generateSeasonEpisodes, commitEpisodesToIssues } from '../arcPlanner.js';+import { providerOverrideOpts } from './session.js';+import { runArcVerify, runBeats, runBeatContinuity, runFoundationGate, runText } from './childRuns.js';+import { runScriptVerify, runEditorial, runReverseOutlineRefresh, runEditorialChecksPass, runEditorialHealthGate } from './editorialSteps.js';+import { runCanonVerify, runVisualDraft, runProduceTeaser } from './visualSteps.js';+import { runRevisionCycle } from './revisionSteps.js';++export async function dispatchStep(sId, step, record) {+ switch (step.kind) {+ case 'generateArc': {+ // Mark attempted up front so the resolver won't re-route here if arc+ // generation yields no seasons (avoids an infinite generateArc loop).+ record.runState.arcAttempted = true;+ const r = await generateArcOverview(sId, providerOverrideOpts(record));+ const committed = await commitSeasonsWithRemap(await getSeries(sId), { arc: r.arc, seasons: r.seasons });+ await recordDomainUsage('cos', { actions: 1 });+ const seasonCount = committed?.series?.seasons?.length ?? (await getSeries(sId)).seasons?.length ?? 0;+ if (seasonCount === 0) {+ // No specific gap filed here — let the conductor file generateArc-stalled.+ return {+ pause: true,+ reason: 'arc generation produced no volumes — cannot create issues; review the series bible and regenerate the arc',+ residual: [{ severity: 'high', location: 'arc', problem: 'arc overview returned zero seasons/volumes' }],+ };+ }+ return {};+ }+ case 'generateEpisodes': {+ // Mark attempted up front so an empty/invalid episode list can't re-loop+ // the resolver back into generateEpisodes for the same still-empty volume.+ record.runState.episodesAttempted.add(step.seasonId);+ const r = await generateSeasonEpisodes(sId, step.seasonId, providerOverrideOpts(record));+ const cur = await getSeries(sId);+ const created = await commitEpisodesToIssues(sId, step.seasonId, r.episodes, { preloadedSeries: cur });+ await recordDomainUsage('cos', { actions: 1 });+ if (!Array.isArray(created) || created.length === 0) {+ return {+ pause: true,+ reason: `episode generation produced no issues for volume ${step.seasonId} — review the volume outline and regenerate`,+ residual: [{ severity: 'high', location: `volume ${step.seasonId}`, problem: 'episode breakdown returned zero episodes/issues' }],+ };+ }+ return {};+ }+ case 'verifyArc':+ return runArcVerify(sId, record);+ case 'beatSheet':+ return runBeats(sId, step.seasonId, record);+ case 'beatContinuity':+ return runBeatContinuity(sId, record);+ case 'foundationGate':+ return runFoundationGate(sId, record);+ case 'textStages':+ return runText(sId, step.issueId, record);+ case 'scriptVerify':+ return runScriptVerify(sId, step.issueId, record);+ case 'editorialReview':+ return runEditorial(sId, record);+ case 'reverseOutline':+ return runReverseOutlineRefresh(sId, record);+ case 'editorialChecks':+ return runEditorialChecksPass(sId, record);+ case 'editorialHealthGate':+ return runEditorialHealthGate(sId, record);+ case 'revisionCycle':+ return runRevisionCycle(sId, record);+ case 'canonVerify':+ return runCanonVerify(sId, record);+ case 'visualDraft':+ return runVisualDraft(sId, step.issueId, record);+ case 'produceTeaser':+ return runProduceTeaser(sId, step.issueId, record);+ default:+ return {};+ }+}diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.jsnew file mode 100644index 0000000000..1fc4dc0b4a--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/dryRun.js@@ -0,0 +1,138 @@+/**+ * Series Autopilot — dry-run plan builder (#2842 split of seriesAutopilot.js).+ * Walks the same step resolver the live run uses to project the work, cost and+ * gates a run would perform, without executing anything.+ */++import { isStageReady } from '../issues.js';+import { resolveReadinessGate } from '../editorialScore.js';+import {+ MAX_ARC_VERIFY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_EDITORIAL_ROUNDS,+ resolveAutopilotCheckPauseThreshold, resolveAutopilotRevision, wantsTeaser, wantsVisual,+} from './config.js';+import { roundsNote, convergenceLoopActions, VISUAL_DRAFT_ENABLED } from './convergence.js';+import { orderedIssues, byNumber, issueHasBeats, textReady, wantsComic, visualReady } from './stepResolver.js';+import { editorialSubsetIds } from './editorialSteps.js';++// ---------------------------------------------------------------------------+// Dry-run planning — enumerate what execute WOULD do, no side effects.+// ---------------------------------------------------------------------------++// Mirrors resolveNextStep's step ordering, but enumerates the FULL remaining+// plan (counts of every unmet step) rather than returning only the next one —+// so it can't reuse the single-step resolver. Kept deliberately in sync by+// hand; they share the same predicates (textReady, isComicTarget, isStageReady).+// `costContext.editorialLlmCheckCount` (optional) is the resolved number of+// enabled LLM-kind editorial checks for this run's subset — supplied by the+// caller (which has loaded settings) so this stays a pure, synchronous function.+// When provided it drives the editorialChecks step's estLlmCalls (issues × LLM+// checks) and whether that pass bills a cos action at all; absent, the step+// estimates a single LLM check.+export function buildDryRunPlan(series, issues, options, costContext = {}) {+ const plan = [];+ const ordered = orderedIssues(issues);+ const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];+ // Mirror the resolver: generateArc runs when arc text is missing OR there are+ // no volumes at all (an arc-only series), so a dry-run plan must show it too.+ const noArc = !series?.arc?.logline && !series?.arc?.summary;+ if (noArc || seasons.length === 0) plan.push({ kind: 'generateArc', count: 1, estActions: 1 });+ const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));+ if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length, estActions: emptySeasons.length });+ const arcRounds = Number.isInteger(options?.maxArcVerifyRounds) ? options.maxArcVerifyRounds : MAX_ARC_VERIFY_ROUNDS;+ plan.push({ kind: 'verifyArc', count: 1, note: roundsNote(arcRounds), estActions: convergenceLoopActions(arcRounds) });+ // foundationGate (#2176) runs once between arc verify and beats, unless+ // disabled or 0-round. Bills judge + fix per round like the arc loop.+ const foundationRounds = Number.isInteger(options?.maxFoundationRounds) ? options.maxFoundationRounds : MAX_FOUNDATION_ROUNDS;+ if (options?.foundationGate !== false && foundationRounds !== 0) {+ plan.push({ kind: 'foundationGate', count: 1, note: roundsNote(foundationRounds), estActions: convergenceLoopActions(foundationRounds) });+ }+ const beatsNeeded = seasons.filter((s) =>+ ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;+ if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded, estActions: beatsNeeded });+ // beatContinuity (#1510) runs once when the run will have a beat corpus to+ // check: beats already exist, OR beatSheet will generate them this run. Mirror+ // the resolver's `ordered.some(issueHasBeats)` gate (post-generation), so a+ // synopsis-only run that produces no beats doesn't advertise a pass it skips.+ if (ordered.some(issueHasBeats) || beatsNeeded) {+ const bcRounds = Number.isInteger(options?.maxBeatContinuityRounds)+ ? options.maxBeatContinuityRounds+ : MAX_BEAT_CONTINUITY_ROUNDS;+ plan.push({ kind: 'beatContinuity', count: 1, note: roundsNote(bcRounds), estActions: convergenceLoopActions(bcRounds) });+ }+ const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;+ if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded, estActions: textNeeded });+ if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: ordered.length, estActions: ordered.length });+ const edRounds = Number.isInteger(options?.maxEditorialRounds) ? options.maxEditorialRounds : MAX_EDITORIAL_ROUNDS;+ // Editorial review is a verify→auto-fix convergence loop like the arc gate, so+ // the per-round estimate mirrors it (analyze + one resolve batch / round). The+ // per-comment auto-fixes within a round bill additionally and scale with the+ // number of blocking findings, which isn't knowable at plan time.+ plan.push({ kind: 'editorialReview', count: 1, note: roundsNote(edRounds), estActions: convergenceLoopActions(edRounds) });+ // maxEditorialRounds === 0 skips the whole editorial gate in execute mode+ // (runEditorial marks editorialReviewed + editorialChecksReviewed ++ // editorialHealthReady), so the plan must not advertise the registry checks or+ // the health gate that won't run.+ if (edRounds !== 0) {+ plan.push({ kind: 'reverseOutline', count: 1, note: 'refresh scene segmentation for editorial checks (#1349)', estActions: 1 });+ // #1575 — when a per-run subset is set, the plan must say so rather than imply+ // the full enabled set runs.+ const editorialSubset = editorialSubsetIds(options);+ // The checks pass bills a single cos action (only when an LLM check runs) but+ // fans out to many LLM calls. The real call count depends on how each check+ // chunks the stitched manuscript by provider context window, so it isn't+ // knowable at plan time — `issues × enabled LLM checks` is a rough proxy that+ // scales with both series size and check count, surfaced so a large series's+ // check cost is visible. When the caller didn't resolve the enabled-check+ // count, assume one LLM check runs.+ const llmCheckCount = Number.isInteger(costContext?.editorialLlmCheckCount)+ ? costContext.editorialLlmCheckCount+ : 1;+ const estLlmCalls = ordered.length * llmCheckCount;+ const checksNote = editorialSubset+ ? `per-run subset of ${editorialSubset.length} editorial check(s) (#1575)`+ : 'enabled editorial checks (#1284)';+ // Surface the optional pause threshold (#1613) when armed, mirroring how the+ // readiness gate is exposed below — so a per-run override is visible in the plan.+ const pauseThreshold = resolveAutopilotCheckPauseThreshold(options);+ const pauseNote = pauseThreshold > 0 ? ` — pauses at ≥ ${pauseThreshold} high finding(s) (#1613)` : '';+ plan.push({+ kind: 'editorialChecks',+ count: 1,+ note: (llmCheckCount > 0 ? `${checksNote} — ~${estLlmCalls} LLM call(s)` : checksNote) + pauseNote,+ estActions: llmCheckCount > 0 ? 1 : 0,+ estLlmCalls,+ });+ // Surface the effective readiness gate (#1580) so a per-run override is+ // visible in the dry-run plan, mirroring how roundsNote exposes the bounds.+ const gate = resolveReadinessGate(options?.readinessGate);+ plan.push({ kind: 'editorialHealthGate', count: 1, note: `editorial health readiness gate (#1316) — gate: ${gate}`, estActions: 0 });+ }+ // Iterate-to-quality revision loop (#2171, opt-in, default off). Each cycle+ // judges every drafted issue (cache-aware — only stale/unjudged content bills),+ // runs one adversarial-cut pass, and re-judges the revised issue: roughly+ // (issues + 2) actions per cycle, capped at maxCycles. High-end estimate — a+ // cycle stops early on plateau / hedged-convergence and cached judges are free.+ if (options?.revisionEnabled) {+ const rev = resolveAutopilotRevision(options);+ plan.push({+ kind: 'revisionCycle',+ count: rev.revisionMaxCycles,+ note: `iterate-to-quality (up to ${rev.revisionMaxCycles} cycle(s), min ${rev.revisionMinCycles}, plateau Δ ${rev.revisionPlateauDelta})`,+ estActions: rev.revisionMaxCycles * (ordered.length + 2),+ });+ }+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {+ // canonVerify runs an LLM pass but bills no cos action (token-only) — 0 budget.+ plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns (no budget cost)', estActions: 0 });+ const visualNeeded = ordered.filter((i) => !visualReady(i)).length;+ // Each draft render bills one cos action: cover + back per issue, plus one per+ // interior page. The interior-page count isn't known until the script parses,+ // so the estimate counts the two covers and notes the per-page additions.+ if (visualNeeded) plan.push({ kind: 'visualDraft', count: visualNeeded, note: 'cover + back + all pages (draft) — +1 action per interior page', estActions: visualNeeded * 2 });+ // Teaser deliverable (#2185, opt-in, default off): one CD video project per+ // issue. Each mint+start bills one cos action for the treatment LLM call; the+ // CD project's own render spend is gated on the creative/cos budget its side.+ if (wantsTeaser(options)) plan.push({ kind: 'produceTeaser', count: ordered.length, note: 'mint + start a Creative Director teaser video per issue (opt-in)', estActions: ordered.length });+ }+ return plan;+}diff --git a/server/services/pipeline/seriesAutopilot/editorialSteps.js b/server/services/pipeline/seriesAutopilot/editorialSteps.jsnew file mode 100644index 0000000000..86a5844f4a--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/editorialSteps.js@@ -0,0 +1,395 @@+/**+ * Series Autopilot — editorial pipeline steps (#2842 split of seriesAutopilot.js):+ * script verification, the LLM review loop, the reverse-outline refresh, the+ * declarative editorial-check pass and the readiness/health gate.+ */++import { recordDomainUsage } from '../../domainUsage.js';+import { getSettings } from '../../settings.js';+import { getIssue } from '../issues.js';+import { analyzeManuscriptCompleteness } from '../arcPlanner.js';+import { verifyComicScript } from '../scriptVerify.js';+import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';+import { generateManuscriptFix, acceptManuscriptFix } from '../manuscriptFix.js';+import { runEditorialChecks, buildEditorialCheckPlan, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors } from '../editorial/checkRunner.js';+import { generateReverseOutline, getReverseOutline } from '../reverseOutline.js';+import { computeHealth, openBlockers, summarizeEditorialBlockers, formatBlockerSummary } from '../editorialScore.js';+import { MAX_EDITORIAL_ROUNDS } from './config.js';+import { DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason, divergencePauseReason } from './convergence.js';+import { broadcast, budgetPause, fileGap, providerOverrideOpts, providerIdOpts } from './session.js';+import { scriptStructurallyReady } from './stepResolver.js';++export async function runScriptVerify(sId, issueId, record) {+ record.runState.scriptChecked.add(issueId);+ const issue = await getIssue(issueId);++ // Gate 1 — STRUCTURAL (pure, cheap): does the script parse into pages/panels?+ // This is the only structural validation before completion in text-only /+ // visual-disabled comic runs, so a failure must BLOCK (pause), not just mark+ // the issue checked — otherwise the run could report done with a script that+ // can't become pages.+ if (!scriptStructurallyReady(issue)) {+ await fileGap(record, sId, {+ gapKind: 'script-unparseable',+ issueId,+ summary: 'The comic script for this issue does not parse into pages/panels, so comic pages can\'t be extracted. It likely needs a manual fix or regeneration of the comicScript stage.',+ context: `issueId=${issueId}`,+ });+ return {+ pause: true,+ gapFiled: true,+ reason: `comic script for issue ${issue.number ?? issueId} does not parse into pages/panels`,+ residual: [{ severity: 'high', location: `issue ${issue.number ?? '?'} / comicScript`, problem: 'script did not parse into pages/panels — cannot extract comic pages' }],+ };+ }++ // Gate 2 — CRAFT (LLM): does the script function as a comic script? This is+ // ADVISORY — unlike arc continuity, script craft is subjective and the+ // gating quality pass is the series-level editorial review, so blocking+ // findings are surfaced + filed (not auto-rewritten, not a hard pause) and+ // the autopilot keeps moving toward a draft. Wrapped so an LLM failure+ // downgrades to a skip instead of aborting the whole run.+ let issues = [];+ try {+ const result = await verifyComicScript(issueId, providerIdOpts(record));+ issues = result.issues || [];+ await recordDomainUsage('cos', { actions: 1 });+ } catch (err) {+ broadcast(sId, { type: 'step:skip', kind: 'scriptVerify', issueId, reason: `craft verify unavailable: ${(err?.message || err).toString().slice(0, 200)}` });+ return {};+ }+ const blocking = issues.filter((i) => i.severity === 'high');+ broadcast(sId, { type: 'verify:round', scope: 'script', issueId, round: 1, findings: issues.length, blocking: blocking.length });+ if (blocking.length) {+ await fileGap(record, sId, {+ gapKind: 'script-craft',+ issueId,+ summary: `Comic script craft review found ${blocking.length} blocking issue(s): ${blocking.map((b) => b.problem).join(' | ').slice(0, 600)}`,+ context: JSON.stringify(blocking).slice(0, 1000),+ });+ // #1572 — fileGap is advisory and only persists a gap task when fileGaps is+ // on (mirror its predicate). Tally what was actually FILED so the terminal+ // "complete" frame can qualify itself instead of silently reporting clean.+ if (record.options.fileGaps && record.mode === 'execute') {+ record.runState.scriptCraftGapIssues.add(issueId);+ record.runState.scriptCraftBlocking += blocking.length;+ }+ }+ return {};+}++export async function runEditorial(sId, record) {+ const maxRounds = Number.isInteger(record.options.maxEditorialRounds)+ ? record.options.maxEditorialRounds+ : MAX_EDITORIAL_ROUNDS;+ // maxRounds === 0 means "skip the editorial gate entirely" — which includes+ // the registry-driven editorial checks (the default info-dumping check is+ // LLM-backed, so a skip run must not spend budget on it). Mark both reviewed+ // so the resolver advances past editorialChecks too; the user can still run+ // checks on demand via the route.+ if (maxRounds === 0) {+ record.runState.editorialReviewed = true;+ // The reverse-outline refresh (#1349) only feeds the registry checks, so a run+ // that skips the whole editorial gate must skip it too — mark it refreshed so+ // the resolver advances past STEP 5.1 without spending budget.+ record.runState.reverseOutlineRefreshed = true;+ record.runState.editorialChecksReviewed = true;+ // Skipping the editorial gate also skips its health convergence check (#1316)+ // — the resolver must advance past editorialHealthGate too.+ record.runState.editorialHealthReady = true;+ return {};+ }+ let convergence = { best: null, sinceBest: 0 };+ for (let round = 1; round <= maxRounds; round += 1) {+ if (record.cancelRequested) return { canceled: true };+ const beforeAnalyze = await budgetPause();+ if (beforeAnalyze) return beforeAnalyze;+ const { issues, runId } = await analyzeManuscriptCompleteness(sId, {+ withEdits: true,+ ...providerOverrideOpts(record),+ });+ await recordDomainUsage('cos', { actions: 1 });+ const blocking = (issues || []).filter((i) => record.options.blockingSets.editorial.has(i.severity));+ broadcast(sId, {+ type: 'verify:round', scope: 'editorial', round, findings: (issues || []).length, blocking: blocking.length,+ });+ // Seed the manuscript-review comment set so the findings are visible in the+ // manuscript editor regardless of auto-fix outcome.+ await seedReviewFromFindings(sId, issues || [], { runId, mode: 'fresh' }).catch((err) => {+ console.log(`⚠️ autopilot: seed editorial review failed for ${sId.slice(0, 12)}: ${err.message}`);+ });+ if (blocking.length === 0) {+ record.runState.editorialReviewed = true;+ return {};+ }+ if (round === maxRounds) {+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('editorial', maxRounds, blocking.length), residual: blocking };+ }+ // Divergence guard (#1571): bail when the auto-fix passes stop reducing blocking findings.+ convergence = trackConvergence(convergence, blocking.length);+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('editorial', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };+ }+ // Bounded auto-fix: apply a fix for each open high-severity comment, then+ // the loop re-analyzes. Each fix is wrapped so one bad anchor doesn't abort+ // the pass (boundary use of try/catch — these call into LLM/file paths).+ const review = await getReview(sId).catch(() => ({ comments: [] }));+ const open = (review.comments || []).filter((c) => c.status === 'open' && record.options.blockingSets.editorial.has(c.severity));+ for (const comment of open) {+ if (record.cancelRequested) return { canceled: true };+ // Each generated fix is its own LLM call — gate AND bill per comment so a+ // multi-comment pass can't overspend or under-count the daily budget.+ const beforeFix = await budgetPause();+ if (beforeFix) return beforeFix;+ try {+ // Thread the run's provider/model override into fix GENERATION (an LLM+ // call) so it honors the same provider as the review — without this the+ // fix silently runs on the active/default provider (and its runtime+ // fallback), which diverges from the run's chosen model and, when the+ // default is rate-limited, degrades fixes onto a weak fallback. Accept+ // is a deterministic edit application (no LLM), so it needs no override.+ if (!comment.fix) await generateManuscriptFix(sId, { commentId: comment.id, ...providerOverrideOpts(record) });+ await acceptManuscriptFix(sId, { commentId: comment.id });+ await recordDomainUsage('cos', { actions: 1 });+ } catch (err) {+ console.log(`⚠️ autopilot: editorial fix ${comment.id} failed: ${(err?.message || err)}`);+ }+ }+ }+ return {};+}++// STEP 5.1 — refresh the reverse-outline scene segmentation (#1349) before the+// registry-driven editorial checks (5.2), so the scene-consuming checks read the+// current draft's scenes rather than a segmentation staled by this run's editorial+// edits. Two cheap pre-gates keep this from spending budget needlessly:+// 1. skip entirely when no enabled editorial check declares a reverse-outline+// source (mirrors the runner's own needsReverseOutline gate), and+// 2. skip when the stored outline is already fresh — using getReverseOutline's+// canonical `stale` flag, NOT a stale-check reimplemented here.+// Only when a regenerate will actually occur do we gate the daily budget and bill a+// cos action — the same shape as runEditorialChecksPass, which gates+bills only when+// an enabled LLM check will actually run. `force:false`+// is a belt-and-suspenders second guard against the stored outline going fresh+// between the pre-check and the call. Failures are advisory (logged), never block.++// #1575 — the per-run editorial-check subset (null = all enabled). Absent/empty+// is normalized to null so EVERY consumer (this reverse-outline gate, the budget+// plan, the checks run) resolves the identical set — otherwise a subset of checks+// that skip the outline could still trigger/bill the refresh keyed off the global+// enabled set, or the gate could bill against checks the run skips.+export const editorialSubsetIds = (options) =>+ Array.isArray(options?.editorialCheckIds) && options.editorialCheckIds.length+ ? options.editorialCheckIds+ : null;++export async function runReverseOutlineRefresh(sId, record) {+ if (record.cancelRequested) return { canceled: true };+ const settings = await getSettings();+ const checkIds = editorialSubsetIds(record.options);+ // Gate 1 — sources-only pre-filter: does any enabled check (narrowed to this+ // run's subset) even DECLARE the outline as a source? If not, nothing to do —+ // and a subset that skips outline-consuming checks must not pay for a refresh+ // those checks would have triggered.+ if (!enabledChecksConsumeReverseOutline(settings, checkIds)) {+ record.runState.reverseOutlineRefreshed = true;+ return {};+ }+ // Gate 2 — is the stored outline stale (or never generated against a draftable+ // manuscript)? `no-content` (nothing drafted) needs no outline; `none` (draftable+ // but never segmented) and a `complete`-but-`stale` outline both need a regen.+ const current = await getReverseOutline(sId).catch(() => null);+ const needsRegen = !!current+ && current.status !== 'no-content'+ && (current.status === 'none' || current.stale === true);+ if (!needsRegen) {+ record.runState.reverseOutlineRefreshed = true;+ return {};+ }+ // Gate 3 (#1614) — gate-aware consumption. A check that DECLARES the outline as+ // a source still won't run if its runtime gate declines for this series (e.g. a+ // canon-less roster). Evaluate each consumer's gate against the current outline+ // and skip the refresh when none would run. Gate on SCENE PRESENCE, not+ // `status`: the precondition is "there's scene content to evaluate gates+ // against" — a never-generated (`status:'none'`) or empty outline has none, so+ // we bootstrap the first generation unconditionally rather than chicken-and-egg+ // ourselves out of it. enabledChecksConsumeReverseOutline only trusts a+ // DECLINING gate that didn't read the outline (the refresh regenerates it, so+ // an outline-content gate's stale verdict can't be trusted and keeps the check+ // a consumer) — so a scoped run of only outline-gated checks still refreshes.+ if (Array.isArray(current.scenes) && current.scenes.length > 0) {+ const gateCtx = await buildReverseOutlineGateContext(sId, { outline: current }).catch(() => null);+ if (gateCtx && !enabledChecksConsumeReverseOutline(settings, checkIds, gateCtx)) {+ record.runState.reverseOutlineRefreshed = true;+ return {};+ }+ }+ // A regenerate WILL spend one LLM call — gate the budget and bill, like the+ // other LLM passes. Bridge autopilot cancellation into the stage's AbortSignal.+ const beforeRefresh = await budgetPause();+ if (beforeRefresh) return beforeRefresh;+ const signal = { get aborted() { return record.cancelRequested; } };+ const regen = (force) => generateReverseOutline(sId, { ...providerIdOpts(record), force, signal })+ .catch((err) => {+ console.log(`⚠️ autopilot: reverse-outline refresh failed for ${sId.slice(0, 12)}: ${err.message}`);+ return null;+ });+ let result = await regen(false);+ // Canceled mid-pass — don't bill, don't mark refreshed; let the loop unwind.+ if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };+ // (#1614) A `cached:true` result means the manuscript hash still matched the+ // stored outline at generate time. Re-confirm staleness against the LIVE+ // manuscript within this run: if a concurrent edit moved the manuscript again+ // after that cache check, the cached outline is now stale and the downstream+ // checks would read it — force exactly one regen so they don't.+ if (result?.cached === true) {+ const after = await getReverseOutline(sId).catch(() => null);+ if (after?.stale === true) {+ result = await regen(true);+ if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };+ }+ }+ // Bill ONLY when the call actually regenerated (an LLM run). A `cached` result+ // (outline still fresh in the race window) or a `no-content` series spent nothing.+ // No verify:round broadcast here — a refresh isn't a review round (it produces+ // scenes, not findings); the conductor's generic step:start/step:complete already+ // surface "Refreshing scene segmentation…" / "done" to the UI.+ if (result && result.cached !== true && result.status !== 'no-content') {+ await recordDomainUsage('cos', { actions: 1 });+ }+ record.runState.reverseOutlineRefreshed = true;+ return {};+}++// STEP 5.2 — run the registry-driven editorial checks once per run, seeding+// their findings into the same manuscript-review comment set. Only LLM-kind+// checks cost tokens, so gate the daily budget AND bill a cos action only when+// an enabled LLM check will actually run — a deterministic-only (or all-checks-+// disabled) run does cheap local work and must neither pause on an exhausted+// budget nor consume quota. Failures are surfaced (logged) but never block the+// run — editorial checks are advisory.+export async function runEditorialChecksPass(sId, record) {+ if (record.cancelRequested) return { canceled: true };+ const settings = await getSettings();+ // #1575 — narrow the pass + its budget gate to this run's subset (null = all+ // enabled). The gate (buildEditorialCheckPlan) and the run (runEditorialChecks)+ // must resolve the SAME set so billing and execution agree.+ const checkIds = editorialSubsetIds(record.options);+ const plan = await buildEditorialCheckPlan(sId, { checkIds, settings });+ const hasLlmCheck = plan.checks.some((c) => c.kind === 'llm');+ if (hasLlmCheck) {+ const beforeChecks = await budgetPause();+ if (beforeChecks) return beforeChecks;+ }+ // Bridge autopilot cancellation into the runner's cooperative AbortSignal so a+ // mid-pass /autopilot/cancel stops before the next check and skips seeding+ // (the runner re-checks `signal.aborted` after each check). A live getter+ // reflects `record.cancelRequested` without a separate controller to manage.+ const signal = { get aborted() { return record.cancelRequested; } };+ // #1578 — forward the runner's per-check check:start/check:complete frames up+ // the autopilot SSE stream (tagged scope:'editorialChecks' so the UI groups+ // them with the editorialChecks verify:round). Without this the only signal+ // during a long (issues × checks) pass is the single terminal verify:round+ // total — no per-check progress or severity breakdown.+ const onProgress = (event) => broadcast(sId, { ...event, scope: 'editorialChecks' });+ const result = await runEditorialChecks(sId, { ...providerOverrideOpts(record), checkIds, settings, signal, onProgress }).catch((err) => {+ console.log(`⚠️ autopilot: editorial checks failed for ${sId.slice(0, 12)}: ${err.message}`);+ return null;+ });+ // Canceled mid-pass — don't bill, don't mark the step reviewed; let the loop+ // unwind via its canceled branch.+ if (result?.canceled || record.cancelRequested) return { canceled: true };+ if (result) {+ if (hasLlmCheck) await recordDomainUsage('cos', { actions: 1 });+ // #1573 — a check whose run() threw is recorded in perCheck.error but the+ // pass otherwise looks clean. Surface the errored count + failing checkIds on+ // the round frame and accumulate them onto the run so the terminal summary+ // can flag a partial failure (no silent "complete").+ const { errored, erroredCheckIds } = summarizeCheckErrors(result.perCheck);+ erroredCheckIds.forEach((id) => record.runState.editorialCheckErroredIds.add(id));+ // #1613 — count the high-severity findings this pass surfaced. The round frame+ // previously hardcoded `blocking: 0`, which made a 50-high-finding pass look+ // "complete" — the misleading per-step signal the issue calls out. Report the+ // real high count so the step's `blocking` matches what it found, whether or+ // not the optional pause gate is armed.+ const highFindings = result.findings.filter((f) => f.severity === 'high');+ broadcast(sId, { type: 'verify:round', scope: 'editorialChecks', round: 1, findings: result.findings.length, blocking: highFindings.length, errored, erroredCheckIds });+ if (errored) {+ console.error(`❌ autopilot: ${errored} editorial check(s) errored — series=${sId.slice(0, 12)} ${erroredCheckIds.join(', ')}`);+ }+ // #1613 — optional gate: when armed (threshold > 0) and the pass surfaced at+ // least that many high findings, PAUSE for human review instead of silently+ // proceeding to the health gate. Off by default (threshold 0), so existing+ // runs are unchanged. Do NOT mark the step reviewed — a resume re-runs the+ // checks and reconciles (like the health gate), so once the human reduces the+ // high findings below the threshold (or lowers it) the run continues.+ const threshold = record.options.checkFindingsPauseThreshold || 0;+ if (threshold > 0 && highFindings.length >= threshold) {+ // Editorial findings already carry severity/location/problem (manuscriptReview+ // sanitizes them), so the residual uses the same shape as the other pauses;+ // keep checkId so the UI can link a residual back to the check that raised it.+ const residual = highFindings.map((f) => ({+ severity: f.severity, // already filtered to 'high' — carry it rather than re-asserting+ location: f.location || (f.checkId ? `check ${f.checkId}` : 'manuscript'),+ problem: f.problem || 'high-severity editorial finding',+ checkId: f.checkId,+ }));+ console.log(`🚦 editorial checks gate — series=${sId.slice(0, 12)} ${highFindings.length} high finding(s) ≥ threshold ${threshold}, pausing for review`);+ return {+ pause: true,+ pauseKind: 'checkFindings',+ reason: `Editorial checks surfaced ${highFindings.length} high-severity finding(s) (≥ threshold ${threshold}) — paused for review. Address them in the manuscript editor, or raise the editorial-check pause threshold above ${highFindings.length} (set it to 0 to disable) in Options and resume.`,+ residual,+ };+ }+ }+ record.runState.editorialChecksReviewed = true;+ return {};+}++// STEP 5.3 — editorial health convergence gate (#1316). A cheap, no-LLM gate:+// read the persisted review, compute the aggregate health under the configured+// readiness gate, and either mark the run clean (proceed to visuals) or PAUSE+// with the open blockers for human triage. This is the consolidated "ready"+// signal — distinct from the completeness loop's own per-round high-only gate —+// so a blocker the registry checks (5.2) surfaced after completeness converged+// still stops the run. No auto-fix here: the completeness loop already attempted+// fixes; remaining blockers need a human (or a re-run after edits).+export async function runEditorialHealthGate(sId, record) {+ if (record.cancelRequested) return { canceled: true };+ // The effective gate (per-run override → persisted setting → null) was resolved+ // and stamped onto record.options at start (#1580), mirroring the round bounds —+ // so the loop and the dry-run plan can't disagree on which gate applied. null+ // falls through to DEFAULT_READINESS_GATE inside computeHealth/openBlockers.+ const gate = record.options.readinessGate || undefined;+ // Do NOT swallow a getReview error into an empty review — that would fail OPEN+ // (the gate would pass on a corrupt/unreadable store and let the run proceed to+ // visuals without verifying health). Let it bubble to the coordinator's+ // top-level catch, which records a clean `error` terminal state.+ const review = await getReview(sId);+ const comments = review.comments || [];+ // Per-series severity-weight override (#1616) resolved + stamped at start, so+ // the health score the gate reads matches the live + persisted scores.+ const health = computeHealth(comments, gate, { weights: record.options.severityWeights });+ broadcast(sId, {+ type: 'verify:round', scope: 'editorialHealth', round: 1,+ findings: health.open, blocking: health.ready ? 0 : health.open, score: health.score,+ });+ if (health.ready) {+ record.runState.editorialHealthReady = true;+ return {};+ }+ // Not clean — surface the open blockers (via the shared helper, so the residual+ // can't disagree with computeHealth's `ready` verdict) for the human triage.+ // No pauseKind (#1571): this is a single-pass gate, not a bounded verify→resolve+ // loop, so it has no maxRounds/divergence distinction — leave it null. If this+ // ever gains a retry loop, thread pauseKind through trackConvergence then.+ const blockers = openBlockers(comments, gate);+ // Surface the per-check / per-issue breakdown that drove the pause (#1579) —+ // a single emoji-prefixed line so "why did health reject my 50-issue series?"+ // is answerable from the logs, and the same breakdown on the marker so the UI+ // / resume banner can render it without re-hitting the health API.+ const healthBreakdown = summarizeEditorialBlockers(health);+ console.log(`🩺 editorial health gate not clean — series=${sId.slice(0, 12)} score=${health.score}, ${health.open} open: ${formatBlockerSummary(healthBreakdown)}`);+ return { pause: true, reason: `editorial health not clean (score ${health.score}, ${health.open} open finding(s))`, residual: blockers, healthBreakdown };+}diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsnew file mode 100644index 0000000000..4b70333166--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -0,0 +1,314 @@+/**+ * Series Autopilot — run orchestration (#2842 split of seriesAutopilot.js):+ * `startSeriesAutopilot` (the resolve → dispatch → broadcast loop) and the+ * boot-time recovery of runs interrupted by a restart.+ */++import { randomUUID } from 'crypto';+import { getDomainMode } from '../../../lib/domainAutonomy.js';+import { mergeSeverityWeights, resolveBlockingSet } from '../../../lib/editorial/index.js';+import { loadState } from '../../cosState.js';+import { getDomainBudgetStatus } from '../../domainUsage.js';+import { getSettings } from '../../settings.js';+import { getSeries, updateSeries } from '../series.js';+import { listIssues } from '../issues.js';+import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';+import { runs } from './state.js';+import {+ resolveAutopilotRounds, resolveAutopilotFoundationGate, resolveAutopilotFoundationThreshold,+ resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,+ resolveAutopilotProduceTeaser, resolveAutopilotRevision,+} from './config.js';+import { VISUAL_DRAFT_ENABLED, summarizePlanCost } from './convergence.js';+import { broadcast, persistMarker, clearPauseNotice, notifyPause, fileGap, scheduleCleanup } from './session.js';+import { resolveNextStep } from './stepResolver.js';+import { editorialSubsetIds } from './editorialSteps.js';+import { dispatchStep } from './dispatch.js';+import { buildDryRunPlan } from './dryRun.js';++// ---------------------------------------------------------------------------+// Public entrypoint.+// ---------------------------------------------------------------------------++/**+ * Start (or no-op resume of) the autopilot for a series. Returns immediately;+ * progress lands via SSE. When the cos domain is `off`, returns+ * `{ rejected:true, mode:'off' }` WITHOUT starting (route maps to 409).+ */+export async function startSeriesAutopilot(sId, options = {}) {+ const existing = runs.get(sId);+ if (existing && !existing.finished) {+ return { runId: existing.runId, alreadyRunning: true, mode: existing.mode };+ }++ const state = await loadState().catch(() => ({ config: {} }));+ const mode = getDomainMode(state.config, 'cos');+ if (mode === 'off') {+ return { rejected: true, mode: 'off' };+ }++ // Resolve the convergence-round bounds ONCE at start (per-run option →+ // persisted setting → default) and stamp them onto the run's options so the+ // synchronous loops, the dry-run plan, and a later resume all read the same+ // effective values. A resume reuses this same path, so a raised persisted+ // setting takes effect on the next Resume without re-specifying it.+ const settings = await getSettings().catch(() => null);+ // Per-series severity config (#1616): resolve the (possibly overridden) health+ // severity weights + the per-gate blocking-severity Sets ONCE at start and+ // stamp them onto run options, mirroring the round bounds / readiness gate —+ // so every gate read site + the health gate use the same resolved values, and+ // a resume re-reads them fresh. Loading the series here is cheap; a missing+ // series (deleted mid-run) falls through to the frozen defaults.+ const seriesRecord = await getSeries(sId).catch(() => null);+ const runOptions = {+ ...options,+ ...resolveAutopilotRounds(options, settings),+ foundationGate: resolveAutopilotFoundationGate(options, settings),+ foundationThreshold: resolveAutopilotFoundationThreshold(options, settings),+ readinessGate: resolveAutopilotReadinessGate(options, settings),+ checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),+ notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),+ produceTeaser: resolveAutopilotProduceTeaser(options, settings),+ ...resolveAutopilotRevision(options, settings),+ severityWeights: mergeSeverityWeights(seriesRecord?.severityWeights),+ blockingSets: {+ arc: resolveBlockingSet(seriesRecord?.blockingSeverities, 'arc'),+ beatContinuity: resolveBlockingSet(seriesRecord?.blockingSeverities, 'beatContinuity'),+ editorial: resolveBlockingSet(seriesRecord?.blockingSeverities, 'editorial'),+ },+ };++ if (existing) {+ // A finished run still in its replay window — evict it so this fresh run+ // fully replaces it (mirrors editorialAnalysisRunner).+ if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);+ for (const c of existing.clients) c.end();+ }++ const runId = randomUUID();+ const record = {+ runId,+ clients: [],+ lastPayload: null,+ cancelRequested: false,+ finished: false,+ cleanupTimer: null,+ startedAt: new Date().toISOString(),+ mode,+ options: runOptions,+ runState: {+ arcAttempted: false,+ arcVerified: false,+ // #2176 — foundation-quality gate satisfied this run (threshold cleared,+ // or the gate disabled/0-round). Boolean like arcVerified so the resolver+ // routes here at most once per run.+ foundationGated: false,+ beatContinuityChecked: false,+ editorialReviewed: false,+ reverseOutlineRefreshed: false,+ editorialChecksReviewed: false,+ editorialHealthReady: false,+ canonVerified: false,+ episodesAttempted: new Set(),+ beatsAttempted: new Set(),+ textAttempted: new Set(),+ scriptChecked: new Set(),+ visualDrafted: new Set(),+ // #2185 — issues whose optional teaser deliverable has been produced (or+ // attempted) this run, so the resolver can't re-loop into produceTeaser.+ teaserProduced: new Set(),+ // #1572 — issues whose ADVISORY craft gate filed a blocking gap task, and+ // the total blocking-finding count. Carried into the terminal `complete`+ // frame + persisted marker so a "clean complete" doesn't hide downstream+ // render blockers the user still has to resolve.+ scriptCraftGapIssues: new Set(),+ scriptCraftBlocking: 0,+ // #1573 — checkIds of editorial checks that threw during this run's checks+ // pass. Surfaced on the terminal `complete` frame + persisted marker so a+ // check that errors every run is visible instead of a silent "clean".+ editorialCheckErroredIds: new Set(),+ // #2171 — iterate-to-quality revision loop state (opt-in). `revisionCyclesRun`+ // is the completed-cycle count (the resolver's cursor); `revisionScoreHistory`+ // is the per-cycle mean series qualityScore the plateau detector reads;+ // `revisionConverged` latches true once a stop condition fires so the resolver+ // routes past the loop to canon/visuals.+ revisionCyclesRun: 0,+ revisionScoreHistory: [],+ revisionConverged: false,+ },+ activeChild: null,+ };+ runs.set(sId, record);++ // Fire-and-forget coordinator. The try/catch is the permitted boundary use —+ // an unhandled LLM rejection here would crash the process on Node ≥15.+ (async () => {+ try {+ // DRY-RUN: enumerate the plan, no side effects.+ if (mode === 'dry-run') {+ const series = await getSeries(sId);+ const issues = await listIssues({ seriesId: sId });+ // Resolve the enabled LLM-check count (#1576) so the plan's editorialChecks+ // step can estimate its issues × checks LLM fan-out. Mirrors the actual+ // pass: same subset (editorialSubsetIds) and same settings the checks read.+ const settings = await getSettings().catch(() => null);+ const checkPlan = await buildEditorialCheckPlan(sId, { checkIds: editorialSubsetIds(runOptions), settings }).catch(() => null);+ const editorialLlmCheckCount = checkPlan ? checkPlan.checks.filter((c) => c.kind === 'llm').length : undefined;+ const plan = buildDryRunPlan(series, issues, runOptions, { editorialLlmCheckCount });+ const planTotals = summarizePlanCost(plan);+ broadcast(sId, { type: 'start', runId, mode, target: series.targetFormat, plan, planTotals });+ // Carry the plan on the terminal frame too: a dry-run emits start ++ // complete synchronously, often before the client attaches, and+ // attachSseClient replays only the LAST frame — so the plan would be+ // lost if it lived solely on the start frame.+ broadcast(sId, { type: 'complete', runId, dryRun: true, steps: plan.length, plan, planTotals, completedAt: new Date().toISOString() });+ console.log(`🧭 autopilot dry-run — series=${sId.slice(0, 12)} steps=${plan.length} est≈${planTotals.estActions} action(s) ${planTotals.estLlmCalls} LLM call(s)`);+ return;+ }++ // EXECUTE.+ const series0 = await getSeries(sId);+ broadcast(sId, { type: 'start', runId, mode, target: series0.targetFormat });+ await persistMarker(sId, { status: 'running', runId, currentStep: null, residualFindings: [], lastError: null });+ // A resume is a fresh start: drop any stale pause banner up front so a run+ // that completes/errors without re-pausing doesn't leave a dead resume link.+ await clearPauseNotice(sId);+ if (runOptions.includeVisual && !VISUAL_DRAFT_ENABLED) {+ broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });+ }++ let ordinal = 0;+ while (!record.cancelRequested) {+ const series = await getSeries(sId);+ const issues = await listIssues({ seriesId: sId });+ const step = resolveNextStep(series, issues, record.runState, runOptions);++ if (step.kind === 'done') {+ // #1572 — qualify "complete" when the advisory craft gate filed+ // blocking script-craft gaps during this run: the run is done, but+ // those gaps still block downstream visual rendering, so report them+ // on both the persisted marker and the terminal frame.+ const craftGapIssues = record.runState.scriptCraftGapIssues.size;+ const craftGapFindings = record.runState.scriptCraftBlocking;+ // #1573 — qualify "complete" when an editorial check threw this run: the+ // run finished, but a check that errored produced no findings, so its+ // dimension was never actually evaluated. Persist the count + carry the+ // failing checkIds on the frame so the UI flags it instead of "clean".+ const editorialCheckErroredIds = [...record.runState.editorialCheckErroredIds];+ const editorialCheckErrors = editorialCheckErroredIds.length;+ await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors });+ broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, completedAt: new Date().toISOString() });+ console.log(`✅ autopilot complete — series=${sId.slice(0, 12)} steps=${ordinal}${craftGapIssues ? ` (${craftGapIssues} issue(s) with filed script-craft gaps)` : ''}${editorialCheckErrors ? ` (${editorialCheckErrors} editorial check(s) errored: ${editorialCheckErroredIds.join(', ')})` : ''}`);+ return;+ }++ // Budget gate (mirrors cosJobScheduler) — pause when today's cos action+ // budget is exhausted rather than burning past it. The editorialChecks+ // step is exempt from this blanket pre-dispatch gate because it+ // self-gates: runEditorialChecksPass only pauses/bills the budget when an+ // enabled LLM check will actually run (returning a pause result this loop+ // still handles), so a deterministic-only or all-disabled checks step can+ // complete a text-ready series even with the budget exhausted. The+ // editorialHealthGate (#1316) is likewise exempt — it's a pure read ++ // score with no LLM cost, so a budget-exhausted run can still produce its+ // readiness verdict (and pause on the findings, not the budget). The+ // reverseOutline refresh is exempt for the SAME reason as editorialChecks:+ // runReverseOutlineRefresh self-gates (it only calls budgetPause + bills+ // when it will actually regenerate), and it no-ops when no enabled check —+ // narrowed to this run's #1575 subset — consumes the outline. A blanket+ // pre-dispatch pause here would wrongly stall a deterministic-only subset+ // (whose refresh is a guaranteed no-op) on an exhausted budget. A gate+ // whose resolved rounds is 0 ("skip") is also exempt: runArcVerify /+ // runEditorial short-circuit with no LLM spend, so "0 skips the gate" must+ // hold even when the budget is exhausted (otherwise the run pauses on+ // budget instead of skipping).+ const zeroRoundSkip = (step.kind === 'verifyArc' && runOptions.maxArcVerifyRounds === 0)+ || (step.kind === 'beatContinuity' && runOptions.maxBeatContinuityRounds === 0)+ || (step.kind === 'editorialReview' && runOptions.maxEditorialRounds === 0)+ || (step.kind === 'foundationGate' && (runOptions.maxFoundationRounds === 0 || runOptions.foundationGate === false));+ const selfGatingStep = step.kind === 'editorialChecks'+ || step.kind === 'editorialHealthGate'+ || step.kind === 'reverseOutline';+ if (!selfGatingStep && !zeroRoundSkip) {+ const budget = await getDomainBudgetStatus('cos');+ if (!budget.withinBudget) {+ const budgetReason = `daily cos ${budget.exceeded} budget reached`;+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: budgetReason });+ broadcast(sId, { type: 'paused', runId, reason: budgetReason, completedAt: new Date().toISOString() });+ await notifyPause(record, sId, { reason: budgetReason, pauseKind: 'budget', currentStep: step.kind });+ console.log(`⏸️ autopilot paused (budget) — series=${sId.slice(0, 12)} after ${ordinal} steps`);+ return;+ }+ }++ ordinal += 1;+ await persistMarker(sId, { status: 'running', runId, currentStep: step.kind });+ broadcast(sId, { type: 'step:start', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal, reason: step.reason });++ const result = await dispatchStep(sId, step, record);++ if (result?.canceled || record.cancelRequested) break;+ if (result?.pause) {+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null });+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, completedAt: new Date().toISOString() });+ await notifyPause(record, sId, { reason: result.reason, pauseKind: result.pauseKind || null, currentStep: step.kind });+ // Only file the generic stalled task when the step didn't already file+ // a more specific gap (canon-undescribed, visual-no-pages, …) — else+ // fileGaps would create two CoS tasks for one underlying problem (the+ // differing gapKind defeats addTask's first-line dedup).+ if (!result.gapFiled) {+ await fileGap(record, sId, {+ gapKind: `${step.kind}-stalled`,+ issueId: step.issueId || null,+ summary: `Autopilot paused: ${result.reason}. Needs human review of the residual findings before it can continue.`,+ context: JSON.stringify(result.residual || []).slice(0, 1000),+ });+ }+ console.log(`⏸️ autopilot paused (${step.kind}) — series=${sId.slice(0, 12)}: ${result.reason}`);+ return;+ }+ broadcast(sId, { type: 'step:complete', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal });+ }++ // Cancelled.+ await persistMarker(sId, { status: 'paused', runId, currentStep: null, lastError: 'canceled by user' });+ broadcast(sId, { type: 'canceled', runId, steps: ordinal, completedAt: new Date().toISOString() });+ console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps`);+ } catch (err) {+ const message = (err?.message || String(err)).slice(0, 1000);+ console.error(`❌ autopilot failed — series=${sId.slice(0, 12)} ${message}`);+ await persistMarker(sId, { status: 'error', runId, lastError: message });+ broadcast(sId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });+ await fileGap(record, sId, {+ gapKind: 'run-error',+ summary: `The autonomous run failed and stopped: ${message}`,+ context: message,+ }).catch(() => {});+ } finally {+ record.finished = true;+ scheduleCleanup(sId, record);+ }+ })();++ return { runId, alreadyRunning: false, mode };+}++/**+ * Boot-time recovery: the in-memory run map is lost on restart, so any series+ * whose persisted marker still says `running` is demoted to `paused` (the user+ * can click Run to resume from the next missing step). Mirrors+ * recoverStuckAutoRuns in autoRunner.js. Best-effort; never blocks boot.+ */+export async function recoverStuckAutopilots() {+ const { listSeries } = await import('../series.js');+ const all = await listSeries().catch(() => []);+ const stuck = all.filter((s) => s.autopilot?.status === 'running');+ if (stuck.length === 0) return 0;+ for (const s of stuck) {+ await updateSeries(s.id, {+ autopilot: { ...s.autopilot, status: 'paused', lastError: 'interrupted by server restart', updatedAt: new Date().toISOString() },+ }).catch(() => null);+ }+ console.log(`📝 autopilot: recovered ${stuck.length} stuck run${stuck.length === 1 ? '' : 's'} on boot`);+ return stuck.length;+}diff --git a/server/services/pipeline/seriesAutopilot/revisionSteps.js b/server/services/pipeline/seriesAutopilot/revisionSteps.jsnew file mode 100644index 0000000000..0be595fbf2--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/revisionSteps.js@@ -0,0 +1,257 @@+/**+ * Series Autopilot — judging & revision steps (#2842 split of seriesAutopilot.js):+ * the quality-score rollup, the per-issue judge fan-out, the adversarial-cuts+ * pass and the bounded revision cycle.+ */++import { randomUUID } from 'crypto';+import { recordDomainUsage } from '../../domainUsage.js';+import { getSettings } from '../../settings.js';+import { listIssues, getIssue, updateStageWithLatest } from '../issues.js';+import { judgeIssue, getIssueJudge, getSeriesJudge } from '../pipelineJudge.js';+import { runEditorialChecks } from '../editorial/checkRunner.js';+import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';+import { applyCuts, filterSafeCutComments } from '../applyCuts.js';+import { eligibleIssues, getComparativeRank } from '../editorial/comparativeRank.js';+import { buildRevisionBrief } from '../editorial/revisionBrief.js';+import { evaluateRevisionStop, decideKeepRevert } from '../editorial/revisionStop.js';+import { broadcast, budgetPause, providerOverrideOpts } from './session.js';++// Mean of the judged issues' composite qualityScore (null when nothing judged).+export function meanQualityScore(seriesJudge) {+ const vals = (seriesJudge?.scores || [])+ .filter((s) => s.judged && Number.isFinite(Number(s.qualityScore)))+ .map((s) => Number(s.qualityScore));+ if (vals.length === 0) return null;+ return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 100) / 100;+}++// Judge every drafted (eligible) issue that needs it — an unjudged or stale+// snapshot. Staleness is read from the persisted snapshots (getSeriesJudge, no+// LLM), so a fresh issue is skipped WITHOUT even a cache-reuse call and, crucially,+// the budget is gated BEFORE a fresh judge spends — never after. Each real judge+// bills one cos action. Returns a pause result when the budget is exhausted with+// judging still to do, a cancel result, or null on completion.+async function judgeAllEligible(sId, record, issues) {+ const eligible = eligibleIssues(issues);+ const { providerOverride, modelOverride } = record.options;+ const pre = await getSeriesJudge(sId, { issues });+ const scoreById = new Map((pre.scores || []).map((s) => [s.issueId, s]));+ for (const issue of eligible) {+ if (record.cancelRequested) return { canceled: true };+ const score = scoreById.get(issue.id);+ const needsJudge = !score || !score.judged || score.stale;+ if (!needsJudge) continue; // already judged against the current content — free.+ // A fresh judge WILL spend an LLM call — gate the budget first, then bill.+ const gate = await budgetPause();+ if (gate) return gate;+ const snap = await judgeIssue(issue.id, { providerId: providerOverride, model: modelOverride }).catch((err) => {+ console.log(`⚠️ revision: judge failed for issue ${issue.id.slice(0, 12)}: ${err.message}`);+ return null;+ });+ if (snap && !snap.cached && snap.status === 'complete') {+ await recordDomainUsage('cos', { actions: 1 });+ }+ }+ return null;+}++// Run the adversarial-cuts editorial check for the series, seed the findings into+// the manuscript-review comment set, and return the freshly-seeded safe-cut+// comments (OVER-EXPLAIN + REDUNDANT). Force-enables the check for this pass so a+// user who disabled it globally still gets the loop's mechanical revision. One+// billed LLM pass; returns { safeComments } or a { pause }/{ canceled } result.+async function runAdversarialCuts(sId, record) {+ const before = await budgetPause();+ if (before) return before;+ const settings = await getSettings().catch(() => null);+ // Overlay a force-enable for the cut check so a globally-disabled check still+ // runs inside the consented revision loop (never mutates persisted settings).+ const merged = {+ ...(settings || {}),+ pipelineEditorialChecks: {+ ...(settings?.pipelineEditorialChecks || {}),+ checks: {+ ...(settings?.pipelineEditorialChecks?.checks || {}),+ 'prose.adversarial-cuts': {+ ...(settings?.pipelineEditorialChecks?.checks?.['prose.adversarial-cuts'] || {}),+ enabled: true,+ },+ },+ },+ };+ const signal = { get aborted() { return record.cancelRequested; } };+ const result = await runEditorialChecks(sId, {+ checkIds: ['prose.adversarial-cuts'],+ settings: merged,+ signal,+ ...providerOverrideOpts(record),+ }).catch((err) => {+ console.log(`⚠️ revision: adversarial cuts failed for ${sId.slice(0, 12)}: ${err.message}`);+ return null;+ });+ if (record.cancelRequested) return { canceled: true };+ if (!result || result.canceled) return { safeComments: [] };+ await recordDomainUsage('cos', { actions: 1 });+ await seedReviewFromFindings(sId, result.findings || [], { runId: result.runId, mode: 'merge' }).catch((err) => {+ console.log(`⚠️ revision: seed cut findings failed for ${sId.slice(0, 12)}: ${err.message}`);+ });+ const review = await getReview(sId).catch(() => ({ comments: [] }));+ return { safeComments: filterSafeCutComments(review.comments || []) };+}++// One iterate-to-quality revision cycle (CWQE Phase 7, #2171). Composes the+// judge (#2167), adversarial cuts (#2168), and — when a fresh ranking exists —+// the comparative Elo (#2169) to revise the WEAKEST drafted issue under a+// keep/revert score gate, then evaluates the stop conditions. Every LLM call is+// budget-gated + billed exactly like the other steps; a budget-exhausted cycle+// returns a pause the coordinator handles. Never routes here in dry-run (dispatch+// only runs in execute mode).+export async function runRevisionCycle(sId, record) {+ if (record.cancelRequested) return { canceled: true };+ const issues0 = await listIssues({ seriesId: sId });+ if (eligibleIssues(issues0).length === 0) {+ // Nothing drafted to revise — converge so the resolver moves on.+ record.runState.revisionConverged = true;+ broadcast(sId, { type: 'revision:converged', reason: 'no-content', cycle: record.runState.revisionCyclesRun || 0 });+ return {};+ }++ // 1. Judge every eligible issue (cache-aware) → baseline mean + weakest.+ const judged = await judgeAllEligible(sId, record, issues0);+ if (judged?.canceled) return { canceled: true };+ if (judged?.pause) return judged;++ const seriesJudge = await getSeriesJudge(sId, { issues: issues0 });+ const preMean = meanQualityScore(seriesJudge);++ // 2. Pick the weakest issue — Elo ranking when a FRESH one exists (#2169),+ // else the judge's weakest-first (lowest qualityScore).+ let weakestId = null;+ const rank = await getComparativeRank(sId).catch(() => null);+ if (rank?.status === 'complete' && !rank.stale && Array.isArray(rank.weakest) && rank.weakest[0]) {+ weakestId = rank.weakest[0].issueId;+ }+ if (!weakestId) weakestId = seriesJudge.weakest?.[0]?.issueId || null;+ if (!weakestId) {+ record.runState.revisionConverged = true;+ broadcast(sId, { type: 'revision:converged', reason: 'no-weakest', cycle: record.runState.revisionCyclesRun || 0 });+ return {};+ }++ const preWeakest = seriesJudge.scores.find((s) => s.issueId === weakestId);+ const preScore = preWeakest?.qualityScore ?? null;+ const stageId = preWeakest?.stageId || 'prose';++ // 3. Adversarial cuts (series-wide seed) + collect this issue's safe cuts.+ const cuts = await runAdversarialCuts(sId, record);+ if (cuts?.canceled) return { canceled: true };+ if (cuts?.pause) return cuts;+ const issueSafeCuts = (cuts.safeComments || []).filter((c) => c.issueId === weakestId);++ // Capture the weakest issue's pre-revision stage state for the keep/revert gate+ // (existing runHistory snapshotting handles the version event; we hold the exact+ // text so a revert can restore it through the serialized write path — never a+ // force over a concurrent human edit).+ const preIssue = await getIssue(weakestId).catch(() => null);+ const preStage = preIssue?.stages?.[stageId] || {};+ const preState = { input: preStage.input || '', output: preStage.output || '', lastRunId: preStage.lastRunId || null };+ // The full judge snapshot for the brief — a persisted-snapshot read (no LLM+ // spend); judgeAllEligible above already judged this issue this cycle.+ const weakestJudge = await getIssueJudge(weakestId).catch(() => null);++ // 4. Build the revision brief (pure) and broadcast it as the revision plan.+ const brief = buildRevisionBrief({+ issue: { number: preIssue?.number, title: preIssue?.title },+ judge: weakestJudge && weakestJudge.status === 'complete' ? weakestJudge : (preWeakest || {}),+ cutComments: issueSafeCuts,+ currentChars: (preState.output || '').length || null,+ });+ broadcast(sId, { type: 'revision:brief', issueId: weakestId, cycle: (record.runState.revisionCyclesRun || 0) + 1, cuts: issueSafeCuts.length, brief: brief.slice(0, 2000) });++ // 5. Apply — mechanical safe cuts are the revision (autonovel: "the cuts ARE the+ // plan"). applyCuts writes through the serialized stage path with a runHistory+ // snapshot for undo. No safe cuts ⇒ nothing to apply this cycle.+ let applied = 0;+ if (issueSafeCuts.length > 0) {+ const cutResult = await applyCuts(sId, issueSafeCuts, { safeTypesOnly: true }).catch((err) => {+ console.log(`⚠️ revision: applyCuts failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);+ return { applied: 0, sections: [] };+ });+ applied = cutResult.applied || 0;+ }++ // 6. Keep/revert gate — re-judge the revised issue; keep only if the composite+ // qualityScore did not regress, else restore the pre-revision text.+ let decision = 'keep';+ let postScore = preScore;+ if (applied > 0) {+ const postIssue = await getIssue(weakestId).catch(() => null);+ const appliedOutput = postIssue?.stages?.[stageId]?.output || '';+ const before = await budgetPause();+ if (before) return before;+ const reJudge = await judgeIssue(weakestId, { stageId, force: true, providerId: record.options.providerOverride, model: record.options.modelOverride }).catch((err) => {+ console.log(`⚠️ revision: re-judge failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);+ return null;+ });+ if (reJudge && reJudge.status === 'complete') await recordDomainUsage('cos', { actions: 1 });+ postScore = reJudge?.status === 'complete' ? reJudge.qualityScore : preScore;+ decision = decideKeepRevert(preScore, postScore);+ if (decision === 'revert') {+ // Restore through the serialized path, guarded so a concurrent human edit is+ // never clobbered: revert ONLY when the stage still holds the cut output we+ // produced. A `revert-` runId marks this as a fresh version event.+ await updateStageWithLatest(weakestId, stageId, (cur) => {+ if ((cur?.output || '') !== appliedOutput) return {};+ return { status: 'edited', input: preState.input, output: preState.output, lastRunId: `revert-${randomUUID()}`, errorMessage: '' };+ }).catch((err) => {+ console.log(`⚠️ revision: revert failed for issue ${weakestId.slice(0, 12)}: ${err.message}`);+ });+ // Re-judge the restored text so the persisted snapshot matches what's on+ // disk (else it lingers pinned to the rejected cut version). Budget-gated ++ // billed like every other judge; skipped (snapshot stays stale — the next+ // cycle re-judges it) when the budget is spent.+ const beforeRevertJudge = await budgetPause();+ if (!beforeRevertJudge) {+ const rj = await judgeIssue(weakestId, { stageId, force: true, providerId: record.options.providerOverride, model: record.options.modelOverride }).catch(() => null);+ if (rj && rj.status === 'complete') await recordDomainUsage('cos', { actions: 1 });+ }+ }+ }++ // 7. Record the cycle: post-cycle mean drives the plateau detector; the ledger+ // line is the experiment log (single emoji line per the CLAUDE.md convention).+ record.runState.revisionCyclesRun = (record.runState.revisionCyclesRun || 0) + 1;+ const postSeriesJudge = await getSeriesJudge(sId, { issues: await listIssues({ seriesId: sId }) });+ const postMean = meanQualityScore(postSeriesJudge);+ if (Number.isFinite(postMean)) record.runState.revisionScoreHistory.push(postMean);+ console.log(`🔁 revision cycle ${record.runState.revisionCyclesRun} — series=${sId.slice(0, 12)} issue=${preIssue?.number ?? weakestId} pre=${preScore ?? '?'} post=${postScore ?? '?'} → ${decision} (applied ${applied} cut(s), mean ${preMean ?? '?'}→${postMean ?? '?'})`);++ // 8. Stop conditions — plateau / hedged-convergence / maxCycles. The residual+ // finding texts come from the weakest issue's judge (verdict + revisions):+ // the reviewer will ALWAYS find something, so the stop is about qualification,+ // not zero defects.+ const findingTexts = [+ postSeriesJudge.scores.find((s) => s.issueId === weakestId)?.oneLineVerdict || '',+ ...((weakestJudge?.topRevisions) || []),+ ].filter(Boolean);+ const stop = evaluateRevisionStop({+ cyclesRun: record.runState.revisionCyclesRun,+ minCycles: record.options.revisionMinCycles,+ maxCycles: record.options.revisionMaxCycles,+ scoreHistory: record.runState.revisionScoreHistory,+ plateauDelta: record.options.revisionPlateauDelta,+ findingTexts,+ });+ broadcast(sId, {+ type: 'revision:cycle', cycle: record.runState.revisionCyclesRun, issueId: weakestId,+ preScore, postScore, decision, applied, preMean, postMean,+ converged: stop.stop, stopReason: stop.reason,+ });+ if (stop.stop) {+ record.runState.revisionConverged = true;+ broadcast(sId, { type: 'revision:converged', reason: stop.reason, detail: stop.detail, cycle: record.runState.revisionCyclesRun });+ console.log(`✅ revision converged (${stop.reason}) — series=${sId.slice(0, 12)}: ${stop.detail}`);+ }+ return {};+}diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsnew file mode 100644index 0000000000..47ccbc4ff2--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -0,0 +1,183 @@+/**+ * Series Autopilot — run session plumbing (#2842 split of seriesAutopilot.js):+ * SSE client attach/broadcast, cancellation, cleanup, the persisted run marker,+ * CoS gap filing, pause notifications, provider option shaping and the budget gate.+ */++import { attachSseClient, broadcastSse, SSE_CLEANUP_DELAY_MS } from '../../../lib/sseUtils.js';+import * as cosTaskStore from '../../cosTaskStore.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';+import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../../notifications.js';+import { getSeries, updateSeries } from '../series.js';+import * as volumeBeatsRunner from '../volumeBeatsRunner.js';+import * as autoRunner from '../autoRunner.js';+import { runs, autopilotEvents } from './state.js';++// ---------------------------------------------------------------------------+// Run registry helpers (mirror editorialAnalysisRunner.js).+// ---------------------------------------------------------------------------++export function isAutopilotActive(seriesId) {+ const run = runs.get(seriesId);+ return !!run && !run.finished;+}++export function attachClient(seriesId, res) {+ return attachSseClient(runs, seriesId, res);+}++export function cancelSeriesAutopilot(seriesId) {+ const run = runs.get(seriesId);+ if (!run || run.finished) return false;+ run.cancelRequested = true;+ // Emit an immediate acknowledgement frame so the UI can switch to a+ // "cancelling…" state right away. Cancellation is cooperative and checked+ // between steps (the terminal `canceled` frame follows once the active+ // step/LLM call returns) — without this ack the user sees no feedback until+ // the loop unwinds, which can be the length of a long in-flight LLM call (#1617).+ broadcastSse(run, { type: 'cancel:acknowledged', runId: run.runId, requestedAt: new Date().toISOString() });+ // Propagate to the currently-delegated child so cancel is responsive+ // mid-step instead of only between steps.+ const child = run.activeChild;+ if (child?.kind === 'beats') volumeBeatsRunner.cancelVolumeBeatsRun(child.id);+ else if (child?.kind === 'text') autoRunner.cancelAutoRun(child.id);+ return true;+}++export function broadcast(seriesId, payload) {+ const run = runs.get(seriesId);+ if (!run) return;+ broadcastSse(run, payload);+ // Mirror every frame onto the in-process bus (CDO Phase 3, #2185) so a+ // server-side consumer (CD plan step) sees the same progress/pause/terminal+ // frames as an SSE client. Emit is best-effort — a listener throw must never+ // abort the run (this runs inside the fire-and-forget coordinator).+ try {+ autopilotEvents.emit(seriesId, payload);+ } catch (err) {+ console.log(`⚠️ autopilot: event emit failed for ${seriesId.slice(0, 12)}: ${err.message}`);+ }+}++export function scheduleCleanup(seriesId, record) {+ record.cleanupTimer = setTimeout(() => {+ if (runs.get(seriesId) !== record) return;+ for (const c of record.clients) c.end();+ runs.delete(seriesId);+ }, SSE_CLEANUP_DELAY_MS);+}++// Thin persisted marker for resume/paused UI + boot recovery. NOT a step+// cursor — see module header. Best-effort; a marker write must never abort a run.+export async function persistMarker(seriesId, patch) {+ await updateSeries(seriesId, {+ autopilot: { ...patch, updatedAt: new Date().toISOString() },+ }).catch((err) => {+ console.log(`⚠️ autopilot: marker write failed for ${seriesId.slice(0, 12)}: ${err.message}`);+ });+}++// File a CoS task for a capability/quality gap the autopilot can't resolve on+// its own (a script that won't parse, a render that keeps failing, a stalled+// verify, a run-ending error). Opt-in via `options.fileGaps`; never fires in+// dry-run. The first description line is kept STABLE per (series, gapKind,+// issue) so cosTaskStore.addTask's pending/in_progress dedup collapses repeats+// instead of spamming a task per page / per run. Best-effort — a task-store+// failure must never abort the autopilot.+export async function fileGap(record, sId, { gapKind, issueId = null, summary, context = '' }) {+ if (!record.options.fileGaps || record.mode !== 'execute') return;+ const idTag = `series ${sId}${issueId ? ` issue ${issueId}` : ''}`;+ const description = `Autopilot ${gapKind} gap — ${idTag}\n\n${summary}`;+ const result = await cosTaskStore.addTask({ description, context, app: 'pipeline' }, 'user')+ .catch((err) => { console.log(`⚠️ autopilot: fileGap (${gapKind}) failed: ${err.message}`); return null; });+ if (result && !result.duplicate) {+ broadcast(sId, { type: 'gap:filed', gapKind, issueId, taskId: result.id });+ }+}++// Pause escalation (#1615): post an in-app notification when a run pauses so the+// user is told actively, not only when they happen to open the status page. The+// SSE `paused` frame still fires for an attached client; this is the persistent+// out-of-band signal for a user who isn't watching. Opt-out via+// `options.notifyOnPause` / the persisted setting (default on); never fires in+// dry-run. Prior pause notifications for this series are cleared first so a+// resume→pause cycle leaves exactly one current banner instead of a stack, and+// the metadata field is series-scoped so removeByMetadata can't touch unrelated+// notifications. Best-effort — a notification failure must never abort the run.+// Drop any pause banner for this series. Called before posting a fresh one (so a+// resume→pause cycle leaves exactly one) AND when a new execute run starts (so a+// run resumed from a pause that then completes/errors doesn't leave a stale+// "paused" banner + dead resume link). Series-scoped metadata so it can't touch+// unrelated notifications. Best-effort.+export async function clearPauseNotice(sId) {+ await removeByMetadata('autopilotPauseSeriesId', sId).catch(() => {});+}++export async function notifyPause(record, sId, { reason, pauseKind = null, currentStep = null }) {+ if (record.options.notifyOnPause === false || record.mode !== 'execute') return;+ const series = await getSeries(sId).catch(() => null);+ const seriesName = series?.name || 'a series';+ await clearPauseNotice(sId);+ await addNotification({+ type: NOTIFICATION_TYPES.AUTOPILOT_PAUSED,+ title: `Autopilot paused — ${seriesName}`,+ description: reason || 'The run paused and needs human review before it can continue.',+ priority: PRIORITY_LEVELS.HIGH,+ link: `/pipeline/series/${sId}`,+ metadata: { autopilotPauseSeriesId: sId, runId: record.runId, pauseKind, currentStep },+ }).catch((err) => { console.log(`⚠️ autopilot: pause notification failed for ${sId.slice(0, 12)}: ${err.message}`); });+}++// Series Autopilot threads BOTH its run provider AND its run model as SOFT+// defaults, NOT hard overrides — so a deliberate per-stage pin (Prompts page /+// stage-config.json) still wins for that stage, matching what verifyComicScript+// already does (#1514 for provider; #1558 for model). Each run-level value lands+// on stageRunner's soft channel (`providerDefault` tier 3 / `modelDefault`): it+// applies only to UNPINNED stages and soft-falls-through (to the active provider+// / the provider's default model) when unavailable, rather than throwing+// PROVIDER_OVERRIDE_UNAVAILABLE or beating a stage's deliberate pin the way a+// hard override would. For the model dimension "unpinned" means a stage carrying+// only a *tier* value (default/quick/coding/heavy) — the run model overrides the+// tier but still loses to a deliberate explicit-model pin (see+// stageRunner.resolveModelHint). Before #1558 the model was threaded as a hard+// `modelOverride`, which let the run model beat even an explicit stage pin.+//+// Two shapes because the delegated services disagree on field names: the+// arc/episode/verify passes take `providerDefault`/`modelDefault`; the child+// runners (volumeBeatsRunner, autoRunner) and the `providerId`-style services+// take `providerIdDefault`/`modelIdDefault`. Each maps its incoming defaults to+// stageRunner's `providerDefault`/`modelDefault` at the leaf call while keeping+// its existing hard `providerOverride`/`providerId` + `modelOverride`/`model`+// params untouched for manual route callers.+export const providerOverrideOpts = (record) => ({+ providerDefault: record.options.providerOverride,+ modelDefault: record.options.modelOverride,+});+export const providerIdOpts = (record) => ({+ providerIdDefault: record.options.providerOverride,+ modelIdDefault: record.options.modelOverride,+ // Multi-candidate draft gate (#2169): bill one cos action per re-roll and stop+ // re-rolling when the daily budget is spent. Only ever invoked by+ // generateStage's runDraftGate on a judgeable stage with draftAttempts > 1 — a+ // no-op for every other stage/run. Check-then-bill so a skipped (budget-out)+ // attempt isn't charged. Returns false to halt further attempts (keep the best+ // so far); true when the attempt may proceed.+ chargeAction: async () => {+ const budget = await getDomainBudgetStatus('cos');+ if (!budget.withinBudget) return false;+ await recordDomainUsage('cos', { actions: 1 });+ return true;+ },+});++// Pause result when the cos action budget is exhausted, else null. Used to gate+// EACH billable call inside the multi-call verify/editorial convergence loops —+// the conductor's per-step budget check only fires once before the step, so+// without this a single step could bill several actions past the daily cap.+// gapFiled:true so a budget pause doesn't also file a generic stalled gap+// (mirrors the conductor's own loop-level budget pause, which files none).+export async function budgetPause() {+ const budget = await getDomainBudgetStatus('cos');+ if (budget.withinBudget) return null;+ return { pause: true, gapFiled: true, reason: `daily cos ${budget.exceeded || 'actions'} budget reached` };+}diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.jsnew file mode 100644index 0000000000..0c57b53037--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/state.js@@ -0,0 +1,30 @@+/**+ * Series Autopilot — in-process run registry & progress bus (#2842 split of+ * seriesAutopilot.js). The single owner of the `runs` map every other module+ * reads through, plus the server-side event tap and its terminal frame types.+ */++import { EventEmitter } from 'events';++// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished,+// cleanupTimer, startedAt, mode, options, runState, activeChild }>+export const runs = new Map();++// In-process progress bus (CDO Phase 3, #2185). Every SSE frame the run+// broadcasts to attached HTTP clients is ALSO emitted here keyed by seriesId, so+// a SERVER-SIDE consumer — the Creative Director plan-advance loop running an+// autopilot as one plan step — can observe progress/pause/terminal frames+// without opening an HTTP/SSE client. SSE behavior is unchanged; this is a+// parallel tap, not a replacement. Listeners are per-seriesId and short-lived+// (attached for the life of one plan step), but a busy install could run several+// concurrently, so lift the default 10-listener cap to avoid a spurious leak+// warning. The payloads are the exact SSE frames (they carry `type`).+export const autopilotEvents = new EventEmitter();+autopilotEvents.setMaxListeners(0);++// The frame `type`s that mean the run reached a terminal/paused state — a+// server-side consumer settles its plan step on any of these. `complete` (or a+// dry-run `complete`), `paused` (convergence/budget/child pause), `canceled`+// (user stop), and `error` (run-ending throw) are exhaustive of the run's exit+// frames (see the fire-and-forget coordinator in startSeriesAutopilot).+export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled', 'error']);diff --git a/server/services/pipeline/seriesAutopilot/stepResolver.js b/server/services/pipeline/seriesAutopilot/stepResolver.jsnew file mode 100644index 0000000000..9576d0d73d--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/stepResolver.js@@ -0,0 +1,303 @@+/**+ * Series Autopilot — deterministic step resolution (#2842 split of+ * seriesAutopilot.js). Pure: given the series, its issues and the run state,+ * decides the single next step. No I/O, so it is exhaustively unit-testable.+ */++import { parseComicScript } from '../../../lib/comicScriptParser.js';+import { isStageReady } from '../issues.js';+import { compareIssuesByPosition } from '../arcPlanner.js';+import { wantsTeaser, wantsVisual } from './config.js';+import { VISUAL_DRAFT_ENABLED } from './convergence.js';++// ---------------------------------------------------------------------------+// Pure next-step resolver — the heart of the conductor (no I/O; unit-tested).+// ---------------------------------------------------------------------------++const setHas = (s, v) => (s instanceof Set ? s.has(v) : Array.isArray(s) ? s.includes(v) : false);++export const byNumber = (a, b) => (a?.number ?? 9999) - (b?.number ?? 9999);++// The script stages a series must have drafted to be "story-ready", derived+// from its targetFormat. prose is the intermediate source the scripts adapt+// from — we gate on the final scripts so a script-first import (prose empty,+// script authored) is already considered ready and never regenerated.+export function requiredScriptStages(series, options = {}) {+ const fmt = series?.targetFormat || 'comic+tv';+ // Per-run format restriction: a multi-format (comic+tv) series can be driven+ // to just one format's scripts in a single autopilot run — e.g. "produce the+ // comic draft only, skip the 24 teleplays." `options.targetFormats` is a+ // subset of ['comic','tv']; absent/empty means "all formats the series wants".+ const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length+ ? options.targetFormats+ : null;+ const wantComic = fmt.includes('comic') && (!restrict || restrict.includes('comic'));+ const wantTv = fmt.includes('tv') && (!restrict || restrict.includes('tv'));+ const stages = [];+ if (wantComic) stages.push('comicScript');+ if (wantTv) stages.push('teleplay');+ // Never strand the run with zero required script stages (which would mark every+ // issue text-ready with no script authored). If the restriction excludes+ // everything this series supports, ignore it and fall back to the series' own+ // formats.+ if (stages.length === 0) return requiredScriptStages(series);+ return stages;+}++export function isComicTarget(series) {+ return (series?.targetFormat || 'comic+tv').includes('comic');+}++// Does THIS run want the comic format? `isComicTarget` alone keys off the+// series' declared format, but a per-run `options.targetFormats` restriction can+// scope a comic+tv series to TV only — in which case the comic-only steps+// (scriptVerify, visual draft) must NOT run, or a TV-only pass would enter+// comic-script verification with no comicScript and pause on an unparseable+// script. Mirrors the restriction logic in requiredScriptStages: an empty/absent+// restriction (or one that excludes everything the series supports) means "all+// formats the series wants", so this stays true for the default whole-series run.+export function wantsComic(series, options = {}) {+ if (!isComicTarget(series)) return false;+ const restrict = Array.isArray(options?.targetFormats) && options.targetFormats.length+ ? options.targetFormats+ : null;+ if (!restrict) return true;+ // If the restriction excludes every format the series supports, requiredScriptStages+ // ignores it (never strand the run) — match that here so the gates agree.+ const wantComic = restrict.includes('comic');+ const wantTv = restrict.includes('tv') && (series?.targetFormat || '').includes('tv');+ if (!wantComic && !wantTv) return true; // restriction is a no-op → whole series+ return wantComic;+}+++export function orderedIssues(issues) {+ return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesByPosition);+}++export function textReady(issue, series, options = {}) {+ return requiredScriptStages(series, options).every((stageId) => isStageReady(issue.stages?.[stageId]));+}++// An issue "has beats" once its idea stage carries expanded beat text+// (idea.output) — the unit the whole-manuscript beat-continuity pass (#1510)+// reads. isStageReady(idea) is exactly that: status ready/edited AND non-empty+// output.+export function issueHasBeats(issue) {+ return isStageReady(issue?.stages?.idea);+}++// Structural script gate (pure): does the comic script parse into >=1 page with+// >=1 panel? Cheap, no LLM — this is the Phase-1 "verify the scripts work".+export function scriptStructurallyReady(issue) {+ const output = issue.stages?.comicScript?.output || '';+ if (!output.trim()) return false;+ const { pages } = parseComicScript(output);+ if (!Array.isArray(pages) || pages.length === 0) return false;+ return pages.some((p) => Array.isArray(p.panels) && p.panels.length > 0);+}++// A render slot counts as "enqueued" once it carries a jobId or a stamped+// filename (proof or final). Draft rendering only kicks off proof renders, but+// we accept either so a re-run never re-renders a slot the user already+// finalized manually.+// Include the legacy pre-proof/final fields (`imageJobId`/`filename`) the+// sanitizer still preserves on upgraded projects — otherwise an+// already-rendered legacy slot reads as un-enqueued and gets re-rendered.+export const slotEnqueued = (slot) => !!(+ slot && (slot.proofImage?.jobId || slot.proofImage?.filename+ || slot.finalImage?.jobId || slot.finalImage?.filename+ || slot.imageJobId || slot.filename)+);+export const pageEnqueued = (page) => !!(+ page && (page.proofImage?.jobId || page.proofImage?.filename+ || page.finalImage?.jobId || page.finalImage?.filename+ || page.imageJobId || page.filename)+);++/**+ * Has an issue's comic art been drafted? True once pages exist, the front cover+ * is enqueued, any authored back cover is enqueued, and every page that HAS+ * panels is enqueued. Pages with no panels can't be rendered, so they don't+ * block readiness.+ */+export function visualReady(issue) {+ const cp = issue.stages?.comicPages;+ const pages = Array.isArray(cp?.pages) ? cp.pages : [];+ if (pages.length === 0) return false;+ if (!slotEnqueued(cp?.cover)) return false;+ if (!slotEnqueued(cp?.backCover)) return false; // always drafted (renderer has a fallback)+ return pages.every((p) => (Array.isArray(p.panels) && p.panels.length > 0 ? pageEnqueued(p) : true));+}++/**+ * Return the first unmet step for a series given its canonical records and the+ * in-run accumulator (`runState`). Pure — caller supplies fresh state.+ *+ * runState fields consulted (all optional): arcVerified, editorialReviewed,+ * reverseOutlineRefreshed (booleans); beatsAttempted, textAttempted, scriptChecked (Set|array of ids).+ * The *attempted* sets stop a perpetually-failing step (an issue whose LLM run+ * keeps erroring) from looping forever — the conductor records an attempt even+ * on failure, so the resolver moves past it within one run.+ */+export function resolveNextStep(series, issues, runState = {}, options = {}) {+ const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];+ const ordered = orderedIssues(issues);++ // STEP 1 — arc. Also (re)generate when there are no seasons at all: an+ // arc-only series (arc text present, seasons: []) has nothing for the+ // episode/issue steps to expand, and would otherwise sail through verify/+ // review of an empty issue list and be marked done with no volumes. The+ // attempted-guard stops a re-loop if arc generation yields no seasons (the+ // dispatch pauses in that case).+ const noArc = !series?.arc?.logline && !series?.arc?.summary;+ if (!runState.arcAttempted && (noArc || seasons.length === 0)) {+ return { kind: 'generateArc', reason: seasons.length === 0 && !noArc ? 'series has no volumes' : 'series has no arc' };+ }++ // STEP 2 — a season with zero issues (in season order). Skip volumes already+ // attempted this run so an empty episode generation can't re-loop (the+ // dispatch pauses when it produces no issues).+ for (const season of seasons) {+ if (setHas(runState.episodesAttempted, season.id)) continue;+ const inSeason = ordered.filter((i) => i.seasonId === season.id);+ if (inSeason.length === 0) {+ return { kind: 'generateEpisodes', seasonId: season.id, reason: `volume ${season.number ?? '?'} has no issues` };+ }+ }++ // STEP 3 — arc verification (once per run; bounded loop happens in dispatch).+ if (!runState.arcVerified) {+ return { kind: 'verifyArc', reason: 'arc not yet verified this run' };+ }++ // STEP 3.5 — foundation-quality gate (#2176). After the arc/volumes exist and+ // arc structure is verified, judge the whole foundation (world / characters /+ // arc) BEFORE the expensive beat/text stages and iterate on the weakest+ // dimension until it clears the threshold. Once per run (bounded loop happens+ // in dispatch). Gated on `foundationGate` being enabled AND a non-zero round+ // budget — a disabled/0-round gate is treated as already satisfied so the+ // resolver falls straight through to beats (the dispatch never runs).+ if (!runState.foundationGated+ && options.foundationGate !== false+ && options.maxFoundationRounds !== 0) {+ return { kind: 'foundationGate', reason: 'foundation not yet judged this run' };+ }++ // STEP 4a — per-volume beat sheets (skip volumes already attempted this run).+ for (const season of seasons) {+ if (setHas(runState.beatsAttempted, season.id)) continue;+ const inSeason = ordered.filter((i) => i.seasonId === season.id);+ if (inSeason.some((i) => !isStageReady(i.stages?.idea))) {+ return { kind: 'beatSheet', seasonId: season.id, reason: `beats missing in volume ${season.number ?? '?'}` };+ }+ }++ // STEP 4a.5 — whole-manuscript beat continuity (#1510). Once every volume's+ // beats exist (the 4a loop above is exhausted), run ONE cross-issue beat-level+ // pass BEFORE the expensive text/script generation — catching dropped+ // cliffhangers, finale drift, unlanded through-lines, and duplicated "firsts"+ // at the cheap beat altitude instead of after 24 full scripts exist. Only+ // meaningful when at least one issue actually carries beats; a synopsis-only+ // run has nothing beat-level to check (and would just duplicate arc verify),+ // so it's skipped without ever marking the gate.+ if (!runState.beatContinuityChecked && ordered.some(issueHasBeats)) {+ return { kind: 'beatContinuity', reason: 'whole-manuscript beat continuity not yet checked this run' };+ }++ // STEP 4b — per-issue text stages (prose + required scripts).+ for (const issue of ordered) {+ if (setHas(runState.textAttempted, issue.id)) continue;+ if (!textReady(issue, series, options)) {+ return { kind: 'textStages', issueId: issue.id, reason: 'prose / scripts not ready' };+ }+ }++ // STEP 4c — structural script gate (comic targets only). Gate on wantsComic,+ // not bare isComicTarget, so a TV-only run of a comic+tv series doesn't enter+ // comic-script verification with no comicScript (which would pause on an+ // unparseable script).+ if (wantsComic(series, options)) {+ for (const issue of ordered) {+ if (setHas(runState.scriptChecked, issue.id)) continue;+ return { kind: 'scriptVerify', issueId: issue.id, reason: 'comic script not yet structurally verified' };+ }+ }++ // STEP 5 — series-level editorial review via the manuscript editor (once).+ if (!runState.editorialReviewed) {+ return { kind: 'editorialReview', reason: 'editorial review not yet run this run' };+ }++ // STEP 5.1 — refresh the reverse-outline scene segmentation (#1349). Runs AFTER+ // the editorial completeness pass (STEP 5, which may edit the manuscript) and+ // BEFORE the registry checks (5.2) so the scene-consuming checks read fresh+ // scenes. The handler self-gates: a no-op (no budget) when no enabled check+ // reads the outline or the stored outline is already fresh.+ if (!runState.reverseOutlineRefreshed) {+ return { kind: 'reverseOutline', reason: 'reverse-outline segmentation not yet refreshed this run' };+ }++ // STEP 5.2 — registry-driven editorial checks (#1284). Runs the enabled+ // editorial checks once per run and seeds their findings into the same+ // manuscript-review comment set. A no-op when no checks are enabled.+ if (!runState.editorialChecksReviewed) {+ return { kind: 'editorialChecks', reason: 'editorial checks not yet run this run' };+ }++ // STEP 5.3 — editorial health convergence gate (#1316). After BOTH editorial+ // passes have seeded their findings, read the aggregate "ready" signal (no open+ // findings above the configured readiness gate). The completeness loop only+ // gates on its OWN high findings; the registry checks (5.2) can surface fresh+ // blockers after it converged, so this final gate reconciles the whole review+ // before visuals. Pauses with the residual blockers when not clean.+ if (!runState.editorialHealthReady) {+ return { kind: 'editorialHealthGate', reason: 'editorial health not yet confirmed clean this run' };+ }++ // STEP 5.4 — iterate-to-quality revision loop (CWQE Phase 7, #2171). Opt-in.+ // Runs AFTER the editorial health gate is clean (so the manuscript is+ // structurally sound) and BEFORE canon/visuals — each cycle judges every+ // drafted issue, revises the weakest through adversarial cuts under a+ // keep/revert score gate, and stops on plateau / hedged-convergence / maxCycles.+ // Pure-function-of-state like every other step: cycle counters + convergence+ // live in runState (revisionCyclesRun / revisionConverged), so a resume picks up+ // mid-loop with no stored cursor. `revisionConverged` is set by the dispatch+ // once a stop condition fires; until then we route back here while cycles remain.+ if (options.revisionEnabled+ && !runState.revisionConverged+ && (runState.revisionCyclesRun || 0) < (options.revisionMaxCycles ?? 1)) {+ return { kind: 'revisionCycle', reason: `iterate-to-quality revision cycle ${(runState.revisionCyclesRun || 0) + 1}` };+ }++ // STEP 5.5 — canon descriptive integrity. Before ANY visual production, every+ // canon noun that appears where it'd be drawn must be described (an artist+ // can't render a name). Runs once per run; the gate blocks (pauses) on+ // undescribed drawn nouns. Only relevant when visuals will be produced.+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options) && !runState.canonVerified) {+ return { kind: 'canonVerify', reason: 'canon descriptive integrity not yet verified this run' };+ }++ // STEP 6 — draft visuals (cover + back + all interior pages).+ if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {+ for (const issue of ordered) {+ if (setHas(runState.visualDrafted, issue.id)) continue;+ if (visualReady(issue)) continue;+ return { kind: 'visualDraft', issueId: issue.id, reason: 'comic pages not yet drafted' };+ }+ }++ // STEP 7 — teaser video deliverable (CDO Phase 3, #2185, opt-in, default off).+ // After every issue is text-ready + drafted, OPTIONALLY mint + start a Creative+ // Director video project seeded from each issue. Gated on wantsTeaser (which+ // itself requires visuals). Attempted-once per issue this run so a started (or+ // failed) teaser can't re-loop the resolver back here.+ if (VISUAL_DRAFT_ENABLED && wantsTeaser(options) && wantsComic(series, options)) {+ for (const issue of ordered) {+ if (setHas(runState.teaserProduced, issue.id)) continue;+ return { kind: 'produceTeaser', issueId: issue.id, reason: 'teaser video not yet produced' };+ }+ }++ return { kind: 'done' };+}diff --git a/server/services/pipeline/seriesAutopilot/visualSteps.js b/server/services/pipeline/seriesAutopilot/visualSteps.jsnew file mode 100644index 0000000000..e48bf330e1--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/visualSteps.js@@ -0,0 +1,230 @@+/**+ * Series Autopilot — visual + canon steps (#2842 split of seriesAutopilot.js):+ * cover/page draft enqueueing, the visual-draft wait loop, the canon-readiness+ * verification gate and the teaser production step.+ */++import { buildRenderSlot } from '../../../lib/renderSlot.js';+import { parseComicScript } from '../../../lib/comicScriptParser.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';+import { getIssue, updateStageWithLatest } from '../issues.js';+import { slotKeyForVariant } from '../owners.js';+import { enqueueComicCover, enqueueComicBackCover, enqueueVisualComicPage } from '../visualStages.js';+import { checkSeriesCanonReadiness } from '../canonReadiness.js';+import { broadcast, fileGap, providerOverrideOpts } from './session.js';+import { slotEnqueued, pageEnqueued, visualReady } from './stepResolver.js';++// Turn a render-enqueue result into the { slotKey, slot } pair the render+// routes persist (proof → proofImage, final → finalImage).+const slotFromRenderResult = (result) => {+ const slotKey = slotKeyForVariant(result.variant);+ return { slotKey, slot: buildRenderSlot({ slotKey, jobId: result.jobId, prompt: result.prompt, fromProof: result.fromProof }) };+};++// Persist an in-flight render slot the way the render routes do: enqueue the+// proof render, then splice the returned jobId onto the freshest persisted+// cover/backCover slot via updateStageWithLatest.+async function enqueueCoverDraft(issueId, slotField, enqueueFn) {+ const { slotKey, slot } = slotFromRenderResult(await enqueueFn(issueId, { target: 'proof' }));+ await updateStageWithLatest(issueId, 'comicPages', (current) => {+ const currentSlot = current?.[slotField] || {};+ return { [slotField]: { ...currentSlot, [slotKey]: slot } };+ });+}++async function enqueuePageDraft(issueId, pageIndex) {+ const { slotKey, slot } = slotFromRenderResult(await enqueueVisualComicPage(issueId, { pageIndex, target: 'proof' }));+ await updateStageWithLatest(issueId, 'comicPages', (current) => {+ const pages = Array.isArray(current?.pages) ? current.pages : [];+ if (!pages[pageIndex]) return {};+ const next = [...pages];+ next[pageIndex] = { ...pages[pageIndex], [slotKey]: slot };+ return { status: 'edited', pages: next };+ });+}++export async function runVisualDraft(sId, issueId, record) {+ let issue = await getIssue(issueId);+ let cp = issue.stages?.comicPages;++ // Respect an explicit lock — the user froze this stage, so don't seed pages+ // or render. Skip (intentional, not a gap) and mark drafted so we don't loop.+ if (cp?.locked === true) {+ broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, reason: 'comicPages stage is locked — skipping draft render' });+ record.runState.visualDrafted.add(issueId);+ return {};+ }++ // 1. Seed pages + cover concepts from the comic script if not already done+ // (mirrors the extract-pages route; pure parse, no LLM).+ if (!(Array.isArray(cp?.pages) && cp.pages.length > 0)) {+ const source = (issue.stages?.comicScript?.output || '').trim();+ if (source) {+ const { pages, coverConcept, backCoverConcept } = parseComicScript(source);+ await updateStageWithLatest(issueId, 'comicPages', (current) => {+ const coverScript = current?.cover?.script || '';+ const backScript = current?.backCover?.script || '';+ return {+ status: pages.length ? 'ready' : 'empty',+ pages,+ cover: coverConcept && !coverScript ? { script: coverConcept, imageJobId: null, prompt: null } : (current?.cover ?? null),+ backCover: backCoverConcept && !backScript ? { script: backCoverConcept, imageJobId: null, prompt: null } : (current?.backCover ?? null),+ errorMessage: '',+ };+ });+ issue = await getIssue(issueId);+ cp = issue.stages?.comicPages;+ }+ }++ const pageCount = Array.isArray(cp?.pages) ? cp.pages.length : 0;+ if (pageCount === 0) {+ // Nothing to draw — the comic script never parsed into pages. This is a real+ // production blocker, so pause for review rather than marking the issue done.+ await fileGap(record, sId, {+ gapKind: 'visual-no-pages',+ issueId,+ summary: 'Cannot draft comic art — the comic script did not parse into any pages. Fix the comicScript stage (PAGE/PANEL structure) first.',+ context: `issueId=${issueId}`,+ });+ return { pause: true, gapFiled: true, reason: `issue ${issue.number ?? issueId} has no comic pages to render — the script did not parse`, residual: [{ severity: 'high', location: `issue ${issue.number ?? '?'} / comicPages`, problem: 'comic script did not parse into pages' }] };+ }++ // Budget-gate + bill each render individually — a comic is many GPU jobs.+ // A failed enqueue (e.g. a page with no panels) is surfaced and skipped.+ const enqueueOne = async (target, fn) => {+ const budget = await getDomainBudgetStatus('cos');+ if (!budget.withinBudget) return { pause: true, reason: `daily cos ${budget.exceeded} budget reached` };+ try {+ await fn();+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(sId, { type: 'render:queued', issueId, target });+ } catch (err) {+ const reason = (err?.message || String(err)).slice(0, 200);+ broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, target, reason });+ // Dedups to one task per issue (idTag has no target), so a broken page+ // doesn't file a task per page.+ await fileGap(record, sId, {+ gapKind: 'render-failed',+ issueId,+ summary: `A draft render failed for this issue (first failure: ${target} — ${reason}). The comic page/panel structure may be incomplete.`,+ context: `issueId=${issueId} target=${target}`,+ });+ }+ return {};+ };++ // 2. Front cover.+ if (!slotEnqueued(cp?.cover)) {+ const r = await enqueueOne('cover', () => enqueueCoverDraft(issueId, 'cover', enqueueComicCover));+ if (r.pause) return r;+ }+ // 3. Back cover — always queue it (like the front cover); the back-cover+ // renderer has a fallback prompt when no concept script is set, so a+ // "complete" draft shouldn't silently omit it.+ issue = await getIssue(issueId);+ cp = issue.stages?.comicPages;+ if (!slotEnqueued(cp?.backCover)) {+ const r = await enqueueOne('backCover', () => enqueueCoverDraft(issueId, 'backCover', enqueueComicBackCover));+ if (r.pause) return r;+ }+ // 4. Every interior page (re-read per page so each splice merges fresh state).+ for (let i = 0; i < pageCount; i += 1) {+ if (record.cancelRequested) return { canceled: true };+ const fresh = await getIssue(issueId);+ const page = fresh.stages?.comicPages?.pages?.[i];+ if (!page || !Array.isArray(page.panels) || page.panels.length === 0) continue;+ if (pageEnqueued(page)) continue;+ const r = await enqueueOne(`page ${i + 1}`, () => enqueuePageDraft(issueId, i));+ if (r.pause) return r;+ }+ // Only consider the issue drafted once every drawable slot is actually+ // enqueued. If a render errored (e.g. an un-renderable page), visualReady is+ // still false — mark it attempted so the resolver doesn't re-loop, but pause+ // for review instead of letting the run report a complete draft.+ const after = await getIssue(issueId);+ if (!visualReady(after)) {+ record.runState.visualDrafted.add(issueId);+ await fileGap(record, sId, {+ gapKind: 'visual-incomplete',+ issueId,+ summary: `Issue ${after.number ?? issueId} could not be fully drafted — some cover/page renders did not enqueue (likely an un-renderable page or missing panels). Review the comic page/panel structure.`,+ context: `issueId=${issueId}`,+ });+ return {+ pause: true,+ gapFiled: true,+ reason: `issue ${after.number ?? issueId} could not be fully drafted — some cover/page renders did not enqueue`,+ residual: [{ severity: 'high', location: `issue ${after.number ?? '?'} / comicPages`, problem: 'not every drawable cover/page render was enqueued (likely an un-renderable page or missing panels)' }],+ };+ }+ record.runState.visualDrafted.add(issueId);+ return {};+}++// Canon descriptive-integrity gate — deterministic (no LLM), so not billable.+// Pauses for human review when a canon noun that appears in the visual source+// has no description (it can't be drawn). Marks canonVerified when clean so the+// run proceeds to visual drafting.+export async function runCanonVerify(sId, record) {+ const report = await checkSeriesCanonReadiness(sId);+ broadcast(sId, {+ type: 'verify:round', scope: 'canon', round: 1,+ findings: report.undescribed.length, blocking: report.undescribed.length,+ });+ if (report.ready) {+ record.runState.canonVerified = true;+ return {};+ }+ const residual = report.undescribed.map((n) => ({+ severity: 'high',+ location: `${n.kind} "${n.name}"`,+ problem: 'Appears where it would be drawn but has no description — can\'t be rendered.',+ }));+ await fileGap(record, sId, {+ gapKind: 'canon-undescribed',+ summary: `${report.undescribed.length} canon noun(s) appear in panels/scenes with no description: ${report.undescribed.map((n) => n.name).join(', ').slice(0, 400)}. Describe them on the Nouns stage before generating pages.`,+ context: JSON.stringify(report.undescribed).slice(0, 1000),+ });+ return {+ pause: true,+ reason: `${report.undescribed.length} canon noun(s) referenced in panels/scenes are undescribed — describe them before visual production`,+ residual,+ gapFiled: true,+ };+}++// Teaser deliverable (CDO Phase 3, #2185, opt-in). Mint + start a Creative+// Director video project seeded from this issue — the autopilot→CD direction of+// the bridge. Attempted-once per issue (marked up front so a failure can't+// re-loop the resolver). Bills one cos action like every other autopilot step+// (the CD project's own downstream render spend is gated by the creative/cos+// budget on its side). A teaser is an OPTIONAL, terminal-phase deliverable, so a+// failure is ADVISORY: it broadcasts a skip + files a gap, but does NOT pause the+// whole run (the story is already done — a failed trailer shouldn't strand it).+// bridgeFromIssue is imported dynamically to keep the pipeline↔creative-director+// module graph acyclic (it transitively pulls the CD plan loop + tool registry).+export async function runProduceTeaser(sId, issueId, record) {+ record.runState.teaserProduced.add(issueId);+ const issue = await getIssue(issueId).catch(() => null);+ try {+ const { produceVideoFromIssue } = await import('../../creativeDirector/bridgeFromIssue.js');+ // The treatment-from-prose LLM call runs through stageRunner's soft channel,+ // so thread the run's provider/model as providerDefault/modelDefault.+ const { project } = await produceVideoFromIssue(issueId, providerOverrideOpts(record));+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(sId, { type: 'teaser:produced', issueId, projectId: project?.id });+ console.log(`🎬 autopilot teaser — series=${sId.slice(0, 12)} issue=${issue?.number ?? issueId} → CD project ${project?.id?.slice(0, 8) ?? '?'}`);+ return {};+ } catch (err) {+ const message = (err?.message || String(err)).slice(0, 300);+ broadcast(sId, { type: 'step:skip', kind: 'produceTeaser', issueId, reason: `teaser production failed: ${message}` });+ await fileGap(record, sId, {+ gapKind: 'teaser-failed',+ issueId,+ summary: `The optional teaser video for issue ${issue?.number ?? issueId} could not be produced: ${message}. The story is complete — this deliverable can be retried from the Creative Director.`,+ context: `issueId=${issueId}`,+ });+ return {};+ }+}diff --git a/server/services/pipeline/seriesAutopilotBarrel.test.js b/server/services/pipeline/seriesAutopilotBarrel.test.jsnew file mode 100644index 0000000000..6ce4d100a3--- /dev/null+++ b/server/services/pipeline/seriesAutopilotBarrel.test.js@@ -0,0 +1,87 @@+import { describe, it, expect, vi } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';++// seriesAutopilot pulls in the pipeline + universe graph transitively; stub the+// peer fan-out the way the main autopilot suites do so this pure import-shape+// test stays hermetic.+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++const barrel = await import('./seriesAutopilot.js');++const HERE = dirname(fileURLToPath(import.meta.url));+const BARREL_SRC = readFileSync(join(HERE, 'seriesAutopilot.js'), 'utf8');+const MODULE_FILES = readdirSync(join(HERE, 'seriesAutopilot'))+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))+ .sort();++// Issue #2842 split the 2,541-line seriesAutopilot.js into ./seriesAutopilot/*+// with the original file kept as a re-exporting barrel (the same treatment+// #1152 gave arcPlanner.js). This pins that contract so the routes, the CDO+// plan-advance loop and the existing suites keep importing from one path.+describe('seriesAutopilot barrel re-exports (issue #2842)', () => {+ it('re-exports every module in ./seriesAutopilot/', () => {+ for (const f of MODULE_FILES) {+ expect(BARREL_SRC, `missing barrel re-export for seriesAutopilot/${f}`)+ .toContain(`'./seriesAutopilot/${f}'`);+ }+ });++ it.each(MODULE_FILES)('%s exports are reachable from the barrel as the same objects', async (f) => {+ const mod = await import(`./seriesAutopilot/${f}`);+ const keys = Object.keys(mod);+ expect(keys.length, `${f} exports nothing`).toBeGreaterThan(0);+ for (const key of keys) {+ expect(barrel[key], `barrel re-export of '${key}' (from ${f})`).toBe(mod[key]);+ }+ });++ it('no symbol collides across the split modules', async () => {+ const seen = new Map();+ const collisions = [];+ for (const f of MODULE_FILES) {+ const mod = await import(`./seriesAutopilot/${f}`);+ for (const key of Object.keys(mod)) {+ if (seen.has(key) && seen.get(key).value !== mod[key]) {+ collisions.push(`${key}: ${seen.get(key).file} vs ${f}`);+ } else if (!seen.has(key)) {+ seen.set(key, { file: f, value: mod[key] });+ }+ }+ }+ expect(collisions).toEqual([]);+ });++ it('keeps the public surface the routes + CDO loop depend on', () => {+ for (const fn of [+ 'startSeriesAutopilot', 'cancelSeriesAutopilot', 'isAutopilotActive',+ 'attachClient', 'recoverStuckAutopilots', 'resolveNextStep',+ 'requiredScriptStages', 'isComicTarget', 'wantsComic', 'wantsVisual',+ 'wantsTeaser', 'scriptStructurallyReady', 'visualReady', 'trackConvergence',+ 'resolveAutopilotRounds', 'resolveAutopilotFoundationGate',+ 'resolveAutopilotFoundationThreshold', 'resolveAutopilotReadinessGate',+ 'resolveAutopilotCheckPauseThreshold', 'resolveAutopilotNotifyOnPause',+ 'resolveAutopilotProduceTeaser', 'resolveAutopilotRevision',+ ]) {+ expect(typeof barrel[fn], fn).toBe('function');+ }+ for (const c of [+ 'autopilotEvents', 'AUTOPILOT_TERMINAL_TYPES', 'MAX_ARC_VERIFY_ROUNDS',+ 'MAX_EDITORIAL_ROUNDS', 'MAX_BEAT_CONTINUITY_ROUNDS', 'MAX_FOUNDATION_ROUNDS',+ 'MAX_CHILD_RETRIES', 'DIVERGENCE_PATIENCE', 'VISUAL_DRAFT_ENABLED',+ ]) {+ expect(barrel[c], c).toBeDefined();+ }+ });++ it('preserves the __testing internals bundle pulled from the split modules', () => {+ expect(Object.keys(barrel.__testing).sort()).toEqual([+ 'buildDryRunPlan', 'meanQualityScore', 'providerIdOpts', 'providerOverrideOpts',+ 'runs', 'summarizePlanCost',+ ]);+ expect(barrel.__testing.runs).toBeInstanceOf(Map);+ });+});