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
Merge remote-tracking branch 'origin/main' into next/issue-2171
Adam Eivy8e951e1e0fd2
diff --cc .changelog/NEXT.mdindex a5528aad8b,80c77d0793..5232e2058a--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@@ -48,7 -53,7 +53,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-2179] The Writers Room now anchors a freeform work's voice with the same exemplar/anti-exemplar passages ("the tuning fork") the series pipeline already uses.** Completing #2179's Writers Room parity: a work can now carry `voiceExemplars` (1–3 short passages that nail its target voice, each with an optional note on what it demonstrates) and `voiceAntiExemplars` (passages in the wrong register, noted with what's wrong — "too ornate", "wrong temperature"), edited in a new **Voice exemplars** drawer on the work editor. On generation those render into the SAME "MATCH this voice / NEVER drift toward this" blocks as the series style guide — via the shared `renderVoiceExemplars`/`sanitizeVoiceExemplars` helpers now exported from `server/lib/styleGuide.js` (one sanitizer, one set of caps, no drift between surfaces) — and are injected into the two prose-generation paths: the **live-continuation** prompt (`writers-room-continue.md`, gated by a conditional `{{#voiceGuide}}` block so a work with no passages carries zero per-call overhead) and the **Phase 9 polish loop**'s revision brief (folded into VOICE RULES so the rewrite is held to the chosen voice, not just told to "match the existing voice"). The editor UI is the shared `VoiceExemplarEditor` component (extracted from the series style-guide editor and reused by both). Zod parity on `writersRoomWorkUpdateSchema` (each passage capped at 2000 chars, list at 3; an explicit `[]` clears); the server sanitizer drops empty passages and re-sanitizes on read. `writers-room-continue.md` is a shipped template, so the block ships to existing installs via a standard hash-keyed migration (181) with migration 166 resynced and the drift baseline updated. (Final slice of #2179 — the earlier slices shipped the series exemplar fields, the AI voice-discovery flow, and the voice-fingerprint baseline hook.) (`server/lib/styleGuide.js`, `server/lib/pipelineValidation.js`, `server/services/writersRoom/local.js`, `server/services/writersRoom/liveDirector.js`, `server/services/writersRoom/polish.js`, `data.reference/prompts/stages/writers-room-continue.md`, `scripts/migrations/181-writers-room-voice-exemplars.js`, `client/src/components/VoiceExemplarEditor.jsx`, `client/src/components/writers-room/WorkEditor.jsx`)- **[issue-2180] Series invention now generates several distinct concepts under an anti-generic banlist, then user-picks (interactive) or judge-picks (autonomous) the winner — concept diversity at the seed is the cheapest quality lever in the pipeline.** Autonomous series invention used to produce ONE concept with no anti-generic pressure; autonovel's seed stage generates many concepts under an explicit banlist ("no chosen-one prophecies, no dark lords, no medieval-Europe-with-elves, no magic academies, no love triangles"), then selects. The `pipeline-series-generate` stage now invents **N genuinely distinct candidate concepts** (default 5, clamped 2–8), each carrying craft facets — HOOK / WORLD / CONFLICT ENGINE + COST / TENSION (personal AND larger-scale) / THEME (genre-neutral, not every series has magic) — under an **anti-generic banlist** that merges a shipped default list with the universe's own `influences.avoid` (case-insensitive dedupe, so an author's "steer clear of X" gets a hard veto at the seed). **Interactive mode** (the "Generate with AI" button on the New Series form) now presents the candidates for **user pick** — a deep-linkable card selection (`?concept=` is the URL source of truth) that pre-fills the form; the rejected candidates stay in memory (and in run history) so the user can switch without regenerating. **Autonomous mode** (CoS-driven invention) **judge-picks** the winner via a new one-call forced-rank stage `pipeline-series-concept-judge` ("which concept would a reader who has seen a thousand pitches stop scrolling for?" — ties forbidden), reusing the writer/judge split (#2167) resolved from the generation stage's `judgeProvider`/`judgeModel`; it **falls back to the first candidate** when no judge is configured or the call fails, so invention never blocks. Seed-faithful expansion is untouched — when the user typed their own idea it's still expanded, never replaced with a "better" concept. Runs ONLY from an explicit user action or the already-consented autonomous path — never at boot (AI-provider policy). Candidate normalization, banlist merge, forced-rank parsing, and judge-pick fallback are unit-tested; the modified prompt ships a hash-keyed migration (customized prompts preserved + warned) and the new judge stage a seed migration. (`server/services/pipeline/seriesGenerate.js`, `data.reference/prompts/stages/pipeline-series-generate.md`, `data.reference/prompts/stages/pipeline-series-concept-judge.md`, `server/routes/pipeline/series.js`, `server/services/creative/tools/pipeline.js`, `scripts/migrations/179-series-multi-concept-ideation.js`, `scripts/migrations/180-series-concept-judge-stage.js`, `client/src/pages/Pipeline.jsx`, `client/src/services/apiPipeline.js`)- **[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`)diff --cc client/src/components/pipeline/AutopilotPanel.jsxindex 13a3d33ce5,a21d86cba5..fa58343398--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@@ -31,13 -31,21 +31,28 @@@ 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;+ // Foundation-quality gate (#2176) — mirror the server defaults. The gate itself+ // defaults ON (the point of the phase); the weighted [0,10] threshold the+ // foundation must clear before drafting mirrors autonovel's 7.5 bar; the improve+ // loop is bounded by MAX_FOUNDATION_ROUNDS (3).+ const DEFAULT_FOUNDATION_GATE = true;+ const DEFAULT_FOUNDATION_THRESHOLD = 7.5;+ const DEFAULT_FOUNDATION_ROUNDS = 3;+ // Threshold input: a [0,10] number (0.5 steps allowed — NOT integer-rounded like+ // the round clamps), blank/invalid → the default.+ const clampFoundationThreshold = (n, fallback) => {+ if (n === '' || n === null || n === undefined) return fallback;+ const v = Number(n);+ if (!Number.isFinite(v)) return fallback;+ return Math.max(0, Math.min(10, Math.round(v * 100) / 100));+ };// Editorial-health readiness gate (#1316/#1580) — the "manuscript clean" bar the// autopilot must clear before visuals. Mirrors READINESS_GATES on the server. The@@@ -223,12 -223,11 +242,17 @@@ export default function AutopilotPanel(// 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);+ // Foundation-quality gate (#2176) — enable toggle + weighted threshold + round+ // bound. Persisted like the other options (saved default + per-run override).+ const [foundationGate, setFoundationGate] = useState(DEFAULT_FOUNDATION_GATE);+ const [foundationThreshold, setFoundationThreshold] = useState(DEFAULT_FOUNDATION_THRESHOLD);+ const [foundationRounds, setFoundationRounds] = useState(DEFAULT_FOUNDATION_ROUNDS);// 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@@@ -239,10 -238,9 +263,13 @@@const 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 foundationGateEditedRef = useRef(false);+ const foundationThresholdEditedRef = useRef(false);+ const foundationRoundsEditedRef = useRef(false);const [canon, setCanon] = useState(null);const [canonLoading, setCanonLoading] = useState(false);@@@ -262,10 -260,9 +289,13 @@@if (!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);+ if (!foundationGateEditedRef.current) setFoundationGate(typeof pec.foundationGate === 'boolean' ? pec.foundationGate : DEFAULT_FOUNDATION_GATE);+ if (!foundationThresholdEditedRef.current) setFoundationThreshold(Number.isFinite(pec.foundationThreshold) ? pec.foundationThreshold : DEFAULT_FOUNDATION_THRESHOLD);+ if (!foundationRoundsEditedRef.current) setFoundationRounds(Number.isInteger(pec.maxFoundationRounds) ? pec.maxFoundationRounds : DEFAULT_FOUNDATION_ROUNDS);// Persisted readiness gate — display-only, drives the "saved default" label.setSavedGate(READINESS_GATE_LABELS[pec.readinessGate] ? pec.readinessGate : '');})@@@ -392,11 -388,12 +431,17 @@@// #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);+ // #2176 — foundation gate. Persist + override like the other options, only+ // when edited (untouched → server resolves from the persisted setting, then+ // the default: gate ON / threshold 7.5 / 3 rounds).+ if (foundationGateEditedRef.current) roundOverrides.foundationGate = foundationGate;+ if (foundationThresholdEditedRef.current) roundOverrides.foundationThreshold = clampFoundationThreshold(foundationThreshold, DEFAULT_FOUNDATION_THRESHOLD);+ if (foundationRoundsEditedRef.current) roundOverrides.maxFoundationRounds = clampRound(foundationRounds, DEFAULT_FOUNDATION_ROUNDS);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@@@ -412,7 -409,7 +457,7 @@@// 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, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, readinessGate, persistRounds]);- }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, foundationGate, foundationThreshold, foundationRounds, readinessGate, persistRounds]);++ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, readinessGate, persistRounds]);const cancel = useCallback(async () => {await cancelPipelineAutopilot(seriesId).catch(() => null);diff --cc server/services/pipeline/seriesAutopilot.jsindex 8f16b43fd2,7d4cbe9a3c..d0e7e49d82--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@@ -99,13 -99,9 +99,14 @@@ import { computeHealth, openBlockers, Rimport { 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,diff --cc server/services/pipeline/seriesAutopilot.test.jsindex 555a640505,1c8392697d..8971d5fb1a--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@@ -697,132 -739,6 +739,132 @@@ describe('resolveAutopilotProduceTease});});+// 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']),++ arcVerified: true, foundationGated: 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';