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: keep verified exact arc repairs
[._.]/ Adam Eivy0b01475dc576
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cf64a4b64c..d4786c528a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,7 +20,7 @@- **Legacy canon prompts can be promoted into their missing description fields.** Universe expansion and promotion historically persisted image-ready `prompt` text while leaving the canonical `physicalDescription`/`description` blank, so the Cast/Places/Objects tabs and readiness gate disagreed with the renderer. A deterministic fill-blanks-only API now copies that already-authored text without an LLM call, preserving locks, IDs, kinds, prompts, and every existing asset.- **Arc verification can now repair the per-character milestones it judges.** The verifier already read canonical per-character arcs, but its resolver could only edit the series arc, volumes, and issue synopses, so a contradiction in a character transition was impossible to close and repeated retries rewrote unrelated records instead. Finding-keyed character-arc patches now preserve character and transition IDs, merge only named fields, participate in regression rollback, and migrate existing prompt installations to the sparse contract.-- **Arc verification repairs long prose without rewriting the whole plan around one sentence.** A localized finding inside a volume synopsis previously forced the model to return the entire field, so a one-clause correction could rewrite more than 8,000 characters, introduce unrelated continuity failures, and be clipped at the storage limit. The resolver now emits bounded exact-match replacements for arc summaries, protagonist arcs, volume synopses, and ending hooks; missing, ambiguous, wholesale-long-field, and over-limit patches fail closed while legacy customized prompts keep their existing contract. Each prompt carries measured current/max/remaining field lengths so the replacement fits on its first attempt, and a rejected exact-only response is recorded as a no-op and retried without paying an independent judge to reread an unchanged plan or misclassifying latent findings as repair regressions. A graceful Pause requested during arc convergence now lands immediately after the active independent judgment instead of silently dispatching another repair/judge pair.+- **Arc verification repairs long prose without rewriting the whole plan around one sentence.** A localized finding inside a volume synopsis previously forced the model to return the entire field, so a one-clause correction could rewrite more than 8,000 characters, introduce unrelated continuity failures, and be clipped at the storage limit. The resolver now emits bounded exact-match replacements for arc summaries, protagonist arcs, volume synopses, and ending hooks; missing, ambiguous, wholesale-long-field, and over-limit patches fail closed while legacy customized prompts keep their existing contract. Each prompt carries measured current/max/remaining field lengths so the replacement fits on its first attempt, and a rejected exact-only response is recorded as a no-op and retried without paying an independent judge to reread an unchanged plan. Because these patches are finding-keyed and bounded, an exhaustive later judge may expose unrelated latent blockers without the guard falsely blaming them on the patch and rewinding a correction that closed its target; legacy whole-field resolvers retain the stricter total-count guard. A graceful Pause requested during arc convergence now lands immediately after the active independent judgment instead of silently dispatching another repair/judge pair.- **Completed CoS agents no longer strand a worktree because of their own completion marker.** The `.agent-done` sentinel is consumed before worktree cleanup, but Git still reported the untracked file as ordinary authored work and the safety gate preserved the otherwise-clean checkout with a high-priority warning. Cleanup now ignores only that runtime marker: sentinel-only trees are removed normally, while any real source change still preserves the worktree and is named in the warning.diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 30de78e251..3158fc0322 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -734,6 +734,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {return {series: resolvedSeries,applied,+ patchMode: exactTextMode ? 'exact-text-v1' : null,rejectedExactEdits,notes,findings,diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex ce5b37b045..3b7b1b6243 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -1663,6 +1663,32 @@ describe('isResolveRegression (pure resolve-round damage check)', () => {});});+describe('isTargetedPatchRegression (bounded exact-text damage check)', () => {+ const { isTargetedPatchRegression } = autopilot;+ const f = (problem, location = 'V1', severity = 'medium') => ({ severity, location, problem });++ it('keeps a sparse patch that closed its target when an exhaustive judge exposes unrelated latent blockers', () => {+ expect(isTargetedPatchRegression(+ [f('the recovery order expires before the mandatory rest completes')],+ [+ f('the destination tow has no established local route', 'V3', 'high'),+ f('the inherited seal kit has no supplier setup', 'V2'),+ ],+ )).toBe(false);+ });++ it('rejects a sparse patch when its target survives alongside new blockers or returns more severe', () => {+ const target = f('the recovery order expires before the mandatory rest completes');+ expect(isTargetedPatchRegression([target], [+ target,+ f('the inherited seal kit has no supplier setup', 'V2'),+ ])).toBe(true);+ expect(isTargetedPatchRegression([target], [+ f('mandatory recovery outlasts the resource order', 'V1', 'high'),+ ])).toBe(true);+ });+});+describe('isBlockingSetRegression (arc rollback ordering)', () => {const { isBlockingSetRegression } = autopilot;const f = (severity, problem) => ({ severity, problem, location: 'V1' });@@ -2452,6 +2478,52 @@ describe('autopilot conductor', () => {expect(last?.pauseKind).toBe('maxRounds');});+ it('keeps a bounded exact patch when a later judge exposes unrelated latent blockers', async () => {+ const target = { severity: 'medium', problem: 'the recovery order expires before the mandatory rest completes', location: 'V1' };+ const latent = [+ { severity: 'high', problem: 'the destination tow has no established local route', location: 'V3' },+ { severity: 'medium', problem: 'the inherited seal kit has no supplier setup', location: 'V2' },+ ];+ arcSpies.verifyArc+ .mockImplementationOnce(async () => ({ issues: [target] }))+ .mockImplementationOnce(async () => ({ issues: latent }))+ .mockImplementationOnce(async () => ({ issues: [] }));+ arcSpies.resolveVerifyIssues+ .mockResolvedValueOnce({ applied: true, patchMode: 'exact-text-v1', runId: 'exact-target' })+ .mockResolvedValueOnce({ applied: true, patchMode: 'exact-text-v1', runId: 'exact-latent' });+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 5 });+ await waitFor(runFinished(seriesId));++ expect(arcSpies.restoreArcState).not.toHaveBeenCalled();+ expect(arcSpies.resolveVerifyIssues.mock.calls[1][1].findings).toEqual(latent);+ expect(recordModelOutcome).toHaveBeenCalledWith('exact-target', expect.objectContaining({+ outcome: 'accepted', scoreBefore: -1, scoreAfter: 0,+ }));+ });++ it('does not rewind exact target closure at the round cap when the later judge is more exhaustive', async () => {+ const target = { severity: 'medium', problem: 'the recovery order expires before the mandatory rest completes', location: 'V1' };+ const latent = [+ { severity: 'high', problem: 'the destination tow has no established local route', location: 'V3' },+ { severity: 'medium', problem: 'the inherited seal kit has no supplier setup', location: 'V2' },+ ];+ arcSpies.verifyArc+ .mockImplementationOnce(async () => ({ issues: [target] }))+ .mockImplementationOnce(async () => ({ issues: latent }));+ arcSpies.resolveVerifyIssues+ .mockResolvedValueOnce({ applied: true, patchMode: 'exact-text-v1', runId: 'exact-before-cap' });+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 2 });+ await waitFor(runFinished(seriesId));++ expect(arcSpies.restoreArcState).not.toHaveBeenCalled();+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last).toMatchObject({+ type: 'paused', pauseKind: 'maxRounds', residualFindings: latent,+ });+ });+it('reverts an arc-resolve round that introduced blocking findings and pauses on the pre-round residual', async () => {// The 2026-08-09 non-convergence, replayed: the loop hands the resolver ONE// blocking finding and gets 3 back, then 5 — with the original stilldiff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 54ed345231..34ea7e5e31 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -28,6 +28,7 @@ import {CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,divergencePauseReason, foundationPauseReason, foundationDivergenceReason,foundationRepairMissed, regressionPauseReason, sameFinding, containsFinding, isBlockingSetRegression,+ isTargetedPatchRegression,isIsolatedFixSafe,} from './convergence.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';@@ -97,13 +98,20 @@ const arcQualityScore = (blocking) => (blocking.length === 0 ? 0 : -blocking.lenasync function recordArcResolveOutcome(candidate, record, { outcome, after, target }) {const runIds = Array.isArray(candidate?.runIds) ? candidate.runIds : [];if (runIds.length === 0) return;+ // A bounded exact patch is judged on the finding(s) it was authorized to+ // touch. An exhaustive follow-up may expose unrelated latent blockers, but+ // those are new work for the next round—not a negative quality delta owned by+ // this provider response. Legacy whole-field rewrites still own the full set.+ const ownedAfter = candidate?.exactTextMode+ ? candidate.blocking.filter((prior) => after.some((current) => sameFinding(prior, current)))+ : after;await Promise.all(runIds.map((runId) => recordModelOutcome(runId, {role: 'creative',stage: record.currentStep || 'verifyArc',outcome,target,scoreBefore: arcQualityScore(candidate.blocking),- scoreAfter: arcQualityScore(after),+ scoreAfter: arcQualityScore(ownedAfter),}).catch(() => {})));// The same checkpoint can remain `lastResolve` for comparison after its// verdict. Consume its evidence once so later seeded/re-confirmation rounds@@ -346,11 +354,11 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc};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.+ // Best verified checkpoint seen in this gate, paired with the exact arc /+ // volume / planning-synopsis state that produced it. Legacy whole-field+ // candidates are ordered by total blockers. A bounded exact patch that closes+ // its authorized targets may promote a larger newly exposed set instead—the+ // verifier's earlier smaller set was incomplete, not a better draft.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@@ -398,16 +406,17 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc}return {};}- // 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. At an equal count, a worse severity mix is also a regression: two- // mediums becoming one medium plus one high is not a safe tie. Checked- // before maxRounds/divergence so no worse baseline survives.+ // Legacy whole-field candidates keep the strict total-count ordering that+ // prevents runaway rewrites. Finding-keyed exact patches own only their+ // targets: a larger set of unrelated findings can be an exhaustive judge+ // exposing pre-existing work, so only a surviving/escalated target proves+ // that bounded patch regressed. Checked before maxRounds/divergence so a+ // demonstrated regression never becomes the live checkpoint.// Reverting is unconditional; PAUSING is not — see the corrective pass below.- if (lastResolve && isBlockingSetRegression(lastResolve.blocking, blocking)) {+ const regressed = lastResolve && (lastResolve.exactTextMode+ ? isTargetedPatchRegression(lastResolve.blocking, blocking)+ : isBlockingSetRegression(lastResolve.blocking, blocking));+ if (regressed) {await recordArcResolveOutcome(lastResolve, record, { outcome: 'rejected', after: blocking, target: scope });const rollbackTarget = bestVerified || lastResolve;const rollback = await restoreArcState(seriesId, rollbackTarget.snapshot);@@ -471,7 +480,11 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc// The restored state is what the retry has to beat, so the next round// compares against ITS count — not the rejected candidate's, which// would let the retry regress back to the discarded draft for free.- lastResolve = { ...rollbackTarget, runIds: arcResolveRunIds(retried) };+ lastResolve = {+ ...rollbackTarget,+ runIds: arcResolveRunIds(retried),+ exactTextMode: retried?.patchMode === 'exact-text-v1',+ };broadcast(seriesId, {type: 'resolve:round', scope, round, retry: true, episodesEdited: editedCount(retried),});@@ -533,19 +546,17 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDiscresidual: blocking,};}- // Equal-count drafts may still represent real causal progress when their- // severity mix is not worse: a resolver can close broad structural findings- // and expose the same number of narrower handoff problems. Treat that latest- // verified tie as the checkpoint so a later stall never rewinds those- // repairs. Count growth and severity escalation are rejected above.- const isNewBest = !bestVerified || blocking.length <= bestVerified.blocking.length;- // Shared exit for the two bounded stops below: rewind to the checkpoint when- // the round they landed on is worse than it, reporting the discarded set the- // same way the regression guard does. Defensive rather than reachable today- // — that guard returns on ANY count growth, so a round that survives to here- // is never worse than the best and `isNewBest` always holds. It stays because- // it is the correct behavior if the guard order ever changes, and one shared- // helper is how both exits keep agreeing on what a rewind owes the user.+ // A bounded patch that closed everything it was authorized to touch is a+ // new checkpoint even when the verifier now reports MORE unrelated work.+ // Rewinding to an earlier low count would merely restore the less exhaustive+ // judge's snapshot and throw away a verified causal correction.+ const exactTargetsClosed = lastResolve?.exactTextMode === true+ && !lastResolve.blocking.some((prior) => blocking.some((current) => sameFinding(prior, current)));+ const isNewBest = exactTargetsClosed || !bestVerified || blocking.length <= bestVerified.blocking.length;+ // Shared exit for the two bounded stops below: rewind only when the current+ // round is genuinely worse than the accepted checkpoint. Exact target+ // closure above promotes its current state, so a newly exhaustive finding+ // set cannot make the cap/divergence exit undo that verified repair.const rewind = async () => {if (isNewBest || !bestVerified) return { residual: blocking, discarded: [] };await restoreArcState(seriesId, bestVerified.snapshot);@@ -598,7 +609,12 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisccontinue;}changed = true;- lastResolve = { blocking, snapshot, runIds: arcResolveRunIds(resolved) };+ lastResolve = {+ blocking,+ snapshot,+ runIds: arcResolveRunIds(resolved),+ exactTextMode: resolved?.patchMode === 'exact-text-v1',+ };broadcast(seriesId, {type: 'resolve:round', scope, round, episodesEdited: editedCount(resolved),});diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.jsindex 1b823496fc..e3c5a8f6e4 100644--- a/server/services/pipeline/seriesAutopilot/convergence.js+++ b/server/services/pipeline/seriesAutopilot/convergence.js@@ -213,6 +213,25 @@ export function isResolveRegression(before, after) {return targeted.some((t) => containsFinding(current, t));}+const FINDING_SEVERITY_RANK = Object.freeze({ low: 1, medium: 2, high: 3 });++/**+ * Regression test for a bounded, finding-keyed exact-text patch. Unlike a+ * legacy whole-field rewrite, a sparse patch that closes its target may safely+ * expose unrelated latent findings elsewhere in the already-authored plan.+ * Revert only when a targeted finding survives while the set grows, or when+ * that same finding returns at a higher severity.+ */+export function isTargetedPatchRegression(before, after) {+ const targeted = Array.isArray(before) ? before : [];+ const current = Array.isArray(after) ? after : [];+ if (isResolveRegression(targeted, current)) return true;+ return targeted.some((prior) => current.some((candidate) => (+ sameFinding(prior, candidate)+ && (FINDING_SEVERITY_RANK[candidate?.severity] || 0) > (FINDING_SEVERITY_RANK[prior?.severity] || 0)+ )));+}+// The arc rollback guard's operational ordering. Total blockers remain the// primary signal: accepting a larger set is what caused the original runaway// repair loop. When the totals tie, severity is the tiebreaker so a resolver