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: gate-aware reverse-outline refresh + cached-staleness recheck in autopilot (#1614)
[._.]/ Adam Eivy713fe1b47ee3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 21f220c21c..d5b2a86b7c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,7 @@- **[issue-1697] Health-panel deep-links now honor the triage's session-local check mute.** Muting a check from the Editorial Findings triage (#1602) hid its findings group but the health panel kept advertising that check/category row as clickable — clicking it scrolled to an empty filtered view. The session mute state (`hiddenCheckIds`) was lifted from `EditorialFindingsTriage` up to `PipelineEditorialChecks`, which now subtracts muted checks from the filterable sets the health panel receives; a category stays clickable only while a non-muted check still contributes an open finding to it. (`client/src/pages/PipelineEditorialChecks.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`)- **[issue-1667] Final-part editorial verdicts no longer lose their carried setup context on a packed last chunk.** The cross-chunk "setup so far" digest normally yields to manuscript coverage — but two whole-story checks (`arc.climax-agency`, `emotion.reaction-proportionality`) gate their verdict to the final part and anchor it on a snippet carried in that digest (the climax candidate / the unprocessed event). When the final chunk packed to within a few hundred chars of the provider window, the digest was silently dropped and the final-only finding was missed. These checks now opt into a `reserveSetupDigest` guarantee that trims the final chunk's manuscript tail to make room for the digest (the inverse of the usual yield), scoped to the final chunk and opt-in checks only — every other chunk and every non-reserving check keeps full manuscript coverage. (`server/lib/editorial/checkRegistry.js`)+- **[issue-1614] Series Autopilot no longer wastes an LLM call refreshing the reverse outline for a check that won't run, and never proceeds on a stale one.** The pre-checks reverse-outline refresh decided "does any enabled check consume the outline?" from declared sources alone — so a check that's enabled but whose runtime gate declines for this series (no POV-tagged scenes, a canon-less roster) could still trigger a billed regeneration nothing would read. The refresh now evaluates each consumer's gate against the current outline and skips the regen when nothing that would actually run consumes it; a never-generated outline still bootstraps unconditionally. Separately, when the regen no-ops as cached the run re-confirms staleness against the live manuscript and forces one regen if a concurrent edit moved it — so the editorial checks never read a stale outline mid-run. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/editorial/checkRunner.js`)- **[issue-1613] Series Autopilot can now pause when an editorial-checks pass surfaces too many High findings.** Previously the registry-driven editorial-checks step always reported "complete" regardless of finding count — a pass that surfaced 50 High findings looked clean and only the downstream health gate caught it, making the per-step signal misleading. A new, off-by-default **pause threshold** (`pipelineEditorialChecks.checkFindingsPauseThreshold`, also a per-run override and an Options field) makes the run pause for human review when the checks pass finds at least N High findings — gating like the verify/editorial loops, with the High findings carried as residual and a "high findings" badge in the panel. The step's progress frame now also reports the real High count instead of a hardcoded `0`. 0 = off, so existing runs are unchanged. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/series.js`, `server/lib/validation.js`, `server/routes/pipeline/autopilot.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)## Internaldiff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 4741aa4978..ffe7df8d4f 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -848,14 +848,54 @@ export async function buildEditorialCheckPlan(seriesId, { checkIds = null, setti* gate inside `runEditorialChecks` exactly, so the autopilot's reverse-outline* refresh step and the runner agree on what consumes the outline. Takes resolved* settings (sync) so a caller that already loaded them doesn't pay a second read.+ *+ * Gate-aware refinement (#1614): an enabled consumer whose runtime `gate(ctx)`+ * declines won't actually run — so it doesn't justify spending an LLM call to+ * refresh the outline. When the caller supplies a `gateCtx` (the autopilot+ * refresh path, which already holds a complete-but-stale outline to evaluate+ * against), a consumer must ALSO pass its gate to count. The sources-only signal+ * stands when no ctx is given (the dry-run plan + the cheap pre-filter, neither+ * of which builds a ctx) so existing callers are unchanged.*/-export function enabledChecksConsumeReverseOutline(settings, checkIds = null) {+export function enabledChecksConsumeReverseOutline(settings, checkIds = null, gateCtx = null) {return getEnabledChecks(settings, checkIds).some(({ check }) => {const sources = checkSources(check);- return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');+ if (!sources.includes('reverseOutline') && !sources.includes('reverseOutline.plotlines')) return false;+ if (gateCtx && typeof check.gate === 'function' && !check.gate(gateCtx)) return false;+ return true;});}+/**+ * Build the minimal context needed to evaluate a reverse-outline consumer's+ * runtime `gate(ctx)` (#1614) — the manuscript corpus, canon, and the current+ * outline's scenes/plotlines. The autopilot's reverse-outline refresh uses this+ * to decide whether any check that would ACTUALLY run consumes the outline+ * before spending an LLM call to regenerate it.+ *+ * Deliberately lighter than buildEditorialContext: no issues / editorial-arc /+ * continuity-bible / comic projections and no injected LLM callers, because the+ * gates of outline-consuming checks read only `manuscript`, `canon`, and+ * `reverseOutline[.plotlines]`. Pass the already-read `outline` (the autopilot's+ * Gate-2 read) to avoid a redundant outline fetch.+ */+export async function buildReverseOutlineGateContext(seriesId, { outline } = {}) {+ const series = await getSeries(seriesId);+ const [sections, canon] = await Promise.all([+ collectManuscriptSections(seriesId),+ getSeriesCanon(series),+ ]);+ const resolved = outline || await getReverseOutline(seriesId).catch(() => null);+ return {+ seriesId,+ series,+ manuscript: sectionsCorpus(sections),+ canon,+ reverseOutline: Array.isArray(resolved?.scenes) ? resolved.scenes : [],+ reverseOutlinePlotlines: Array.isArray(resolved?.plotlines) ? resolved.plotlines : [],+ };+}+/*** Read the manuscript review and annotate each editorial-check finding with a* `stale` flag (#1345): true when the content the check analyzed has changeddiff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex 451cb9b572..70cb76cf68 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -76,7 +76,7 @@ vi.mock('../reverseOutline.js', () => ({ getReverseOutline: vi.fn(async () => oulet editorialState = { characters: [] };vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () => editorialState) }));-const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, summarizeCheckErrors, previewCustomCheck, buildScopedPriorFindings, effectiveCheckSources } = await import('./checkRunner.js');+const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors, previewCustomCheck, buildScopedPriorFindings, effectiveCheckSources } = await import('./checkRunner.js');const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');const { collectManuscriptSections } = await import('../arcPlanner.js');const { getSeriesCanon } = await import('../seriesCanon.js');@@ -999,6 +999,50 @@ describe('enabledChecksConsumeReverseOutline (#1349)', () => {const settings = disableWhere(consumesOutline);expect(enabledChecksConsumeReverseOutline(settings)).toBe(false);});++ // Gate-aware consumption (#1614): a supplied ctx narrows the signal to checks+ // that would ACTUALLY run for this series, not just declare the source.+ describe('gate-aware via ctx (#1614)', () => {+ // No manuscript, no named canon, no scenes → every outline consumer's+ // runtime gate declines, so nothing would run even though sources match.+ const gatedOutCtx = { manuscript: '', canon: { characters: [] }, reverseOutline: [], reverseOutlinePlotlines: [] };+ // A drafted manuscript re-opens the manuscript-gated outline consumers.+ const liveCtx = { manuscript: 'The kingdom fell.', canon: { characters: [{ name: 'Bob' }] }, reverseOutline: [{ povCharacter: 'Bob' }], reverseOutlinePlotlines: [] };++ it('sources-only signal is unchanged when no ctx is supplied', () => {+ expect(enabledChecksConsumeReverseOutline({})).toBe(true);+ expect(enabledChecksConsumeReverseOutline({}, null, null)).toBe(true);+ });++ it('is false when every consumer is gated out by the ctx', () => {+ expect(enabledChecksConsumeReverseOutline({}, null, gatedOutCtx)).toBe(false);+ });++ it('is true when at least one consumer passes its gate against the ctx', () => {+ expect(enabledChecksConsumeReverseOutline({}, null, liveCtx)).toBe(true);+ });+ });+});++describe('buildReverseOutlineGateContext (#1614)', () => {+ it('assembles manuscript + canon + the passed outline scenes/plotlines', async () => {+ const outline = { scenes: [{ povCharacter: 'Bob' }], plotlines: [{ id: 'p1' }] };+ const ctx = await buildReverseOutlineGateContext('s1', { outline });+ expect(ctx.manuscript).toContain('the kingdom fell');+ expect(ctx.canon.characters.map((c) => c.name)).toContain('Alina');+ expect(ctx.reverseOutline).toEqual(outline.scenes);+ expect(ctx.reverseOutlinePlotlines).toEqual(outline.plotlines);+ });++ it('reads the stored outline when none is passed, and tolerates a missing one', async () => {+ outlineState = { scenes: [{ povCharacter: 'Zog' }], plotlines: [] };+ const ctx = await buildReverseOutlineGateContext('s1');+ expect(ctx.reverseOutline).toEqual(outlineState.scenes);+ // A non-array scenes/plotlines payload normalizes to empty arrays.+ const ctx2 = await buildReverseOutlineGateContext('s1', { outline: { status: 'none' } });+ expect(ctx2.reverseOutline).toEqual([]);+ expect(ctx2.reverseOutlinePlotlines).toEqual([]);+ });});// Inter-check context sharing (#1627) — dependency-scoped prior findings in ctx.diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 8aa51ea5e6..15eed0ba72 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -92,7 +92,7 @@ import {import * as volumeBeatsRunner from './volumeBeatsRunner.js';import * as autoRunner from './autoRunner.js';import { seedReviewFromFindings, getReview } from './manuscriptReview.js';-import { runEditorialChecks, buildEditorialCheckPlan, enabledChecksConsumeReverseOutline, summarizeCheckErrors } from './editorial/checkRunner.js';+import { runEditorialChecks, buildEditorialCheckPlan, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors } from './editorial/checkRunner.js';import { generateReverseOutline, getReverseOutline } from './reverseOutline.js';import { computeHealth, openBlockers, READINESS_GATES, resolveReadinessGate, summarizeEditorialBlockers, formatBlockerSummary } from './editorialScore.js';import { getSettings } from '../settings.js';@@ -1044,10 +1044,12 @@ const editorialSubsetIds = (options) =>async function runReverseOutlineRefresh(sId, record) {if (record.cancelRequested) return { canceled: true };const settings = await getSettings();- // Gate 1 — does any enabled check (narrowed to this run's subset) even read the- // outline? If not, nothing to do — and a subset that skips outline-consuming- // checks must not pay for a refresh those checks would have triggered.- if (!enabledChecksConsumeReverseOutline(settings, editorialSubsetIds(record.options))) {+ const checkIds = editorialSubsetIds(record.options);+ // Gate 1 — sources-only pre-filter: does any enabled check (narrowed to this+ // run's subset) even DECLARE the outline as a source? If not, nothing to do —+ // and a subset that skips outline-consuming checks must not pay for a refresh+ // those checks would have triggered.+ if (!enabledChecksConsumeReverseOutline(settings, checkIds)) {record.runState.reverseOutlineRefreshed = true;return {};}@@ -1062,20 +1064,48 @@ async function runReverseOutlineRefresh(sId, record) {record.runState.reverseOutlineRefreshed = true;return {};}+ // Gate 3 (#1614) — gate-aware consumption. A check that DECLARES the outline as+ // a source still won't run if its runtime gate declines for this series (e.g.+ // no POV-tagged scenes, a canon-less roster). Evaluate each consumer's gate+ // against the current outline so a refresh is skipped when nothing that would+ // actually run reads it. Only applied to a COMPLETE-but-stale outline: a+ // never-generated outline (`status:'none'`) has no scenes to gate against, so+ // the outline-content gates would all decline — we bootstrap the first run+ // unconditionally rather than chicken-and-egg ourselves out of it.+ if (current.status === 'complete') {+ const gateCtx = await buildReverseOutlineGateContext(sId, { outline: current }).catch(() => null);+ if (gateCtx && !enabledChecksConsumeReverseOutline(settings, checkIds, gateCtx)) {+ record.runState.reverseOutlineRefreshed = true;+ return {};+ }+ }// A regenerate WILL spend one LLM call — gate the budget and bill, like the// other LLM passes. Bridge autopilot cancellation into the stage's AbortSignal.const beforeRefresh = await budgetPause();if (beforeRefresh) return beforeRefresh;const signal = { get aborted() { return record.cancelRequested; } };- const result = await generateReverseOutline(sId, { ...providerIdOpts(record), force: false, signal })+ const regen = (force) => generateReverseOutline(sId, { ...providerIdOpts(record), force, signal }).catch((err) => {console.log(`⚠️ autopilot: reverse-outline refresh failed for ${sId.slice(0, 12)}: ${err.message}`);return null;});+ let result = await regen(false);// Canceled mid-pass — don't bill, don't mark refreshed; let the loop unwind.if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };+ // (#1614) A `cached:true` result means the manuscript hash still matched the+ // stored outline at generate time. Re-confirm staleness against the LIVE+ // manuscript within this run: if a concurrent edit moved the manuscript again+ // after that cache check, the cached outline is now stale and the downstream+ // checks would read it — force exactly one regen so they don't.+ if (result?.cached === true) {+ const after = await getReverseOutline(sId).catch(() => null);+ if (after?.stale === true) {+ result = await regen(true);+ if (result?.status === 'canceled' || record.cancelRequested) return { canceled: true };+ }+ }// Bill ONLY when the call actually regenerated (an LLM run). A `cached` result- // (outline went fresh in the race window) or a `no-content` series spent nothing.+ // (outline still fresh in the race window) or a `no-content` series spent nothing.// No verify:round broadcast here — a refresh isn't a review round (it produces// scenes, not findings); the conductor's generic step:start/step:complete already// surface "Refreshing scene segmentation…" / "done" to the UI.diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 9182102071..968e4c1de3 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -76,6 +76,10 @@ vi.mock('./manuscriptReview.js', () => ({// Drives whether the reverse-outline refresh step (#1349) thinks a scene-consuming// check is enabled. Default false so the existing conductor runs skip it cheaply.let reverseOutlineConsumed = false;+// Gate-aware (#1614) signal: drives the consumption check when a gateCtx is+// passed (the autopilot's Gate 3). `null` = mirror the sources-only signal, so+// every pre-#1614 test keeps its existing behavior.+let reverseOutlineConsumedGated = null;// Drives the perCheck array the editorial-checks pass sees, so a test can inject// an errored check and assert it surfaces in the run summary (#1573).let editorialChecksPerCheck = [];@@ -85,7 +89,12 @@ let editorialChecksFindings = [];const checkRunnerSpies = {runEditorialChecks: vi.fn(async () => ({ runId: 'ec', findings: editorialChecksFindings, perCheck: editorialChecksPerCheck, canceled: false })),buildEditorialCheckPlan: vi.fn(async () => ({ seriesId: 's', checks: [], enabledCount: 0, consumesReverseOutline: reverseOutlineConsumed })),- enabledChecksConsumeReverseOutline: vi.fn(() => reverseOutlineConsumed),+ enabledChecksConsumeReverseOutline: vi.fn((settings, checkIds, gateCtx) =>+ (gateCtx != null && reverseOutlineConsumedGated !== null ? reverseOutlineConsumedGated : reverseOutlineConsumed)),+ // Gate-context builder (#1614) — the SUT calls this before the gate-aware+ // consumption re-check. Shape is irrelevant here (the consumption mock above+ // ignores it); it only needs to resolve to a truthy ctx.+ buildReverseOutlineGateContext: vi.fn(async (seriesId) => ({ seriesId, manuscript: 'x', canon: { characters: [] }, reverseOutline: [], reverseOutlinePlotlines: [] })),// Real pure impl (the module is fully mocked) so the SUT's error-summarizing// matches production behavior without pulling checkRunner's heavy imports.summarizeCheckErrors: (perCheck) => {@@ -177,6 +186,7 @@ beforeEach(() => {canonReady = true;canonUndescribed = [];reverseOutlineConsumed = false;+ reverseOutlineConsumedGated = null;reverseOutlineState = { status: 'complete', stale: false };editorialChecksPerCheck = [];editorialChecksFindings = [];@@ -1264,6 +1274,50 @@ describe('autopilot conductor', () => {expect(generateReverseOutline).not.toHaveBeenCalled();});+ it('skips the refresh when the only consumer is gated out for this series (#1614)', async () => {+ // A check DECLARES the outline as a source (gate 1 passes) but its runtime+ // gate declines for this series — so refreshing the (stale) outline would+ // spend an LLM call no runnable check consumes.+ reverseOutlineConsumed = true; // gate 1: a consumer declares the source+ reverseOutlineConsumedGated = false; // gate 3: but every consumer is gated out+ reverseOutlineState = { status: 'complete', stale: true };+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');+ expect(checkRunnerSpies.buildReverseOutlineGateContext).toHaveBeenCalled();+ expect(generateReverseOutline).not.toHaveBeenCalled();+ });++ it('bootstraps a never-generated outline without the gate-aware skip (#1614)', async () => {+ // `status:'none'` has no scenes to gate against — the outline-content gates+ // would all falsely decline, so the first generation must NOT be gate-skipped.+ reverseOutlineConsumed = true;+ reverseOutlineConsumedGated = false; // would skip a complete outline, but...+ reverseOutlineState = { status: 'none', stale: false }; // ...never generated yet+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(checkRunnerSpies.buildReverseOutlineGateContext).not.toHaveBeenCalled();+ expect(generateReverseOutline).toHaveBeenCalledTimes(1);+ });++ it('forces a regen when a cached refresh is still stale against the live manuscript (#1614)', async () => {+ reverseOutlineConsumed = true;+ reverseOutlineState = { status: 'complete', stale: true };+ // First generate() no-ops as cached (hash matched at generate time), but the+ // live manuscript is still stale → the run forces one more regen.+ generateReverseOutline+ .mockImplementationOnce(async () => ({ status: 'complete', cached: true, stale: false }))+ .mockImplementationOnce(async () => ({ status: 'complete', stale: false, scenes: [{ id: 'sc1' }] }));+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(generateReverseOutline).toHaveBeenCalledTimes(2);+ expect(generateReverseOutline.mock.calls[0][1]).toMatchObject({ force: false });+ expect(generateReverseOutline.mock.calls[1][1]).toMatchObject({ force: true });+ });+it('a budget-exhausted run does not pause at the no-op reverse-outline refresh (#1575 self-gating exemption)', async () => {// A subset run whose checks don't consume the outline makes the refresh a// guaranteed no-op. Budget goes exhausted right after the editorial-review