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
fix: preserve best arc verification state
[._.]/ Adam Eivyf112c1ae0963
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2b7c0a8cf2..272ad8c35f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,5 +9,6 @@- **Stopping Series Autopilot now stops the active AI run.** Direct arc, episode, foundation, correction, and fallback runs publish their concrete run ids to the conductor, so Stop no longer waits for a long provider call to finish. Runs History also exposes Stop for active rows.- **Runs History safely displays structured model output.** Prompt and output endpoints are read as plain text, preventing valid JSON completions from crashing React when a run is expanded.- **Arc auto-resolve keeps corrections field-scoped and within storage limits.** A resolver fixing one synopsis now omits unrelated volume fields instead of paraphrasing them, and its prompt carries explicit headroom below every persisted arc/volume string cap so a well-intended rewrite cannot be silently clipped into the next verification failure.+- **Arc verification preserves its best demonstrated draft.** Any auto-resolve pass that raises the total blocking-finding count now pauses immediately and restores the lowest-blocker arc snapshot seen in that gate, even when the verifier describes the added problems as newly surfaced findings. Divergence and max-round exits likewise return the best verified state instead of whichever rewrite happened to run last.- **Continuing a video carries its prompt forward.** Continuing or extending a clip we generated now prefills the Video Gen prompt (and negative prompt) with the one that produced the source, instead of dropping you into an empty box. This covers both entry points: the **Continue** action on a video card/lightbox, and picking a prior render in Extend mode. Text you typed yourself is never overwritten — only a blank box or a value an earlier pick filled — and a clip we didn't generate (an import, or a legacy render with no stored prompt) leaves the field alone rather than clearing it. The style preset is dropped along with the prefill, since history stores the already-composed prompt and re-applying a preset would prefix it twice.- **Subscription Usage cards now lay out in four quadrants.** The provider quota grid orders Claude, Antigravity, Codex, Grok — and because Codex and Grok typically report only a single weekly meter, they now share one grid cell stacked vertically instead of each stretching to a full-height card. Cards render at their natural height, so the Image Gen card floats into the fourth quadrant and the whole section fits above the fold on desktop.diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 9cebe610a8..da360aea3a 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -33,7 +33,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe', '74d6c26548660d85fc345b2099c63b6c', '648e11352cd1565aee490de1f662bef0'],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c'],'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],- 'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],+ 'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],@@ -63,7 +63,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590','pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d',+ 'pipeline-arc-resolve.md': '96f73a7e90526d65ef2bb100fb1cd4bf','pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8','pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex c58760674c..e10966b641 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -293,24 +293,52 @@ const DEFAULT_ID_PREFIX = Object.freeze({export const isStr = (v) => typeof v === 'string';export const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');+// Smallest share of the budget a sentence-boundary cut may keep. A cut that+// lands above this wins over a mid-sentence clip; below it, gutting the record+// costs more than the ragged edge does.+//+// This was 0.6, which rejected a valid sentence break at 53% of a field's budget+// and fell through to a nearly-at-cap whole-word fragment. The next verification+// round then flagged the sanitizer-authored incomplete sentence, and every+// over-cap replacement reproduced it. A single-sentence field (logline, ending+// hook) is the common case: its first terminator is often its ONLY one, so a+// floor near the top of the budget rejects the clean cut it was meant to prefer.+const SENTENCE_CUT_FLOOR = 0.3;++// A sentence terminator that actually ENDS a sentence: `.`/`!`/`?` plus any+// closing quote or bracket, and then either whitespace or the end of the window.+// Requiring that lookahead is what keeps "Dr. Vey" and "3.5" from reading as+// breaks; allowing `$` is what lets a terminator sitting flush against the+// budget edge count, which `lastIndexOf('. ')` missed because it demanded a+// trailing space that the slice had already cut off.+const SENTENCE_END_RE = /[.!?]["'’”)\]]*(?=\s|$)/g;+const COMMON_ABBREVIATION_RE = /\b(?:dr|etc|jr|mr|mrs|ms|prof|sr|st|vs)\.$/i;+// Boundary-aware cap for PROSE fields (loglines, synopses, ending hooks). A hard// `slice(0, max)` clips mid-word ("...tracing the brand and"), which downstream// verify passes flag as "truncated mid-sentence" — and because a resolver then// regenerates an over-cap value that gets re-clipped the same way, the// verify→resolve loop never converges. When the text fits, it's returned// untouched. When it must be clipped, back off to the last sentence terminator-// (. ! ?) within the budget; if there's no sentence break in the last ~40% of-// the budget (one run-on sentence), fall back to the last whitespace boundary so-// the result still ends on a whole word. Never returns more than `max` chars.+// (. ! ?) within the budget, provided that cut keeps at least+// SENTENCE_CUT_FLOOR of it; otherwise (one run-on sentence, or a break so early+// that honoring it would gut the field) fall back to the last whitespace+// boundary so the result still ends on a whole word. Never returns more than+// `max` chars.export function trimToClause(v, max) {if (!isStr(v)) return '';const s = v.trim();if (s.length <= max) return s;const window = s.slice(0, max);- // Prefer the last sentence terminator, but only if it's not so early that we'd- // drop most of the content (keep at least ~60% of the budget).- const sentence = Math.max(window.lastIndexOf('. '), window.lastIndexOf('! '), window.lastIndexOf('? '));- if (sentence >= Math.floor(max * 0.6)) return window.slice(0, sentence + 1).trim();+ // Prefer the last real sentence terminator in the window. `end` is the cut+ // point (exclusive) so trailing quotes/brackets ride along with the period.+ let end = -1;+ SENTENCE_END_RE.lastIndex = 0;+ for (let m = SENTENCE_END_RE.exec(window); m; m = SENTENCE_END_RE.exec(window)) {+ if (m[0][0] === '.' && COMMON_ABBREVIATION_RE.test(window.slice(0, m.index + 1))) continue;+ end = m.index + m[0].length;+ }+ if (end >= Math.floor(max * SENTENCE_CUT_FLOOR)) return window.slice(0, end).trim();// No usable sentence break — clip on the last whole word instead of mid-word.const space = window.lastIndexOf(' ');return (space > 0 ? window.slice(0, space) : window).trim();@@ -1463,5 +1491,3 @@ export function mergeExtractedBible(existing, incoming, kind, {return existing.sort((a, b) => keyOf(a).localeCompare(keyOf(b)));}--diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 3b514c186d..8062602d02 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -1492,13 +1492,32 @@ describe('storyBible — trimToClause (boundary-aware prose cap)', () => {expect(trimToClause(42, 50)).toBe('');});- it('clips at a sentence boundary when one falls in the last ~40% of the budget', () => {+ it('clips at a sentence boundary when it preserves a meaningful share of the budget', () => {const text = 'First full sentence about the arc here. And then a second clause runs on well past the budget.';const out = trimToClause(text, 50);expect(out).toBe('First full sentence about the arc here.');expect(out.length).toBeLessThanOrEqual(50);});+ it('prefers the only complete sentence at 53% over a near-cap fragment', () => {+ const complete = `${'word '.repeat(52)}done.`; // 265 chars+ const tail = ` ${'continuation '.repeat(30)}`;+ const out = trimToClause(complete + tail, 500);+ expect(out).toBe(complete);+ expect(out.endsWith('.')).toBe(true);+ });++ it('does not treat abbreviations or decimals as sentence endings', () => {+ const text = `Dr. Example measured 3.5 units before the actual stop. ${'tail '.repeat(20)}`;+ const out = trimToClause(text, 70);+ expect(out).toBe('Dr. Example measured 3.5 units before the actual stop.');+ });++ it('keeps closing quotes and brackets attached to the sentence', () => {+ const text = `The operator said, "Stop now." ${'tail '.repeat(20)}`;+ expect(trimToClause(text, 50)).toBe('The operator said, "Stop now."');+ });+it('never clips mid-word — falls back to a whole-word boundary on a run-on', () => {// No sentence terminator within budget → must still end on a complete word,// not "...tracing the brand an".diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 728a915432..4adbe7668c 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -1922,6 +1922,10 @@ describe('autopilot conductor', () => {// Bailed at round 3 — NOT all 6 rounds (the whole point: budget saved).expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(+ seriesId,+ await arcSpies.snapshotArcState.mock.results[0].value,+ );const series = await seriesSvc.getSeries(seriesId);expect(series.autopilot?.status).toBe('paused');// Persisted through sanitizeAutopilot so the resume banner survives a reload.@@ -2018,16 +2022,17 @@ describe('autopilot conductor', () => {expect(last?.residualFindings).toEqual([restatements[0]]);});- it('keeps a round that closed what it targeted, even when new findings surface', async () => {- // Guard against the over-strict rollback: this round DID clear the finding- // it was handed, and the two that follow were latent underneath. Reverting- // it would throw away real progress, so the loop keeps the edits and falls- // through to the existing divergence guard when it stops improving.+ it('rolls back blocker-count growth even when the resolver closed its targeted finding', async () => {+ // Finding identity is not a safe acceptance gate: a rewrite can close the+ // one finding it was handed while exposing two different blockers and still+ // leave the draft operationally worse. Preserve the demonstrated lower-count+ // state and let a human decide whether the latent trade is worthwhile.const first = { severity: 'high', problem: 'first eclipse staged twice', location: 'V1' };const latent = [{ severity: 'high', problem: 'mentor subplot never pays off', location: 'V3' },{ severity: 'high', problem: 'finale hook is unresolved', location: 'V4' },];+ arcSpies.verifyArc.mockReset();arcSpies.verifyArc.mockImplementationOnce(async () => ({ issues: [first] })).mockImplementationOnce(async () => ({ issues: latent }))@@ -2036,10 +2041,43 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });await waitFor(runFinished(seriesId));- expect(arcSpies.restoreArcState).not.toHaveBeenCalled();+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(+ seriesId,+ await arcSpies.snapshotArcState.mock.results[0].value,+ );const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;- expect(last?.pauseKind).toBe('divergence');- expect(last?.residualFindings).toEqual(latent);+ expect(last?.pauseKind).toBe('regression');+ expect(last?.residualFindings).toEqual([first]);+ });++ it('restores the best verified snapshot in a 4 → 2 → 4 regression', async () => {+ const holes = (n, prefix) => Array.from({ length: n }, (_, i) => ({+ severity: 'high', problem: `${prefix} ${i}`, location: `V${i + 1}`,+ }));+ const rounds = [holes(4, 'initial'), holes(2, 'best'), holes(4, 'regressed'), holes(5, 'never reached')];+ arcSpies.verifyArc.mockReset();+ rounds.forEach((result) => arcSpies.verifyArc.mockImplementationOnce(async () => ({ issues: result })));+ const initialSnapshot = { marker: 'initial', arc: null, seasons: [], episodes: [] };+ const bestSnapshot = { marker: 'best', arc: null, seasons: [], episodes: [] };+ arcSpies.snapshotArcState+ .mockImplementationOnce(async () => initialSnapshot)+ .mockImplementationOnce(async () => bestSnapshot);++ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 12 });+ await waitFor(runFinished(seriesId));++ // The first increase stops the loop; the 5-blocker round is never spent.+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(2);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.pauseKind).toBe('regression');+ expect(last?.reason).toMatch(/best verified 2-finding state/);+ expect(last?.residualFindings).toEqual(rounds[1]);});it('a default-cap arc run is unaffected by the divergence guard (maxRounds still wins)', async () => {@@ -2054,6 +2092,10 @@ describe('autopilot conductor', () => {expect(last?.type).toBe('paused');expect(last?.pauseKind).toBe('maxRounds');expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(+ seriesId,+ await arcSpies.snapshotArcState.mock.results[0].value,+ );});it('a per-run override beats the persisted maxArcVerifyRounds setting', async () => {diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 8372f4ea7e..e2e0f60c66 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -22,7 +22,7 @@ import { MAX_ARC_VERIFY_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_FOUNDATION_ROUNDimport {CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,divergencePauseReason, foundationPauseReason, foundationDivergenceReason,- isResolveRegression, regressionPauseReason,+ regressionPauseReason,} from './convergence.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';import { requiredScriptStages, textReady } from './stepResolver.js';@@ -57,6 +57,12 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})}let convergence = { best: null, sinceBest: 0 };let changed = false;+ // Lowest verified blocker set seen in this gate, paired with the exact arc /+ // volume / planning-synopsis state that produced it. A later resolver is not+ // allowed to make this demonstrated best state worse: blocker-count growth+ // pauses immediately and restores this snapshot, even when the verifier+ // describes the new set as wholly latent findings.+ let bestVerified = null;// The findings the previous round's auto-resolve was handed, plus the state of// the arc just before it ran — the two halves the regression guard below needs// to decide whether that round earned its edits.@@ -109,37 +115,47 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})}return {};}- // Regression guard: the previous round's resolve came back with MORE- // blocking findings than it was handed and still hadn't closed them — its- // rewrite damaged the arc. Put the pre-resolve state back and pause on the- // residual the user actually had, rather than committing the worse arc and- // pausing on that (the shape observed on the 2026-08-09 divergence pause,- // where 1 blocking finding became 3 and then 5). Checked BEFORE the- // maxRounds/divergence exits so the rollback happens whichever pause the- // round would otherwise land on.- if (lastResolve && isResolveRegression(lastResolve.blocking, blocking)) {- const rollback = await restoreArcState(seriesId, lastResolve.snapshot);+ // Monotonic regression guard: a resolver candidate that increases the+ // TOTAL blocker count is operationally worse even when it closed the exact+ // finding it was handed and exposed different latent defects. Restore the+ // best verified state, not merely the immediately previous state; otherwise+ // a 4 → 2 → 4 → 5 run pauses on 4 and discards the demonstrated 2-blocker+ // draft. Checked before maxRounds/divergence so no worse baseline survives.+ if (lastResolve && blocking.length > lastResolve.blocking.length) {+ const rollbackTarget = bestVerified || lastResolve;+ const rollback = await restoreArcState(seriesId, rollbackTarget.snapshot);broadcast(seriesId, {type: 'resolve:rollback', scope: 'arc', round,before: lastResolve.blocking.length, after: blocking.length,+ best: rollbackTarget.blocking.length,reverted: rollback.restored,episodesReverted: rollback.episodesRestored,});return {pause: true,pauseKind: 'regression',- reason: regressionPauseReason('arc', lastResolve.blocking.length, blocking.length),- residual: lastResolve.blocking,+ reason: regressionPauseReason(+ 'arc',+ lastResolve.blocking.length,+ blocking.length,+ rollbackTarget.blocking.length,+ ),+ residual: rollbackTarget.blocking,};}+ const isNewBest = !bestVerified || blocking.length < bestVerified.blocking.length;if (round === maxRounds) {- return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };+ if (!isNewBest && bestVerified) await restoreArcState(seriesId, bestVerified.snapshot);+ const residual = !isNewBest && bestVerified ? bestVerified.blocking : blocking;+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, residual.length), residual };}// Divergence guard (#1571): if the resolve passes stop reducing blocking// findings, bail now rather than burning the remaining rounds + budget.convergence = trackConvergence(convergence, blocking.length);if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {- return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('arc', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };+ if (!isNewBest && bestVerified) await restoreArcState(seriesId, bestVerified.snapshot);+ const residual = !isNewBest && bestVerified ? bestVerified.blocking : blocking;+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('arc', residual.length, DIVERGENCE_PATIENCE), residual };}if (record.cancelRequested) return { canceled: true };// resolveVerifyIssues bills another action — recheck the budget so a single@@ -147,8 +163,10 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})const beforeResolve = await budgetPause();if (beforeResolve) return beforeResolve;// Snapshot before the rewrite lands (two record reads, no LLM spend) so the- // regression guard at the top of the next round can undo it.+ // regression guard at the top of the next round can undo it. A strictly+ // lower blocker count also promotes this snapshot to the gate-wide best.const snapshot = await snapshotArcState(seriesId);+ if (isNewBest) bestVerified = { blocking, snapshot };const resolved = await resolveVerifyIssues(seriesId, {findings: blocking,...providerOverrideOpts(record),diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.jsindex 22afad7332..d88e74c3cb 100644--- a/server/services/pipeline/seriesAutopilot/convergence.js+++ b/server/services/pipeline/seriesAutopilot/convergence.js@@ -209,11 +209,11 @@ export function isResolveRegression(before, after) {// both "ran out of rounds" and "stopped converging": the state the user is being// handed is the one from BEFORE the round, and saying so is the difference// between a trustworthy pause and an unexplained rewind.-export function regressionPauseReason(gate, beforeCount, afterCount) {+export function regressionPauseReason(gate, beforeCount, afterCount, bestCount = beforeCount) {const { label, fix } = PAUSE_GATES[gate];return `${label} auto-resolve made the draft worse — the round it ran on ${beforeCount} blocking finding(s) `- + `came back with ${afterCount} and still hadn't closed what it was given, so its edits were reverted. `- + `Paused for review with the original ${beforeCount} finding(s). ${fix}, then resume.`;+ + `came back with ${afterCount}, so its edits were reverted regardless of how the verifier reworded the findings. `+ + `Paused for review with the best verified ${bestCount}-finding state from this gate. ${fix}, then resume.`;}// Foundation gate pause reasons (#2176) — the gate converges on a WEIGHTED