Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2171]): iterate-to-quality revision loop in Series Autopilot
Adam Eivy11594b43ff57
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 25ba60d59f..7e03410fa5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,6 +47,8 @@## Creative Writing Quality Engine+- **[issue-2171] Series Autopilot can now iterate a series to quality — an opt-in revision loop that revises the weakest issue under a keep/revert score gate and stops on plateau, hedged-convergence, or a cycle cap.** Autopilot used to cap editorial convergence at 2 rounds and then *pause* for a human, with craft findings advisory-only. A new opt-in `revisionCycle` step (off by default; enable + tune min/max cycles and the plateau delta in the Autopilot options drawer, persisted like the other gate settings) sits between the editorial-health gate and canon/visuals and cycles the manuscript toward publishable quality unattended. Each cycle: **(1)** judges every drafted issue (composing the Phase 3 judge #2167, cache-aware so only stale content bills), **(2)** picks the weakest issue — the Phase 5 Elo ranking (#2169) when a fresh one exists, else the lowest composite `qualityScore` — **(3)** runs the Phase 4 adversarial-cut pass (#2168) and auto-applies the safe cut types (OVER-EXPLAIN + REDUNDANT) through the snapshotted stage-write path, **(4)** builds a structured revision brief (PROBLEM / **WHAT TO KEEP** — the strongest sentences, so a rewrite can't gut the good material / WHAT TO CHANGE / VOICE RULES / TARGET) from the judge output + cut list, then **(5)** re-judges and applies a **keep/revert gate** — a revision is kept only when `qualityScore` did not regress, else the pre-revision text is restored through the serialized write path (never a force over a concurrent human edit). The loop stops on **plateau** (mean series score moves less than a configurable delta after a minimum cycle count), **maxCycles** (a cost ceiling, default 1–3), or **qualification-aware convergence** — remaining findings classified as hedged trade-offs ("individually fine", "deliberate choice", "costs of ambition") rather than actionable defects; majority-hedged ⇒ converged. Every judge/cut/re-judge call is budget-gated and billed against the cos daily action cap exactly like the existing steps, budget exhaustion pauses the run, and resume is a pure function of state (cycle counters live in run state, no stored cursor). Every keep/revert decision is logged as a single-line experiment-ledger entry. Pure brief-assembly and stop-condition/keep-revert logic are unit-tested. Gated on the already-consented Series Autopilot — never fires at boot (AI-provider policy). (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/editorial/revisionBrief.js`, `server/services/pipeline/editorial/revisionStop.js`, `server/lib/pipelineValidation.js`, `server/routes/pipeline/autopilot.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)+- **[issue-2169] Two comparative-quality mechanisms build on the calibrated judge — a multi-candidate draft gate, and head-to-head Elo ranking of a series' issues.** Both compose the Phase 3 judge (#2167) to escape autonovel's "rubric trap" (absolute 1-10 scores collapse into a 2-point band; comparison forces the discrimination the judge can't avoid). **(1) Multi-candidate draft gate** — a new opt-in per-stage config (`draftAttempts` 1–3, default **1 = off**; optional `draftGateThreshold`, schema parity added to `stageConfigUpdateSchema`) makes `generateStage` generate → judge → re-roll a FRESH draft while the composite `qualityScore` is below the threshold, up to the attempt cap, and keep the best-scoring attempt. Every attempt persists (rejected drafts stay recoverable in run history) and a per-attempt scorecard lands on `stage.draftGate` (`{ winner, threshold, attempts:[{ runId, qualityScore, rejected }] }`) — never silently discarded. Only the judgeable stages (prose/comicScript/teleplay) gate; the single-shot path is byte-for-byte unchanged when off. When run from Series Autopilot each re-roll bills one cos action and stops re-rolling when the daily budget is spent (keeping the best so far); a manual regenerate is never cos-billed. Canon extraction runs once, on the winning draft. **(2) Head-to-head Elo ranking** — a new `comparativeRank.js` + forced-pick `pipeline-judge-compare.md` stage prompt ("you are not allowed to call it a tie" — quote the deciding passage) runs a Swiss-style tournament (~4 rounds, K=32 Elo) across the series' drafted issues, each side truncated to a comparable budget via `contextBudget.js`. The ranking + per-match records persist at `data/pipeline-comparative-rank/{seriesId}.json`, content-hash-pinned for staleness (reuses `computeSourceContentHash`), with the weakest-N slice as the revision-priority order Phase 7 consumes. A tie/hedge/garbage pick from the judge falls through to a deterministic, balanced tiebreak. Surfaced as a new **Rankings** tab on the Reader Map page (`?tab=rank`) — an Elo table with the weakest issues flagged as revision priorities. Runs ONLY from the explicit "Rank issues" action or an autopilot step — never at boot (AI-provider policy). Pure Elo math + Swiss pairing + tie-refusal parsing + staleness are unit-tested. (`server/services/pipeline/editorial/comparativeRank.js`, `server/services/pipeline/textStages.js`, `server/services/pipeline/issues.js`, `server/services/pipeline/seriesAutopilot.js`, `server/lib/pipelineValidation.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-compare.md`, `client/src/components/pipeline/ComparativeRankView.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`, `client/src/services/apiPipeline.js`)- **[issue-2167] A calibrated LLM quality judge now scores each drafted issue, with a writer/judge model split — `qualityScore = judge overall − deterministic slop penalty`.** PortOS had severity findings and a deterministic health score but no LLM quality *score* per issue — the keep/revert currency Phases 5 and 7 need. A new harsh, calibrated judge (`server/services/pipeline/pipelineJudge.js`, stage prompt `pipeline-judge-issue.md`) scores a drafted issue across **9 dimensions** (voice adherence, beat coverage, character voice, plants seeded, prose quality, continuity, canon compliance, lore integration, engagement) against the SAME contract the writer received — style guide, beat sheet, and **full canon** (no reveal-gating, so it can catch canon/continuity/premature-reveal issues the writer's horizon-filtered view hides). An anti-inflation **calibration ladder** ("the median competent AI-generated chapter is a 6; a 10 does not exist for a draft; err lower") plus a **QUOTE TEST** (3 strongest / 3 weakest exact sentences) and a scene-vs-summary ratio keep the judge honest. The composite `qualityScore = judgeOverall − computeSlopPenalty(text)` (the deterministic slop penalty from #2165, clamped ≥ 0) is the dual immune system — the mechanical layer catches what the LLM judge normalizes away. **Writer/judge split:** a new `resolveJudgeForStage()` (sibling of `resolveProviderForStage()` in `server/lib/stageRunner.js`) resolves a per-writer-stage `judgeProvider`/`judgeModel` pin (schema parity: added to `stageConfigUpdateSchema`), defaulting to the writer's own provider but with the UI encouraging a *different*, harsher judge model to avoid self-congratulation. Scores persist per issue+stage at `data/pipeline-judge/{issueId}.json` with a `sourceContentHash` so a later edit flips the score to `stale` (mirrors `editorialAnalysis.js`), and the judge run itself lands in run history via `runStagedLLM` (a malformed-JSON response is retried once). Surfaced as a score chip + dimension/quote/revision breakdown on the issue page (`IssueJudgePanel`) and a weakest-first quality column on the series Editorial Roadmap. Runs ONLY from an explicit user action or the already-consented autopilot — never at boot. (`server/services/pipeline/pipelineJudge.js`, `server/lib/stageRunner.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-issue.md`, `client/src/components/pipeline/IssueJudgePanel.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`)diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex df80b8f9df..13a3d33ce5 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -31,6 +31,13 @@ const DEFAULT_CHECK_PAUSE_THRESHOLD = 0;// Pause-notification escalation (#1615) — mirror the server default (on). The one// autopilot setting that defaults ON: a zero-cost in-app banner when a run pauses.const DEFAULT_NOTIFY_ON_PAUSE = true;+// Iterate-to-quality revision loop (#2171) — mirror the server defaults. Off by+// default (a fresh burst of judge + cut LLM spend); cycles bound the cost and the+// plateau delta is the mean-score movement below which the series counts converged.+const DEFAULT_REVISION_ENABLED = false;+const DEFAULT_REVISION_MIN_CYCLES = 1;+const DEFAULT_REVISION_MAX_CYCLES = 2;+const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;// Editorial-health readiness gate (#1316/#1580) — the "manuscript clean" bar the// autopilot must clear before visuals. Mirrors READINESS_GATES on the server. The@@ -56,6 +63,15 @@ const clampNumber = (n, { fallback, min, max }) => {const clampRound = (n, fallback) => clampNumber(n, { fallback, min: ROUND_MIN, max: ROUND_MAX });// Pause threshold: blank → 0 (off), non-negative integer, no upper cap.const clampThreshold = (n) => clampNumber(n, { fallback: 0, min: 0, max: null });+// Revision cycles: at least 1 (0 would strand the loop), capped like the rounds.+const clampCycles = (n, fallback) => clampNumber(n, { fallback, min: 1, max: ROUND_MAX });+// Plateau delta: a float ≥ 0 (blank → the default). No rounding, unlike the gates.+const clampDelta = (n, fallback) => {+ if (n === '' || n === null || n === undefined) return fallback;+ const v = Number(n);+ if (!Number.isFinite(v)) return fallback;+ return Math.min(10, Math.max(0, v));+};// A single numeric field for the Options popover (round bounds + the pause// threshold). Allows '' mid-edit (so the field can be cleared) and clamps +@@ -64,7 +80,7 @@ const clampThreshold = (n) => clampNumber(n, { fallback: 0, min: 0, max: null })// fallback or mark the field dirty, or it would clobber a saved limit before// settings load and block the load from applying it. `max` caps the input (null =// uncapped); `clamp(value, defaultValue)` defaults to the round clamp.-function RoundInput({ id, label, settingKey, value, setValue, defaultValue, persist, max = ROUND_MAX, clamp = clampRound }) {+function RoundInput({ id, label, settingKey, value, setValue, defaultValue, persist, max = ROUND_MAX, clamp = clampRound, min = ROUND_MIN, step }) {const dirtyRef = useRef(false);return (<div className="flex items-center gap-2">@@ -72,8 +88,9 @@ function RoundInput({ id, label, settingKey, value, setValue, defaultValue, pers<inputid={id}type="number"- min={ROUND_MIN}+ min={min}max={max ?? undefined}+ step={step ?? undefined}value={value}onChange={(e) => { dirtyRef.current = true; setValue(e.target.value === '' ? '' : Number(e.target.value)); }}onBlur={() => {@@ -107,8 +124,10 @@ const STEP_LABELS = {reverseOutline: 'Refreshing scene segmentation',editorialChecks: 'Editorial checks',editorialHealthGate: 'Editorial health gate',+ revisionCycle: 'Iterate-to-quality revision',canonVerify: 'Checking canon descriptions',visualDraft: 'Drafting comic art',+ produceTeaser: 'Producing teaser video',};const stepLabel = (kind) => STEP_LABELS[kind] || kind;@@ -204,6 +223,12 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// default + per-run override) but defaults ON — toggling off silences the// in-app pause banner. Persisted on change so the choice is reused on Resume.const [notifyOnPause, setNotifyOnPause] = useState(DEFAULT_NOTIFY_ON_PAUSE);+ // Iterate-to-quality revision loop (#2171). Persisted like the other options+ // (saved default + per-run override) so a configured loop is reused on Resume.+ const [revisionEnabled, setRevisionEnabled] = useState(DEFAULT_REVISION_ENABLED);+ const [revisionMinCycles, setRevisionMinCycles] = useState(DEFAULT_REVISION_MIN_CYCLES);+ const [revisionMaxCycles, setRevisionMaxCycles] = useState(DEFAULT_REVISION_MAX_CYCLES);+ const [revisionPlateauDelta, setRevisionPlateauDelta] = useState(DEFAULT_REVISION_PLATEAU_DELTA);// Per-field dirty flags. Until a field is edited its input shows a display// default we must NOT persist (that would clobber a higher saved setting on// the untouched gate). Tracked per-field so editing one gate never discards@@ -214,6 +239,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst beatContinuityEditedRef = useRef(false);const checkPauseEditedRef = useRef(false);const notifyEditedRef = useRef(false);+ const revisionEnabledEditedRef = useRef(false);+ const revisionMinEditedRef = useRef(false);+ const revisionMaxEditedRef = useRef(false);+ const revisionDeltaEditedRef = useRef(false);const [canon, setCanon] = useState(null);const [canonLoading, setCanonLoading] = useState(false);@@ -233,6 +262,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateif (!beatContinuityEditedRef.current) setBeatContinuityRounds(Number.isInteger(pec.maxBeatContinuityRounds) ? pec.maxBeatContinuityRounds : DEFAULT_BEAT_CONTINUITY_ROUNDS);if (!checkPauseEditedRef.current) setCheckPauseThreshold(Number.isInteger(pec.checkFindingsPauseThreshold) ? pec.checkFindingsPauseThreshold : DEFAULT_CHECK_PAUSE_THRESHOLD);if (!notifyEditedRef.current) setNotifyOnPause(typeof pec.notifyOnPause === 'boolean' ? pec.notifyOnPause : DEFAULT_NOTIFY_ON_PAUSE);+ if (!revisionEnabledEditedRef.current) setRevisionEnabled(typeof pec.revisionEnabled === 'boolean' ? pec.revisionEnabled : DEFAULT_REVISION_ENABLED);+ if (!revisionMinEditedRef.current) setRevisionMinCycles(Number.isInteger(pec.revisionMinCycles) ? pec.revisionMinCycles : DEFAULT_REVISION_MIN_CYCLES);+ if (!revisionMaxEditedRef.current) setRevisionMaxCycles(Number.isInteger(pec.revisionMaxCycles) ? pec.revisionMaxCycles : DEFAULT_REVISION_MAX_CYCLES);+ if (!revisionDeltaEditedRef.current) setRevisionPlateauDelta(Number.isFinite(pec.revisionPlateauDelta) ? pec.revisionPlateauDelta : DEFAULT_REVISION_PLATEAU_DELTA);// Persisted readiness gate — display-only, drives the "saved default" label.setSavedGate(READINESS_GATE_LABELS[pec.readinessGate] ? pec.readinessGate : '');})@@ -268,6 +301,16 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdatesetNotifyOnPause(v);persistRounds({ notifyOnPause: v });}, [persistRounds]);+ // Revision loop (#2171): the enable checkbox persists immediately (no blur); the+ // cycle bounds + plateau delta persist on blur via RoundInput like the others.+ const editRevisionEnabled = useCallback((v) => {+ revisionEnabledEditedRef.current = true;+ setRevisionEnabled(v);+ persistRounds({ revisionEnabled: v });+ }, [persistRounds]);+ const editRevisionMinCycles = useCallback((v) => { revisionMinEditedRef.current = true; setRevisionMinCycles(v); }, []);+ const editRevisionMaxCycles = useCallback((v) => { revisionMaxEditedRef.current = true; setRevisionMaxCycles(v); }, []);+ const editRevisionPlateauDelta = useCallback((v) => { revisionDeltaEditedRef.current = true; setRevisionPlateauDelta(v); }, []);const { latest, frames } = usePipelineProgress(pipelineAutopilotSseUrl, [seriesId], { enabled: active });@@ -349,6 +392,11 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// #1615 — pause notification toggle persists + overrides like the others, but// is a plain boolean (no clamp). Untouched sends nothing → server default (on).if (notifyEditedRef.current) roundOverrides.notifyOnPause = notifyOnPause;+ // #2171 — the revision-loop knobs persist + override like the round inputs.+ if (revisionEnabledEditedRef.current) roundOverrides.revisionEnabled = revisionEnabled;+ if (revisionMinEditedRef.current) roundOverrides.revisionMinCycles = clampCycles(revisionMinCycles, DEFAULT_REVISION_MIN_CYCLES);+ if (revisionMaxEditedRef.current) roundOverrides.revisionMaxCycles = clampCycles(revisionMaxCycles, DEFAULT_REVISION_MAX_CYCLES);+ if (revisionDeltaEditedRef.current) roundOverrides.revisionPlateauDelta = clampDelta(revisionPlateauDelta, DEFAULT_REVISION_PLATEAU_DELTA);if (Object.keys(roundOverrides).length) await persistRounds(roundOverrides);// Per-run readiness-gate override (#1580): send it ONLY when the user picked a// specific gate. Unlike the round inputs we never persist it — '' leaves the@@ -364,7 +412,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// effect can reject a stale terminal frame from the previous run.activeRunIdRef.current = res.runId || null;setActive(true);- }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, readinessGate, persistRounds]);+ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, readinessGate, persistRounds]);const cancel = useCallback(async () => {await cancelPipelineAutopilot(seriesId).catch(() => null);@@ -513,6 +561,54 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate<p className="text-[11px] text-gray-500">When the editorial-checks pass surfaces this many High findings (or more), the run pauses for review instead of proceeding. 0 = off. Saved as the default and reused on Resume.</p>+ <label className="flex items-center gap-2 text-xs text-gray-300 pt-1 border-t border-port-border mt-1">+ <input type="checkbox" checked={revisionEnabled} onChange={(e) => editRevisionEnabled(e.target.checked)} />+ Iterate to quality (revise the weakest issue under a keep/revert score gate)+ </label>+ {revisionEnabled ? (+ <>+ <div className="flex flex-wrap gap-4 pt-1">+ <RoundInput+ id="autopilot-revision-min-cycles"+ label="Min cycles"+ settingKey="revisionMinCycles"+ value={revisionMinCycles}+ setValue={editRevisionMinCycles}+ defaultValue={DEFAULT_REVISION_MIN_CYCLES}+ persist={persistRounds}+ min={1}+ clamp={clampCycles}+ />+ <RoundInput+ id="autopilot-revision-max-cycles"+ label="Max cycles"+ settingKey="revisionMaxCycles"+ value={revisionMaxCycles}+ setValue={editRevisionMaxCycles}+ defaultValue={DEFAULT_REVISION_MAX_CYCLES}+ persist={persistRounds}+ min={1}+ clamp={clampCycles}+ />+ <RoundInput+ id="autopilot-revision-plateau-delta"+ label="Plateau Δ"+ settingKey="revisionPlateauDelta"+ value={revisionPlateauDelta}+ setValue={editRevisionPlateauDelta}+ defaultValue={DEFAULT_REVISION_PLATEAU_DELTA}+ persist={persistRounds}+ min={0}+ max={10}+ step={0.1}+ clamp={clampDelta}+ />+ </div>+ <p className="text-[11px] text-gray-500">+ After the editorial-health gate, judge every drafted issue and revise the weakest via adversarial cuts, keeping a change only when the quality score doesn't regress. Stops on plateau (mean score moves less than Δ), hedged-convergence, or max cycles. Fresh judge + cut LLM spend — saved as the default and reused on Resume.+ </p>+ </>+ ) : null}<p className="text-[11px] text-gray-500">Runs under the CoS auto-run autonomy domain. With it set to <em>dry-run</em>, this only previews the plan.</p>diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex f9473ebdf6..8d5cbeec17 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -218,6 +218,17 @@ export const pipelineEditorialChecksSettingsSchema = z.object({// (opt-in) — producing video is a fresh burst of LLM + render spend. Optional +// additive so older peers fall through to off.produceTeaser: z.boolean().optional(),+ // Iterate-to-quality revision loop (CWQE Phase 7, #2171). When on, the autopilot+ // cycles the weakest drafted issue through adversarial cuts + a judge-gated+ // keep/revert after the editorial-health gate, stopping on plateau /+ // hedged-convergence / maxCycles. Defaults OFF (opt-in) — a fresh burst of judge+ // + cut LLM spend. `revisionMaxCycles` is the cost ceiling; `revisionMinCycles`+ // floors the plateau/hedge stops; `revisionPlateauDelta` is the mean-score+ // movement below which the series counts as converged. All optional + additive.+ revisionEnabled: z.boolean().optional(),+ revisionMinCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),+ revisionMaxCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),+ revisionPlateauDelta: z.number().min(0).max(10).optional(),}).strict();// Cursor-context payload for the CD-bridge suggest route — identical shape todiff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex 4aba2a3509..bff75c376f 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -82,6 +82,18 @@ const autopilotStartSchema = z.object({// comic issue is drafted the run mints + starts a Creative Director teaser video// per issue. Falls back to pipelineEditorialChecks.produceTeaser, then off.produceTeaser: z.boolean().optional(),+ // Iterate-to-quality revision loop (CWQE Phase 7, #2171). When true, after the+ // editorial-health gate the run cycles the weakest drafted issue through+ // adversarial cuts + a judge-gated keep/revert, stopping on plateau /+ // hedged-convergence / maxCycles. Falls back to the persisted+ // pipelineEditorialChecks.revision* setting, then off. minCycles floors the+ // stops; maxCycles is the cost ceiling; plateauDelta is the score-movement+ // convergence threshold. Caps share MAX_CONVERGENCE_ROUNDS so a direct API call+ // can't request an absurd cycle budget.+ revisionEnabled: z.boolean().optional(),+ revisionMinCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),+ revisionMaxCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),+ revisionPlateauDelta: z.number().min(0).max(10).optional(),});router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {diff --git a/server/services/pipeline/editorial/revisionBrief.js b/server/services/pipeline/editorial/revisionBrief.jsnew file mode 100644index 0000000000..7f2ee5c009--- /dev/null+++ b/server/services/pipeline/editorial/revisionBrief.js@@ -0,0 +1,161 @@+/**+ * Pipeline — Revision brief assembly (CWQE Phase 7, #2171).+ *+ * Pure assembly of the revision BRIEF the Series Autopilot's iterate-to-quality+ * loop hands the reviser for the weakest issue. Autonovel's revision phase proved+ * that a rewrite prompt structured as PROBLEM / WHAT TO KEEP / WHAT TO CHANGE /+ * VOICE RULES / TARGET — with an explicit WHAT TO KEEP section carrying the+ * strongest sentences + protected passage — is what stops a rewrite from+ * destroying the good material while fixing the weak.+ *+ * The brief composes the evidence sources the earlier phases already produced:+ * - the calibrated judge snapshot (#2167): oneLineVerdict, per-dimension fixes,+ * strongest/weakest sentences, topRevisions;+ * - the adversarial-cut findings (#2168) grouped by cut type (the cuts ARE the+ * revision plan);+ * - optional reader-panel consensus notes (#2170) when available.+ *+ * No I/O and no LLM — the caller supplies the snapshots; this returns a string.+ * Unit-tested on plain fixtures.+ */++// Human labels for the 9 judge dimensions (mirrors pipelineJudge.JUDGE_DIMENSIONS+// order). Kept local so this module stays free of a service import — a tiny,+// stable map is cheaper than the coupling.+const DIMENSION_LABELS = Object.freeze({+ voiceAdherence: 'Voice adherence',+ beatCoverage: 'Beat coverage',+ characterVoice: 'Character voice',+ plantsSeeded: 'Plants seeded',+ proseQuality: 'Prose quality',+ continuity: 'Continuity',+ canonCompliance: 'Canon compliance',+ loreIntegration: 'Lore integration',+ engagement: 'Engagement',+});++const trimList = (arr, cap = 8) => (Array.isArray(arr) ? arr.filter((s) => typeof s === 'string' && s.trim()).slice(0, cap) : []);++/**+ * The weakest scored dimensions of a judge snapshot, ascending by score, capped+ * at `n`. Only dimensions carrying an actionable note (fix or weakestMoment) are+ * returned — a low score with no guidance isn't useful in the brief. Pure.+ */+export function weakestDimensions(judge, n = 3) {+ const dims = judge?.dimensions && typeof judge.dimensions === 'object' ? judge.dimensions : {};+ return Object.keys(DIMENSION_LABELS)+ .map((key) => {+ const d = dims[key] || {};+ return {+ key,+ label: DIMENSION_LABELS[key],+ score: Number.isFinite(Number(d.score)) ? Number(d.score) : null,+ fix: typeof d.fix === 'string' ? d.fix.trim() : '',+ weakestMoment: typeof d.weakestMoment === 'string' ? d.weakestMoment.trim() : '',+ };+ })+ .filter((d) => d.score != null && (d.fix || d.weakestMoment))+ .sort((a, b) => a.score - b.score)+ .slice(0, n);+}++/**+ * Group adversarial-cut comments by their cut type (subtype). Returns a+ * Map-like plain object `{ TYPE: [quote, …] }`, quotes deduped + capped. Pure.+ */+export function groupCutsByType(cutComments) {+ const groups = {};+ for (const c of (Array.isArray(cutComments) ? cutComments : [])) {+ const type = (typeof c?.subtype === 'string' && c.subtype.trim()) ? c.subtype.trim() : 'UNCLASSIFIED';+ const quote = (typeof c?.anchorQuote === 'string' && c.anchorQuote.trim())+ ? c.anchorQuote.trim()+ : (typeof c?.problem === 'string' ? c.problem.trim() : '');+ if (!quote) continue;+ (groups[type] ||= []);+ if (!groups[type].includes(quote)) groups[type].push(quote);+ }+ return groups;+}++/**+ * Assemble the revision brief string for one issue from the judge snapshot, the+ * open adversarial-cut findings, and optional reader-panel consensus notes.+ *+ * @param {object} p+ * @param {object} p.issue the issue record ({ number, title })+ * @param {object} p.judge the judge snapshot (#2167) for the issue+ * @param {Array} [p.cutComments] open adversarial-cut review comments (#2168)+ * @param {string[]} [p.panelConsensus] reader-panel consensus notes (#2170)+ * @param {number} [p.currentChars] current draft length (drives the TARGET line)+ * @returns {string} the brief+ */+export function buildRevisionBrief({ issue, judge, cutComments = [], panelConsensus = [], currentChars = null } = {}) {+ const num = issue?.number != null ? `#${issue.number}` : '';+ const title = typeof issue?.title === 'string' ? issue.title : '';+ const heading = `REVISION BRIEF — Issue ${num}${title ? `: ${title}` : ''}`.trim();+ const j = judge && typeof judge === 'object' ? judge : {};+ const lines = [heading, ''];++ // PROBLEM — the verdict + the weakest dimensions' fixes.+ lines.push('PROBLEM');+ if (typeof j.oneLineVerdict === 'string' && j.oneLineVerdict.trim()) {+ lines.push(`- Verdict: ${j.oneLineVerdict.trim()}`);+ }+ if (Number.isFinite(Number(j.qualityScore))) {+ lines.push(`- Current quality score: ${j.qualityScore} (judge ${j.overall ?? '?'} − slop ${j.slopPenalty ?? 0}).`);+ }+ for (const d of weakestDimensions(j, 3)) {+ lines.push(`- ${d.label} (${d.score}/10): ${d.fix || d.weakestMoment}`);+ }+ lines.push('');++ // WHAT TO KEEP — protect the strongest material so the rewrite can't gut it.+ lines.push('WHAT TO KEEP (do not weaken these)');+ const strongest = trimList(j.strongestSentences, 3);+ if (strongest.length) {+ for (const s of strongest) lines.push(`- Keep this beat/voice: "${s}"`);+ } else {+ lines.push('- Preserve the issue\'s strongest voice and its landed beats — tighten around them, don\'t replace them.');+ }+ lines.push('');++ // WHAT TO CHANGE — the concrete edit list: judge revisions, weak sentences, cuts.+ lines.push('WHAT TO CHANGE');+ const revisions = trimList(j.topRevisions, 3);+ for (const r of revisions) lines.push(`- ${r}`);+ const weakest = trimList(j.weakestSentences, 3);+ for (const w of weakest) lines.push(`- Rework this line: "${w}"`);+ const cutGroups = groupCutsByType(cutComments);+ for (const type of Object.keys(cutGroups)) {+ const quotes = cutGroups[type].slice(0, 4);+ lines.push(`- Cut (${type}): ${quotes.map((q) => `"${q.length > 120 ? `${q.slice(0, 120)}…` : q}"`).join('; ')}`);+ }+ const consensus = trimList(panelConsensus, 4);+ for (const c of consensus) lines.push(`- Reader panel: ${c}`);+ if (revisions.length === 0 && weakest.length === 0 && Object.keys(cutGroups).length === 0 && consensus.length === 0) {+ lines.push('- No specific edits surfaced — tighten prose, remove over-explanation, and vary sentence rhythm.');+ }+ lines.push('');++ // VOICE RULES — carry the voice-adherence fix so the reviser stays on-voice.+ lines.push('VOICE RULES');+ const voiceFix = j.dimensions?.voiceAdherence?.fix;+ if (typeof voiceFix === 'string' && voiceFix.trim()) {+ lines.push(`- ${voiceFix.trim()}`);+ } else {+ lines.push('- Hold the series voice, tense, and POV exactly as established. Do not drift register.');+ }+ lines.push('');++ // TARGET — tighten toward the judge's fat estimate when we know the length.+ lines.push('TARGET');+ if (Number.isFinite(Number(currentChars)) && Number(currentChars) > 0) {+ lines.push(`- Current length ≈ ${Number(currentChars).toLocaleString()} chars. Cut fat; do not pad. Aim tighter, not longer.`);+ } else {+ lines.push('- Cut fat; keep the issue tight. Do not pad to hit a length.');+ }++ return lines.join('\n');+}++export const __testing = { DIMENSION_LABELS, trimList };diff --git a/server/services/pipeline/editorial/revisionBrief.test.js b/server/services/pipeline/editorial/revisionBrief.test.jsnew file mode 100644index 0000000000..8e0de868a4--- /dev/null+++ b/server/services/pipeline/editorial/revisionBrief.test.js@@ -0,0 +1,104 @@+import { describe, it, expect } from 'vitest';+import { buildRevisionBrief, weakestDimensions, groupCutsByType } from './revisionBrief.js';++const judge = {+ overall: 6.0,+ slopPenalty: 1.0,+ qualityScore: 5.0,+ oneLineVerdict: 'Competent but over-explained; the middle sags.',+ strongestSentences: ['The bell tolled once, and the city held its breath.'],+ weakestSentences: ['She felt a sense of unease wash over her.'],+ topRevisions: ['Cut the interiority in the tavern scene.', 'Land the cliffhanger harder.'],+ dimensions: {+ voiceAdherence: { score: 8, fix: 'Hold the wry narrator voice in the council scene.' },+ beatCoverage: { score: 7, fix: '' },+ characterVoice: { score: 5, fix: 'Give the captain a distinct cadence.', weakestMoment: 'flat dialogue' },+ plantsSeeded: { score: 9, fix: '' },+ proseQuality: { score: 4, fix: 'Vary sentence length; too much uniform rhythm.' },+ continuity: { score: 8, fix: '' },+ canonCompliance: { score: 8, fix: '' },+ loreIntegration: { score: 7, fix: '' },+ engagement: { score: 6, fix: 'Raise stakes earlier.' },+ },+};++const cutComments = [+ { subtype: 'OVER-EXPLAIN', anchorQuote: 'which of course meant that she was afraid', problem: 'x' },+ { subtype: 'REDUNDANT', anchorQuote: 'again, once more, a second time', problem: 'y' },+ { subtype: 'OVER-EXPLAIN', anchorQuote: 'in other words, he was lying', problem: 'z' },+];++describe('weakestDimensions', () => {+ it('returns the lowest-scoring dimensions that carry a note, ascending', () => {+ const weak = weakestDimensions(judge, 3);+ expect(weak.map((d) => d.key)).toEqual(['proseQuality', 'characterVoice', 'engagement']);+ expect(weak[0].label).toBe('Prose quality');+ });+ it('skips dimensions with no fix and no weakestMoment', () => {+ const weak = weakestDimensions(judge, 9);+ expect(weak.find((d) => d.key === 'beatCoverage')).toBeUndefined();+ });+ it('tolerates a missing/empty judge', () => {+ expect(weakestDimensions(null)).toEqual([]);+ expect(weakestDimensions({})).toEqual([]);+ });+});++describe('groupCutsByType', () => {+ it('groups quotes by subtype and dedupes', () => {+ const groups = groupCutsByType([...cutComments, cutComments[0]]);+ expect(groups['OVER-EXPLAIN']).toHaveLength(2);+ expect(groups.REDUNDANT).toHaveLength(1);+ });+ it('falls back to UNCLASSIFIED for a missing subtype', () => {+ const groups = groupCutsByType([{ anchorQuote: 'orphan quote' }]);+ expect(groups.UNCLASSIFIED).toEqual(['orphan quote']);+ });+ it('ignores comments with no quote/problem', () => {+ expect(groupCutsByType([{ subtype: 'FAT' }])).toEqual({});+ });+});++describe('buildRevisionBrief', () => {+ const brief = buildRevisionBrief({+ issue: { number: 3, title: 'The Sundering' },+ judge,+ cutComments,+ panelConsensus: ['The Genre Reader: the tavern scene stalls momentum.'],+ currentChars: 12345,+ });++ it('has all five sections in order', () => {+ const idx = (s) => brief.indexOf(s);+ expect(idx('PROBLEM')).toBeGreaterThanOrEqual(0);+ expect(idx('WHAT TO KEEP')).toBeGreaterThan(idx('PROBLEM'));+ expect(idx('WHAT TO CHANGE')).toBeGreaterThan(idx('WHAT TO KEEP'));+ expect(idx('VOICE RULES')).toBeGreaterThan(idx('WHAT TO CHANGE'));+ expect(idx('TARGET')).toBeGreaterThan(idx('VOICE RULES'));+ });+ it('names the issue and carries the verdict', () => {+ expect(brief).toContain('Issue #3: The Sundering');+ expect(brief).toContain('Competent but over-explained');+ });+ it('protects the strongest sentence in WHAT TO KEEP', () => {+ expect(brief).toContain('The bell tolled once');+ });+ it('lists the judge revisions and grouped cuts in WHAT TO CHANGE', () => {+ expect(brief).toContain('Land the cliffhanger harder.');+ expect(brief).toContain('Cut (OVER-EXPLAIN)');+ expect(brief).toContain('Cut (REDUNDANT)');+ });+ it('carries the voice-adherence fix in VOICE RULES', () => {+ expect(brief).toContain('Hold the wry narrator voice');+ });+ it('mentions the current length in TARGET', () => {+ expect(brief).toContain('12,345');+ });++ it('degrades gracefully with no evidence', () => {+ const bare = buildRevisionBrief({ issue: { number: 1 }, judge: {} });+ expect(bare).toContain('WHAT TO KEEP');+ expect(bare).toContain('No specific edits surfaced');+ expect(bare).toContain('Hold the series voice');+ });+});diff --git a/server/services/pipeline/editorial/revisionStop.js b/server/services/pipeline/editorial/revisionStop.jsnew file mode 100644index 0000000000..1da8f94148--- /dev/null+++ b/server/services/pipeline/editorial/revisionStop.js@@ -0,0 +1,144 @@+/**+ * Pipeline — Iterate-to-quality revision loop: stop-condition + keep/revert logic+ * (CWQE Phase 7, #2171).+ *+ * Pure decision helpers for the Series Autopilot's optional revision loop+ * (`runRevisionCycle` in seriesAutopilot.js). They carry NO I/O so the whole+ * stopping/keep-revert policy is unit-testable on plain score/finding fixtures —+ * the autopilot only supplies the numbers and reads the verdict.+ *+ * Three decisions, ported from autonovel's revision phase:+ *+ * 1. keep/revert — a revision is kept only when the re-judged qualityScore did+ * NOT regress (post ≥ pre). A regression restores the pre-revision snapshot.+ * 2. plateau — stop cycling once the mean series qualityScore stops moving+ * (|Δ| < plateauDelta between the last two cycles), after a minimum count.+ * 3. qualification-aware convergence — "the reviewer will ALWAYS find+ * something". Stop when the remaining findings read as hedged trade-offs+ * ("individually fine", "deliberate choice", "costs of ambition") rather+ * than actionable defects. Majority-hedged ⇒ converged.+ */++// Phrases that mark a finding as a HEDGED trade-off rather than an actionable+// defect (autonovel's "costs of ambition" language). Matched case-insensitively+// as substrings so surrounding prose ("this is individually fine, but…") still+// trips them. Kept deliberately small + specific — a broad list would classify+// genuine critique as hedged and stop the loop early.+export const HEDGE_PHRASES = Object.freeze([+ 'individually fine',+ 'deliberate choice',+ 'deliberate decision',+ 'costs of ambition',+ 'not a flaw',+ 'not really a flaw',+ 'matter of taste',+ 'matter of preference',+ 'defensible choice',+ 'works as intended',+ 'nothing wrong with',+ 'no notes',+ 'stylistic choice',+ 'author’s prerogative',+ "author's prerogative",+]);++/**+ * Classify one finding string as 'hedged' (a qualified trade-off) or 'actionable'+ * (a real defect). Non-string / empty input is 'actionable' by default — an+ * unlabeled finding shouldn't be treated as converged.+ */+export function classifyQualification(text) {+ if (typeof text !== 'string' || !text.trim()) return 'actionable';+ const lower = text.toLowerCase();+ return HEDGE_PHRASES.some((p) => lower.includes(p)) ? 'hedged' : 'actionable';+}++/**+ * True when the STRICT majority of non-empty findings are hedged. An empty list+ * is NOT majority-hedged (there's nothing to converge on — a fresh run with no+ * findings yet keeps its other stop conditions intact). Ties (exactly half) are+ * not a majority, so the loop keeps going while defects are still even with hedges.+ */+export function isMajorityHedged(findingTexts = []) {+ const texts = (Array.isArray(findingTexts) ? findingTexts : []).filter((t) => typeof t === 'string' && t.trim());+ if (texts.length === 0) return false;+ const hedged = texts.filter((t) => classifyQualification(t) === 'hedged').length;+ return hedged * 2 > texts.length;+}++/**+ * True when the mean series qualityScore has plateaued — the absolute change+ * between the two most recent cycles is below `plateauDelta`. Needs at least two+ * recorded scores; fewer than two is never a plateau (not enough signal).+ * Non-finite entries are ignored rather than poisoning the comparison.+ */+export function detectPlateau(scoreHistory = [], plateauDelta = 0.3) {+ const scores = (Array.isArray(scoreHistory) ? scoreHistory : []).filter((n) => Number.isFinite(n));+ if (scores.length < 2) return false;+ const last = scores[scores.length - 1];+ const prev = scores[scores.length - 2];+ return Math.abs(last - prev) < plateauDelta;+}++/**+ * Keep/revert gate for a single revised issue. Keep when the re-judged score did+ * NOT regress (post ≥ pre). Revert only on a genuine regression. When either+ * score is unknown (never judged / judge failed) we KEEP — we can't prove a+ * regression, and reverting a possibly-good revision on missing data is worse+ * than keeping it. Returns 'keep' | 'revert'.+ */+export function decideKeepRevert(preScore, postScore) {+ const pre = Number(preScore);+ const post = Number(postScore);+ if (!Number.isFinite(pre) || !Number.isFinite(post)) return 'keep';+ return post >= pre ? 'keep' : 'revert';+}++/**+ * Decide whether the revision loop should STOP after the cycle that just+ * completed. Precedence:+ * 1. maxCycles — a hard ceiling, always honored (cost cap).+ * 2. after minCycles: qualification-aware convergence (majority-hedged findings).+ * 3. after minCycles: plateau (mean series score stopped moving).+ * Otherwise keep cycling.+ *+ * @param {object} p+ * @param {number} p.cyclesRun cycles completed so far (incl. the one just run)+ * @param {number} p.minCycles floor before hedge/plateau stops can fire+ * @param {number} p.maxCycles hard ceiling+ * @param {number[]} p.scoreHistory mean series qualityScore per completed cycle+ * @param {number} p.plateauDelta |Δ| below which the score counts as plateaued+ * @param {string[]} p.findingTexts remaining finding descriptions to classify+ * @returns {{ stop: boolean, reason: string|null, detail: string }}+ */+export function evaluateRevisionStop({+ cyclesRun = 0,+ minCycles = 1,+ maxCycles = 2,+ scoreHistory = [],+ plateauDelta = 0.3,+ findingTexts = [],+} = {}) {+ if (cyclesRun >= maxCycles) {+ return { stop: true, reason: 'maxCycles', detail: `reached the max of ${maxCycles} revision cycle(s)` };+ }+ if (cyclesRun >= minCycles) {+ if (isMajorityHedged(findingTexts)) {+ return {+ stop: true,+ reason: 'hedged',+ detail: 'remaining findings are majority-hedged trade-offs (qualification-aware convergence)',+ };+ }+ if (detectPlateau(scoreHistory, plateauDelta)) {+ const scores = scoreHistory.filter((n) => Number.isFinite(n));+ const delta = Math.abs(scores[scores.length - 1] - scores[scores.length - 2]);+ return {+ stop: true,+ reason: 'plateau',+ detail: `mean series quality plateaued (Δ ${delta.toFixed(2)} < ${plateauDelta})`,+ };+ }+ }+ return { stop: false, reason: null, detail: '' };+}diff --git a/server/services/pipeline/editorial/revisionStop.test.js b/server/services/pipeline/editorial/revisionStop.test.jsnew file mode 100644index 0000000000..aaf73d0f17--- /dev/null+++ b/server/services/pipeline/editorial/revisionStop.test.js@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest';+import {+ classifyQualification,+ isMajorityHedged,+ detectPlateau,+ decideKeepRevert,+ evaluateRevisionStop,+ HEDGE_PHRASES,+} from './revisionStop.js';++describe('classifyQualification', () => {+ it('flags hedge phrases as hedged (case-insensitive substring)', () => {+ expect(classifyQualification('This is individually fine, but the pacing sags.')).toBe('hedged');+ expect(classifyQualification('A DELIBERATE CHOICE to slow the reveal.')).toBe('hedged');+ expect(classifyQualification('the costs of ambition here are acceptable')).toBe('hedged');+ });+ it('treats a real defect as actionable', () => {+ expect(classifyQualification('The villain\'s motivation is never established.')).toBe('actionable');+ });+ it('defaults empty / non-string to actionable', () => {+ expect(classifyQualification('')).toBe('actionable');+ expect(classifyQualification(null)).toBe('actionable');+ expect(classifyQualification(42)).toBe('actionable');+ });+ it('every HEDGE_PHRASE classifies as hedged', () => {+ for (const p of HEDGE_PHRASES) expect(classifyQualification(`note: ${p} indeed`)).toBe('hedged');+ });+});++describe('isMajorityHedged', () => {+ it('is true only on a strict majority', () => {+ expect(isMajorityHedged(['individually fine', 'deliberate choice', 'real defect here'])).toBe(true);+ expect(isMajorityHedged(['individually fine', 'real defect', 'another real defect'])).toBe(false);+ });+ it('a tie (exactly half) is NOT a majority', () => {+ expect(isMajorityHedged(['individually fine', 'a genuine problem'])).toBe(false);+ });+ it('empty list is not majority-hedged', () => {+ expect(isMajorityHedged([])).toBe(false);+ expect(isMajorityHedged(['', ' '])).toBe(false);+ });+});++describe('detectPlateau', () => {+ it('needs at least two scores', () => {+ expect(detectPlateau([7.5], 0.3)).toBe(false);+ expect(detectPlateau([], 0.3)).toBe(false);+ });+ it('true when the last delta is below the threshold', () => {+ expect(detectPlateau([6.0, 7.0, 7.1], 0.3)).toBe(true);+ });+ it('false when the last delta meets or exceeds the threshold', () => {+ expect(detectPlateau([6.0, 7.0], 0.3)).toBe(false);+ expect(detectPlateau([7.0, 7.4], 0.3)).toBe(false); // 0.4 delta is well above the threshold+ });+ it('ignores non-finite entries', () => {+ expect(detectPlateau([7.0, NaN, 7.1], 0.3)).toBe(true);+ });+});++describe('decideKeepRevert', () => {+ it('keeps when post >= pre', () => {+ expect(decideKeepRevert(6.0, 6.0)).toBe('keep');+ expect(decideKeepRevert(6.0, 7.2)).toBe('keep');+ });+ it('reverts on a genuine regression', () => {+ expect(decideKeepRevert(7.2, 6.0)).toBe('revert');+ });+ it('keeps when either score is unknown (cannot prove a regression)', () => {+ expect(decideKeepRevert(null, 6.0)).toBe('keep');+ expect(decideKeepRevert(6.0, undefined)).toBe('keep');+ expect(decideKeepRevert(NaN, NaN)).toBe('keep');+ });+});++describe('evaluateRevisionStop', () => {+ it('stops at maxCycles regardless of score/findings', () => {+ const r = evaluateRevisionStop({ cyclesRun: 2, minCycles: 1, maxCycles: 2, scoreHistory: [5, 8], findingTexts: ['real defect'] });+ expect(r.stop).toBe(true);+ expect(r.reason).toBe('maxCycles');+ });+ it('does not stop before minCycles even on a plateau', () => {+ const r = evaluateRevisionStop({ cyclesRun: 1, minCycles: 2, maxCycles: 5, scoreHistory: [7.0, 7.05], plateauDelta: 0.3 });+ expect(r.stop).toBe(false);+ });+ it('stops on hedged convergence after minCycles', () => {+ const r = evaluateRevisionStop({+ cyclesRun: 1, minCycles: 1, maxCycles: 5,+ scoreHistory: [6.0, 8.0], plateauDelta: 0.3,+ findingTexts: ['individually fine', 'deliberate choice', 'a real defect'],+ });+ expect(r.stop).toBe(true);+ expect(r.reason).toBe('hedged');+ });+ it('stops on plateau after minCycles when findings are actionable', () => {+ const r = evaluateRevisionStop({+ cyclesRun: 2, minCycles: 1, maxCycles: 5,+ scoreHistory: [7.0, 7.1], plateauDelta: 0.3,+ findingTexts: ['a real defect', 'another problem'],+ });+ expect(r.stop).toBe(true);+ expect(r.reason).toBe('plateau');+ });+ it('keeps cycling when score is still climbing and findings are actionable', () => {+ const r = evaluateRevisionStop({+ cyclesRun: 1, minCycles: 1, maxCycles: 5,+ scoreHistory: [6.0, 7.5], plateauDelta: 0.3,+ findingTexts: ['a real defect'],+ });+ expect(r.stop).toBe(false);+ expect(r.reason).toBe(null);+ });+});diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 5f7bab9a69..8f16b43fd2 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -99,6 +99,11 @@ import { computeHealth, openBlockers, READINESS_GATES, resolveReadinessGate, sumimport { 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 { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';@@ -233,6 +238,46 @@ 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 = {@@ -584,6 +629,21 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {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@@ -1597,6 +1657,245 @@ async function runProduceTeaser(sId, issueId, record) {}}+// 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': {@@ -1652,6 +1951,8 @@ async function dispatchStep(sId, step, record) {return runEditorialChecksPass(sId, record);case 'editorialHealthGate':return runEditorialHealthGate(sId, record);+ case 'revisionCycle':+ return runRevisionCycle(sId, record);case 'canonVerify':return runCanonVerify(sId, record);case 'visualDraft':@@ -1750,6 +2051,20 @@ function buildDryRunPlan(series, issues, options, costContext = {}) {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 });@@ -1807,6 +2122,7 @@ export async function startSeriesAutopilot(sId, options = {}) {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'),@@ -1860,6 +2176,14 @@ export async function startSeriesAutopilot(sId, options = {}) {// 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,};@@ -2038,4 +2362,4 @@ export async function recoverStuckAutopilots() {}// Export internals for tests.-export const __testing = { runs, buildDryRunPlan, summarizePlanCost, providerOverrideOpts, providerIdOpts };+export const __testing = { runs, buildDryRunPlan, summarizePlanCost, providerOverrideOpts, providerIdOpts, meanQualityScore };diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 251774d25d..555a640505 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -697,6 +697,132 @@ describe('resolveAutopilotProduceTeaser (config gate, #2185)', () => {});});+// CWQE Phase 7 (#2171) — iterate-to-quality revision loop.+describe('resolveAutopilotRevision (config gate, #2171)', () => {+ const {+ resolveAutopilotRevision,+ DEFAULT_REVISION_MIN_CYCLES,+ DEFAULT_REVISION_MAX_CYCLES,+ DEFAULT_REVISION_PLATEAU_DELTA,+ } = autopilot;++ it('defaults OFF with the module cycle defaults', () => {+ expect(resolveAutopilotRevision({}, null)).toEqual({+ revisionEnabled: false,+ revisionMinCycles: DEFAULT_REVISION_MIN_CYCLES,+ revisionMaxCycles: DEFAULT_REVISION_MAX_CYCLES,+ revisionPlateauDelta: DEFAULT_REVISION_PLATEAU_DELTA,+ });+ });+ it('per-run option wins over the persisted setting', () => {+ const r = resolveAutopilotRevision(+ { revisionEnabled: true, revisionMaxCycles: 4, revisionPlateauDelta: 0.5 },+ { pipelineEditorialChecks: { revisionEnabled: false, revisionMaxCycles: 2 } },+ );+ expect(r.revisionEnabled).toBe(true);+ expect(r.revisionMaxCycles).toBe(4);+ expect(r.revisionPlateauDelta).toBe(0.5);+ });+ it('falls back to the persisted setting when no per-run option', () => {+ const r = resolveAutopilotRevision({}, { pipelineEditorialChecks: { revisionEnabled: true, revisionMinCycles: 2 } });+ expect(r.revisionEnabled).toBe(true);+ expect(r.revisionMinCycles).toBe(2);+ });+ it('clamps maxCycles up to at least minCycles (misconfig can never strand the loop)', () => {+ const r = resolveAutopilotRevision({ revisionMinCycles: 3, revisionMaxCycles: 1 });+ expect(r.revisionMaxCycles).toBe(3);+ });+ it('floors minCycles at 1 and plateauDelta at 0', () => {+ const r = resolveAutopilotRevision({ revisionMinCycles: 0, revisionPlateauDelta: -5 });+ expect(r.revisionMinCycles).toBe(1);+ expect(r.revisionPlateauDelta).toBe(0);+ });+});++describe('resolveNextStep — revision cycle ordering (#2171)', () => {+ const comic = { targetFormat: 'comic', arc: { logline: 'L', summary: 'S' }, seasons: [{ id: 'se1', number: 1 }] };+ const issue = (over = {}) => ({ id: 'iss1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {}, ...over });+ // Health-clean base runState (everything up to and including the health gate).+ const healthClean = {+ arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']),+ editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true,+ editorialHealthReady: true,+ };+ const stages = { idea: ready(), comicScript: ready(VALID_SCRIPT) };++ it('does NOT insert a revision cycle when disabled (default) — proceeds to canonVerify', () => {+ const step = resolveNextStep(comic, [issue({ stages })], healthClean, { includeVisual: true });+ expect(step.kind).toBe('canonVerify');+ });++ it('inserts the revision cycle after the health gate and before canonVerify when enabled', () => {+ const step = resolveNextStep(comic, [issue({ stages })], healthClean, { includeVisual: true, revisionEnabled: true, revisionMaxCycles: 2 });+ expect(step.kind).toBe('revisionCycle');+ expect(step.reason).toMatch(/cycle 1/);+ });++ it('routes back to the revision cycle while cycles remain (cursor is revisionCyclesRun)', () => {+ const step = resolveNextStep(+ comic, [issue({ stages })],+ { ...healthClean, revisionCyclesRun: 1 },+ { includeVisual: true, revisionEnabled: true, revisionMaxCycles: 3 },+ );+ expect(step.kind).toBe('revisionCycle');+ expect(step.reason).toMatch(/cycle 2/);+ });++ it('stops routing to the revision cycle once maxCycles is reached', () => {+ const step = resolveNextStep(+ comic, [issue({ stages })],+ { ...healthClean, revisionCyclesRun: 2 },+ { includeVisual: true, revisionEnabled: true, revisionMaxCycles: 2 },+ );+ expect(step.kind).toBe('canonVerify');+ });++ it('stops routing to the revision cycle once converged (plateau/hedge latched)', () => {+ const step = resolveNextStep(+ comic, [issue({ stages })],+ { ...healthClean, revisionCyclesRun: 1, revisionConverged: true },+ { includeVisual: true, revisionEnabled: true, revisionMaxCycles: 5 },+ );+ expect(step.kind).toBe('canonVerify');+ });++ it('dry-run plan lists the revision cycle after the health gate when enabled', () => {+ const series = { targetFormat: 'comic', arc: { logline: 'L', summary: 'S' }, seasons: [{ id: 'se1', number: 1 }] };+ const issues = [{ id: 'i1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {} }];+ const plan = autopilot.__testing.buildDryRunPlan(series, issues, { revisionEnabled: true, revisionMaxCycles: 3, includeVisual: false });+ const kinds = plan.map((p) => p.kind);+ expect(kinds).toContain('revisionCycle');+ expect(kinds.indexOf('revisionCycle')).toBeGreaterThan(kinds.indexOf('editorialHealthGate'));+ const rev = plan.find((p) => p.kind === 'revisionCycle');+ expect(rev.count).toBe(3);+ });++ it('dry-run plan omits the revision cycle when disabled', () => {+ const series = { targetFormat: 'comic', arc: { logline: 'L', summary: 'S' }, seasons: [{ id: 'se1', number: 1 }] };+ const issues = [{ id: 'i1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {} }];+ const plan = autopilot.__testing.buildDryRunPlan(series, issues, { includeVisual: false });+ expect(plan.map((p) => p.kind)).not.toContain('revisionCycle');+ });+});++describe('meanQualityScore (#2171)', () => {+ const { meanQualityScore } = autopilot.__testing;+ it('averages only judged, finite scores', () => {+ expect(meanQualityScore({ scores: [+ { judged: true, qualityScore: 6 },+ { judged: true, qualityScore: 8 },+ { judged: false, qualityScore: null },+ ] })).toBe(7);+ });+ it('is null when nothing is judged', () => {+ expect(meanQualityScore({ scores: [{ judged: false, qualityScore: null }] })).toBe(null);+ expect(meanQualityScore({ scores: [] })).toBe(null);+ });+});+describe('autopilotEvents in-process bus (#2185)', () => {it('mirrors the SSE frames a real run broadcasts onto the bus keyed by seriesId', async () => {cosMode = 'dry-run';