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
restrict arc-verify rollback to the episode synopses the resolver reported writing
[._.]/ Adam Eivy22f75df067b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b65813f2c6..5092e64661 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -111,3 +111,4 @@- **The foundation gate now remembers every repair it rejected for a dimension, not just the last one.** Two rollback-evidence models were living side by side in one file: the arc gate accumulates every discarded set for its whole lifetime and carries it across a pause, while the foundation gate kept a single most-recent rejection per dimension — so a dimension that rejected two different repairs handed the third evidence of only the second, and the editor was free to re-author the first. Same evidence loss, one level down, and a reader had every reason to assume the two behaved alike. Both gates now ride one shared per-key bank: the arc gate banks a flat history as before, the foundation gate banks one per dimension, and each rejected set is recorded at the moment it is thrown away rather than when the next attempt happens to read it — so an unverified restore, which pauses without ever reaching a retry, still contributes its evidence. An accepted repair no longer wipes the dimension's history (a candidate the gate rejected is still a candidate it rejected; only the stale "this failed, try another angle" strategy note is cleared), and the evidence is filtered against the gap the call is actually being asked to close, so no editor is told to both fix and avoid the same thing. It survives the pause too, as a per-dimension `foundationDiscardedFindings` on the paused marker that a resume seeds its bank from — a marker written before the field existed simply resumes with an empty bank, exactly as it does today.- **An "isolated" arc repair now has to actually be one small edit.** When arc verification's auto-resolve regresses twice on the same residual, the gate escalates to fixing one finding at a time — snapshot, resolve that finding alone, re-verify, keep the patch only if it closed its own target without growing the set. Isolating the *finding* never isolated the *edit*, though: every entry in a single-finding response trivially names that one finding, so the finding-keyed filter passed a whole-arc rewrite plus every volume, and each "isolated" attempt regressed exactly like the whole-set pass it had escalated from. On the run that surfaced this, both attempts started from the same verified 2-blocker checkpoint and came back with 4 and then 7, so the gate paused having retained nothing after four resolves and three verifications. The resolver now has an explicit isolated mode: the prompt is told the contract, and the server discards the candidate *before persistence* unless it is one causal patch — one owner record, one changed field (one exact-text replacement, one short scalar, or one existing character-transition patch). Echoed identity fields that match what is stored don't count as changes, and neither do edits the appliers would have dropped anyway. A rejected candidate costs its own resolve call and nothing else: there is no rewrite to roll back and no verification round billed to discover that it was worse. Coordinated cross-record repairs stay with the whole-set and corrective passes, and every existing guard — spine-only scope, the blocker-count rollback, the round limits, restoring the best verified snapshot — is untouched.- **A character-arc beat is no longer clipped mid-word, which was enough on its own to stall an arc verification.** The per-character arc fields — each transition's label and note, plus want, need, start state and end state — were capped with a hard slice, so an over-long value written by the arc auto-resolver ended wherever the character count ran out: one live series carried a beat that stopped at "...the four-minute crossing e". That path never sees the route's validator (the resolver writes through the service sanitizer directly), and the next verification round reads the fragment as an authoring gap it can't close, which is precisely the verify → resolve loop `trimToClause` was introduced to break for arc summaries, loglines and ending hooks. Those fields now use the same boundary-aware cap: an over-cap value backs off to the last complete sentence, or to the last whole word when there is no sentence break to find. `characterName` keeps its hard trim, because it is an identity string matched against the canon cast rather than prose.+- **An arc rollback now reverts only what the round it is undoing actually wrote.** When arc verification rejects a regressive auto-resolve, it restores the state it snapshotted before that round ran — and it decided what to put back by diffing the store against that snapshot, treating *every* difference as the round's own work. An episode synopsis that changed for any other reason while the verification was running (the verify plus its per-volume passes are several provider calls long) was therefore reverted by a round that never touched it. The arc-spine gate made that plainly visible: its resolver may not edit episodes at all, so a paused run reported `resolve:round episodesEdited: 0` immediately followed by `resolve:rollback episodesReverted: 1` — a write nothing in that round could have authored, undone anyway. The resolver now returns an exact mutation manifest — the episodes it wrote, with the value it left on each — and the rollback restores an episode's `idea` stage only when that episode is on the manifest *and* the value the resolver wrote is still the one standing, so a later write on top of a resolver-owned episode is left alone too. A spine round's manifest is empty by construction, which is what makes its rollback arc-and-volume-only. Nothing else about the revert changed: the arc, character arcs and volume list still come back wholesale, and the episodes a restored volume list would otherwise strand are still re-pointed at their snapshot volume regardless of the manifest. The same manifest now feeds `episodesEdited`, which had been counting the applier's *skipped* entries — a locked stage, an unmatched episode number, a failed write — as edits, so the two telemetry fields can no longer describe different sets.diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 116406210a..2669501199 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1388,6 +1388,11 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(out.episodesResolved[0]).toMatchObject({ issueId: issue.id, number: fresh.number, clearedBeats: false });const updated = await issuesSvc.getIssue(issue.id);expect(updated.stages.idea.input).toBe('corrected — the Atrium is NOT convened here');+ // The entry doubles as the rollback's mutation manifest: it reports the+ // value this call actually left standing.+ expect(planner.resolvedEpisodeEdits(out)).toEqual([+ { issueId: issue.id, idea: { input: updated.stages.idea.input, output: '', status: updated.stages.idea.status } },+ ]);});// The pre-episode arc-spine gate verifies an episode-EMPTY plan (#3789). A@@ -1970,6 +1975,75 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbexpect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('e1 planning synopsis');});+ // The rollback used to treat ANY difference from the snapshot as the round's+ // own work, so an episode synopsis written while the verification was running+ // was reverted by a round that never touched it — observed as an arc-SPINE+ // gate (whose resolver may not edit episodes at all) reporting+ // `resolve:round episodesEdited: 0` followed by `resolve:rollback+ // episodesReverted: 1`. The manifest is what makes ownership provable.+ describe('restores only the episodes the resolve round is on record as writing', () => {+ // The damage every case below shares: a rewritten arc, a minted volume that+ // took an episode off its own, and a synopsis rewrite on e1.+ async function regressiveRound({ s, v1, v2, e1 }) {+ const minted = await seasonsSvc.createSeason(s.id, { title: 'Volume 1', synopsis: 'duplicate', episodeCountTarget: 2 });+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'rewritten logline', summary: 'rewritten summary' },+ seasons: [{ ...v1, synopsis: 'rewritten v1' }, v2, minted],+ });+ await issuesSvc.updateIssue(e1.id, { seasonId: minted.id });+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'resolver rewrote e1', output: '', status: 'empty' });+ return { minted, e1Edit: { issueId: e1.id, idea: { input: 'resolver rewrote e1', output: '', status: 'empty' } } };+ }++ it('reverts its own episode write and the volume it drove, and keeps an unrelated one', async () => {+ const seed = await seedArc();+ const { s, v2, e1, e2 } = seed;+ const snapshot = await planner.snapshotArcState(s.id);+ const { e1Edit } = await regressiveRound(seed);+ // Lands between the snapshot and the rollback, from outside this round.+ await issuesSvc.updateStage(e2.id, 'idea', { input: 'edited elsewhere mid-verify' });++ const result = await planner.restoreArcState(s.id, snapshot, { episodeEdits: [e1Edit] });+ expect(result).toMatchObject({ restored: true, episodesRestored: 1, reassignedIssueCount: 1 });++ const series = await seriesSvc.getSeries(s.id);+ expect(series.arc.logline).toBe('original logline');+ expect(series.seasons[0].synopsis).toBe('v1 synopsis');+ expect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('e1 planning synopsis');+ // The minted volume is gone, so its episode still has to come back with it.+ expect((await issuesSvc.getIssue(e1.id)).seasonId).toBe(seed.v1.id);+ expect((await issuesSvc.getIssue(e2.id)).stages.idea.input).toBe('edited elsewhere mid-verify');+ expect((await issuesSvc.getIssue(e2.id)).seasonId).toBe(v2.id);+ });++ it('leaves an episode it wrote alone once a later write lands on top of it', async () => {+ const seed = await seedArc();+ const { s, e1 } = seed;+ const snapshot = await planner.snapshotArcState(s.id);+ const { e1Edit } = await regressiveRound(seed);+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'a human kept editing after the resolver' });++ const result = await planner.restoreArcState(s.id, snapshot, { episodeEdits: [e1Edit] });+ expect(result).toMatchObject({ restored: true, episodesRestored: 0 });+ expect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('a human kept editing after the resolver');+ // The arc-level revert still happens — only the episode is off limits.+ expect((await seriesSvc.getSeries(s.id)).arc.logline).toBe('original logline');+ });++ it('restores no synopsis at all for an arc-spine round (empty manifest)', async () => {+ const seed = await seedArc();+ const { s, e1 } = seed;+ const snapshot = await planner.snapshotArcState(s.id);+ await regressiveRound(seed);++ const result = await planner.restoreArcState(s.id, snapshot, { episodeEdits: [] });+ expect(result).toMatchObject({ restored: true, episodesRestored: 0, reassignedIssueCount: 1 });+ expect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('resolver rewrote e1');+ expect((await seriesSvc.getSeries(s.id)).seasons.map((x) => x.id)).toEqual([seed.v1.id, seed.v2.id]);+ expect((await issuesSvc.getIssue(e1.id)).seasonId).toBe(seed.v1.id);+ });+ });+it('leaves a locked idea stage alone (the resolve pass never touched it)', async () => {const { s, e1 } = await seedArc();const snapshot = await planner.snapshotArcState(s.id);@@ -2031,6 +2105,25 @@ describe('arcPlanner — shapeEpisodeResolutions', () => {});});+describe('arcPlanner — resolvedEpisodeEdits (rollback mutation manifest)', () => {+ it('carries only the writes that landed, with the value they left', () => {+ expect(planner.resolvedEpisodeEdits({+ episodesResolved: [+ { issueId: 'iss-1', number: 1, idea: { input: 'rewritten', output: '', status: 'empty' } },+ { issueId: 'iss-2', number: 2, skipped: 'locked' },+ { issueId: 'iss-3', number: 3, skipped: 'write-failed' },+ { seasonNumber: 2, episodeNumber: 9, skipped: 'no-match' },+ ],+ })).toEqual([{ issueId: 'iss-1', idea: { input: 'rewritten', output: '', status: 'empty' } }]);+ });++ it('is empty for a round that reported nothing — including an arc-spine one', () => {+ expect(planner.resolvedEpisodeEdits({ applied: true, episodesResolved: [] })).toEqual([]);+ expect(planner.resolvedEpisodeEdits({ applied: false })).toEqual([]);+ expect(planner.resolvedEpisodeEdits(null)).toEqual([]);+ });+});+// Shared by every commitSeasonsWithRemap case below — they all commit a fresh// draft arc and vary only the seasons.const DRAFT_ARC = Object.freeze({ logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' });diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 6944569291..7c2b23cad0 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -931,8 +931,15 @@ export async function resolveVerifyIssues(seriesId, options = {}) {* that still encode the contradiction.** A locked `idea` stage is left untouched (the user froze it) and reported as- * skipped. Returns `[{ issueId, number, seasonNumber, clearedBeats, skipped }]`+ * skipped. Returns `[{ issueId, number, seasonNumber, clearedBeats, skipped, idea }]`* for the conductor to surface; never throws — a bad match is dropped, not fatal.+ *+ * `idea` is the stage AS THIS CALL LEFT IT, and it is what makes the entry a+ * mutation manifest rather than a report: rollback restores an episode only when+ * the resolver is on record as having written it AND the value it wrote is still+ * standing (see `restoreArcState`). A write that failed is reported skipped —+ * counting it as an applied edit told the gate a synopsis had changed when the+ * store still held the old one.*/export async function applyEpisodeResolutions(seriesId, series, episodes) {if (!Array.isArray(episodes) || episodes.length === 0) return [];@@ -956,14 +963,21 @@ export async function applyEpisodeResolutions(seriesId, series, episodes) {continue;}const hadBeats = !!(issue.stages?.idea?.output && issue.stages.idea.output.trim());- await updateStageWithLatest(issue.id, 'idea', (current) => (+ const written = await updateStageWithLatest(issue.id, 'idea', (current) => (hadBeats? { input: edit.synopsis, output: '', status: 'empty', errorMessage: '' }: { input: edit.synopsis })).catch((err) => {console.log(`⚠️ arc-resolve: episode ${edit.episodeNumber} synopsis edit failed: ${err.message}`);+ return null;+ });+ applied.push({+ issueId: issue.id,+ number: issue.number,+ seasonNumber: edit.seasonNumber,+ clearedBeats: hadBeats,+ ...(written ? { idea: ideaSnapshotOf(written.stage) } : { skipped: 'write-failed' }),});- applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, clearedBeats: hadBeats });}if (applied.length) {const fixed = applied.filter((a) => !a.skipped).length;@@ -982,6 +996,26 @@ const ideaSnapshotOf = (stage) => ({status: stage?.status ?? 'empty',});+const sameIdea = (a, b) => a.input === b.input && a.output === b.output && a.status === b.status;++/**+ * The episode-synopsis writes ONE resolve pass actually landed, as+ * `[{ issueId, idea }]` — the exact-mutation manifest a rollback needs so it can+ * tell its own round's edits from a write that arrived from somewhere else while+ * the verification was running. Derived from the applier's own report (an entry+ * carries `idea` only when the write went through), so the manifest cannot claim+ * an edit that never happened.+ *+ * Empty for an arc-spine round: that gate's resolver may not touch episodes at+ * all (`selectFindingKeyedEdits` discards them), which is exactly why a+ * spine-scope rollback must leave every episode `idea` field alone.+ */+export const resolvedEpisodeEdits = (resolved) => (Array.isArray(resolved?.episodesResolved)+ ? resolved.episodesResolved+ .filter((entry) => entry?.issueId && !entry.skipped && entry.idea)+ .map((entry) => ({ issueId: entry.issueId, idea: entry.idea }))+ : []);+// Every issue in the series, without per-stage run history: `listIssues` caps at// 1000 (a longer series would lose its tail from the snapshot, making those// episodes unrestorable) and carries history payloads this projection throws@@ -1028,18 +1062,35 @@ export async function snapshotArcState(seriesId) {* damage because a lock flipped mid-run would strand the user with the damage.* A locked `idea` stage IS skipped — the resolve pass never touched it.*+ * `options.episodeEdits` is the round's exact mutation manifest (see+ * `resolvedEpisodeEdits`): pass it and only those episodes' `idea` fields are+ * eligible, and only while the value the resolver wrote is still the one+ * standing. Everything else — including an unrelated synopsis edit that landed+ * while the verification ran — keeps whatever is in the store, because "differs+ * from the snapshot" was never proof the round owned the difference. An arc-spine+ * round always passes an empty manifest, so it can never restore an episode.+ * Omit it and every differing episode is restored (the pre-manifest behavior+ * foundation structure repair still relies on). Volume reassignment is NOT+ * manifest-gated either way: the volume list is being restored wholesale, so an+ * episode left pointing at a volume that is about to disappear would be stranded.+ ** Callers must re-verify after every resolve so they can distinguish a* regressive round from a good one. The arc convergence loop uses this to keep* its best verified checkpoint; foundation structure repair uses it to restore* the pre-repair plan when its bounded verify/correct pass is still blocked.* The manual `/arc/resolve` route remains an explicit unguarded user edit.*/-export async function restoreArcState(seriesId, snapshot) {+export async function restoreArcState(seriesId, snapshot, { episodeEdits = null } = {}) {if (!snapshot || snapshot.seriesId !== seriesId || !Array.isArray(snapshot.episodes)) {return { restored: false, episodesRestored: 0, reassignedIssueCount: 0 };}const issues = await listEpisodesForSnapshot(seriesId);const byId = new Map(issues.map((iss) => [iss.id, iss]));+ // What the round is on record as having written to each episode, or null when+ // the caller kept the pre-manifest "restore every difference" contract.+ const ownedIdea = Array.isArray(episodeEdits)+ ? new Map(episodeEdits.map((e) => [e.issueId, e.idea]))+ : null;const stageUpdates = [];const reassign = [];for (const snap of snapshot.episodes) {@@ -1050,9 +1101,14 @@ export async function restoreArcState(seriesId, snapshot) {if ((cur.seasonId ?? null) !== snap.seasonId) reassign.push(snap);if (cur.stages?.idea?.locked === true) continue;const idea = ideaSnapshotOf(cur.stages?.idea);- if (idea.input === snap.idea.input- && idea.output === snap.idea.output- && idea.status === snap.idea.status) continue;+ if (sameIdea(idea, snap.idea)) continue;+ if (ownedIdea) {+ const written = ownedIdea.get(snap.id);+ // Either the round never wrote this episode, or its write has since been+ // overwritten — in both cases what stands is someone else's, not the+ // regressive candidate this rollback is undoing.+ if (!written || !sameIdea(idea, written)) continue;+ }stageUpdates.push({issueId: snap.id,stageId: 'idea',diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex c3f9793ea9..88f40533db 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -2658,9 +2658,12 @@ describe('autopilot conductor', () => {// Only the first-attempt resolve snapshots; the corrective pass reuses the// checkpoint it was just rewound to rather than pinning the reverted draft.expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(1);+ // The resolver reported no episode writes, so the rollback is authorized to+ // restore none — the arc and volumes come back, every synopsis stays put.expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,+ { episodeEdits: [] },);// The corrective pass is handed the CHECKPOINT's findings (what the restored// plan actually has) plus the rejected attempt's own findings to steer away@@ -2966,9 +2969,10 @@ describe('autopilot conductor', () => {.mockImplementationOnce(async () => round(5, 2));// The round reports real work (the observed `resolve:round episodesEdited=1`)// — it edited episodes and STILL came back worse, which is the whole point.+ // The reported `idea` is the mutation manifest the rollback is restricted to.arcSpies.resolveVerifyIssues.mockImplementationOnce(async () => ({applied: true,- episodesResolved: [{ issueId: 'i1', number: 1 }],+ episodesResolved: [{ issueId: 'i1', number: 1, idea: { input: 'rewritten', output: '', status: 'empty' } }],}));const { seriesId } = await seedComplete();await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });@@ -2978,9 +2982,12 @@ describe('autopilot conductor', () => {// again with no retries left, so rounds 4-6 are never billed.expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ // Rolled back with the round's own episode write attached, so the restore+ // puts that synopsis back and leaves every other episode alone.expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,+ { episodeEdits: [{ issueId: 'i1', idea: { input: 'rewritten', output: '', status: 'empty' } }] },);const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');@@ -3014,6 +3021,7 @@ describe('autopilot conductor', () => {expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,+ { episodeEdits: [] },);const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');@@ -3053,7 +3061,7 @@ describe('autopilot conductor', () => {// (none here) moves the store on and forces a fresh one. The corrective pass// still rewinds to the checkpoint it already holds.expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(3);- expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot, { episodeEdits: [] });const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');expect(last?.reason).toMatch(/best verified 2-finding state/);@@ -3300,7 +3308,7 @@ describe('autopilot conductor', () => {const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');- expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot, { episodeEdits: [] });expect(last?.residualFindings).toEqual(rounds[0]);expect(last?.discardedFindings).toEqual(rounds[1]);});diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex c68250d107..027ff0a985 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -11,7 +11,7 @@ import { getSeries, AUTOPILOT_DISCARDED_MAX } from '../series.js';import { listIssues, getIssue, isStageReady } from '../issues.js';import {verifyArc, verifyVolume, resolveVerifyIssues, analyzeBeatContinuity, resolveBeatContinuity,- snapshotArcState, restoreArcState,+ snapshotArcState, restoreArcState, resolvedEpisodeEdits,} from '../arcPlanner.js';import {judgeFoundation, applyFoundationFix, establishCharacterFoundation, foundationGateStatus, foundationFixTarget,@@ -86,7 +86,11 @@ async function resolveArcFindings(seriesId, record, { findings, avoid, spineOnly}// Episode synopses one resolve pass actually rewrote, for the telemetry frames.-const editedCount = (resolved) => (Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0);+// Read off the same mutation manifest the rollback is driven by, so+// `episodesEdited` and `episodesReverted` can no longer describe different sets:+// counting every reported entry included the ones the applier SKIPPED (locked+// stage, no matching episode, failed write) as edits.+const editedCount = (resolved) => resolvedEpisodeEdits(resolved).length;// A resolver's provider run is only a TECHNICAL success until the next// independent arc verification decides whether its candidate remains in the@@ -235,6 +239,12 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b// capture an identical snapshot is pure I/O. Dropped after an accepted patch,// which is the only thing that moves the store on.let snapshot = null;+ // The episode synopses the resolver has REPORTED writing since that snapshot+ // was taken. A rejected attempt restores those and nothing else, so an episode+ // edit that arrives from elsewhere while the verification runs is not swept up+ // with the candidate being undone. Cleared alongside the snapshot: a restore+ // has already undone them, and an accepted patch keeps them.+ let ownedEdits = [];const blocking = () => standing?.blocking ?? baseline;for (const target of baseline) {if (attempts >= attemptsLeft) break;@@ -251,7 +261,10 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b// model-outcome record falls back to the gate's scope so a per-target// performance history is never keyed on an empty string.const targetLabel = typeof target.location === 'string' ? target.location : null;- if (!snapshot) snapshot = await snapshotArcState(seriesId);+ if (!snapshot) {+ snapshot = await snapshotArcState(seriesId);+ ownedEdits = [];+ }// Recomputed per target: earlier attempts in this same pass have banked// their rejections by now. Everything still standing is an active repair// target for this pass, so the whole set — not just `target` — is what the@@ -261,6 +274,7 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, bconst resolved = await resolveArcFindings(seriesId, record, {findings: [target], avoid, spineOnly, isolated: true,});+ ownedEdits.push(...resolvedEpisodeEdits(resolved));// The resolver applied nothing — for an isolated attempt that means the// candidate was too broad to BE one (see `isolatedCandidateRejection`) and// was discarded before it touched the store. Nothing was written, so there@@ -289,7 +303,7 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b// The run is ending mid-attempt, so this patch can never be judged. Put// the snapshot back rather than leaving an unverified rewrite in a plan// the user is about to be handed.- await restoreArcState(seriesId, snapshot);+ await restoreArcState(seriesId, snapshot, { episodeEdits: ownedEdits });return { accepted, attempts, verified: standing, outcome: verified.outcome };}const kept = isIsolatedFixSafe(target, blocking(), verified.blocking);@@ -309,7 +323,8 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b// capture the state this patch left behind, not the one before it.snapshot = null;} else {- await restoreArcState(seriesId, snapshot);+ await restoreArcState(seriesId, snapshot, { episodeEdits: ownedEdits });+ ownedEdits = [];// The verified consequence of a rewrite the gate just threw away — the// same evidence a whole-set rollback banks, at single-finding grain.// Without this the pass paid a resolve + a verify to learn something no@@ -370,6 +385,30 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })// from a spine round misreports the failure to both the status line and the// stall-diagnosis prompt that replays these frames.const scope = spineOnly ? 'arcSpine' : 'arc';+ // Every snapshot this gate is still holding, each paired with the episode+ // synopses the resolver has REPORTED writing since it was taken. Rollback+ // restores exactly those episodes, so an unrelated write that lands while a+ // verification round is running survives instead of being reverted as if the+ // round had authored it — "differs from the snapshot" was never proof of+ // ownership, and an arc-spine round (which may not touch episodes at all) was+ // reverting episode synopses on that reasoning alone.+ //+ // Per snapshot rather than per round because a checkpoint can outlive the+ // round that took it: rewinding to a `bestVerified` from three rounds back has+ // to undo every resolve that landed after it, not just the last one.+ const held = [];+ const takeSnapshot = async () => {+ const snapshot = await snapshotArcState(seriesId);+ held.push({ snapshot, episodeEdits: [] });+ return snapshot;+ };+ const noteResolverEdits = (resolved) => {+ const edits = resolvedEpisodeEdits(resolved);+ if (edits.length) for (const entry of held) entry.episodeEdits.push(...edits);+ };+ const restoreTo = (snapshot) => restoreArcState(seriesId, snapshot, {+ episodeEdits: held.find((entry) => entry.snapshot === snapshot)?.episodeEdits ?? [],+ });let convergence = { best: null, sinceBest: 0 };let changed = false;// Best verified checkpoint seen in this gate, paired with the exact arc /@@ -437,7 +476,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })if (regressed) {await recordArcResolveOutcome(lastResolve, record, { outcome: 'rejected', after: blocking, target: scope });const rollbackTarget = bestVerified || lastResolve;- const rollback = await restoreArcState(seriesId, rollbackTarget.snapshot);+ const rollback = await restoreTo(rollbackTarget.snapshot);const discarded = discardedSet(blocking);bank.record(discarded);// Neither second chance is worth its LLM call without a round left to@@ -494,6 +533,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })avoid: bank.avoid(discarded, rollbackTarget.blocking),spineOnly,});+ noteResolverEdits(retried);if (retried?.applied !== false) changed = true;// The restored state is what the retry has to beat, so the next round// compares against ITS count — not the rejected candidate's, which@@ -528,7 +568,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })// good as the checkpoint and becomes the new one. Its verification is// handed to the next round, which is where the gate is allowed to// clear: nothing advances on the per-finding checks alone.- bestVerified = { blocking: isolated.verified.blocking, snapshot: await snapshotArcState(seriesId) };+ bestVerified = { blocking: isolated.verified.blocking, snapshot: await takeSnapshot() };lastResolve = bestVerified;seededVerify = isolated.verified;continue;@@ -576,7 +616,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })// 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);+ await restoreTo(bestVerified.snapshot);const discarded = discardedSet(blocking);bank.record(discarded);return { residual: bestVerified.blocking, discarded };@@ -601,7 +641,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })// regression guard at the top of the next round can undo it. A lower or// equal blocker count promotes the latest verified draft to the checkpoint;// equal counts can reflect different, narrower findings after real repairs.- const snapshot = await snapshotArcState(seriesId);+ const snapshot = await takeSnapshot();if (isNewBest) bestVerified = { blocking, snapshot };// Resolve at the altitude this gate verified at: the spine round judged an// episode-empty plan, so its resolver may only patch the arc + volumes@@ -612,6 +652,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })avoid: bank.avoid([], blocking),spineOnly,});+ noteResolverEdits(resolved);if (resolved?.applied === false) {await recordArcResolveOutcome({ blocking, runIds: arcResolveRunIds(resolved) },