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
collapse the arc rollback's two mutation accumulators onto one shared ledger
[._.]/ Adam Eivyca84a0708bbd
diff --git a/PLAN.md b/PLAN.mdindex 0aa3ce39db..50cb8906fa 100644--- a/PLAN.md+++ b/PLAN.md@@ -349,3 +349,7 @@ is not reliably announced.### Stop the arc-verify prompt from checking fields its context never renders- [ ] The arc-verify prompt's checklist and `buildVerifyContext`'s `renderLeaf` (`server/services/pipeline/arcPlanner/context.js`) are two independent lists that have to agree, with nothing enforcing it. They drifted once already: check #6 in `data/prompts/stages/pipeline-arc-verify.md` reports an arc-role imbalance from `arcRole`, which the leaf did not render, so every verified series got a permanent "zero pilot/finale" finding no resolver could ever close — and because the foundation gate's structure arm reverts whenever `verifyArc` leaves *any* blocker, that one phantom finding stalled the gate on plans with nothing wrong with them. `arcRole` is now rendered, but the class is still open: the same silent drift returns the next time a check names a field (`status`, `lengthProfile`, `themes`, a season field) the leaf drops. **The call to make:** add a test that parses the installed + shipped `pipeline-arc-verify.md` for backticked leaf field names and asserts each one appears in a leaf built by `buildVerifyContext`, failing loudly on a check that reads a field the context cannot supply. Prove it with a bypass probe (delete a field from the leaf and watch the test fail) — a rendered-but-unread field is harmless, an unrendered-but-checked field is a permanent false positive. `renderVolumeIssue` needs the same treatment against `pipeline-volume-verify.md` if that prompt ever grows a field-level check. Surfaced while unstalling a foundationGate pause whose structure repair had been reverting on this phantom blocker.++### Give the foundation gate's structure repair the same rollback ownership as the arc gate++- [ ] `restoreArcState` now takes an exact mutation manifest (`{ episodeEdits }`) so a rollback restores only the episode synopses the resolver reported writing, instead of every episode that differs from the pre-resolve snapshot. The arc gate passes one (`server/services/pipeline/seriesAutopilot/childRuns.js`, via `createArcMutationLedger`); the foundation gate's structure repair does not, so its three rollbacks (`server/services/pipeline/foundationJudge.js` ~lines 1914, 1928, 1947) still revert any episode idea-stage difference — including a write that landed from elsewhere during the repair. Its exposure window is *longer* than the arc gate's: one resolve plus up to `MAX_STRUCTURE_CORRECTION_PASSES` correct/verify pairs. **The call to make:** it already holds each `resolveVerifyIssues` result (`trackedResolve`), so accumulate `resolvedEpisodeEdits()` across the repair's resolves on the same shared ledger and pass `ledger.since(snapshot)` at those three sites. Do NOT touch `restoreFoundationState`'s own `restoreArcState` call (~line 1709) — it verifies restore fidelity by diffing episodes wholesale via `mismatchedFoundationFields`, so the manifest-free contract is correct there, and that split is what the doc comment on `restoreArcState` records. Deferred from the arc-gate fix to keep that change to the gate whose defect was observed; needs its own regression coverage in `foundationJudge.rollback.test.js`. Surfaced by the /simplify altitude and reuse reviews.diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 2669501199..9ae3b0bff8 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1976,14 +1976,13 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollb});// 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.+ // own work — see `createArcMutationLedger` for the run that exposed it.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.+ // Bound once so the manifest provably reports the value that was written.+ const WROTE = { input: 'resolver rewrote e1', output: '', status: 'empty' };+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, {@@ -1991,8 +1990,8 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbseasons: [{ ...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' } } };+ await issuesSvc.updateStage(e1.id, 'idea', { ...WROTE });+ return { e1Edit: { issueId: e1.id, idea: { ...WROTE } } };}it('reverts its own episode write and the volume it drove, and keeps an unrelated one', async () => {@@ -2038,7 +2037,7 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbconst 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 issuesSvc.getIssue(e1.id)).stages.idea.input).toBe(WROTE.input);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);});diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 7c2b23cad0..52cb08ebf9 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -1002,9 +1002,9 @@ const sameIdea = (a, b) => a.input === b.input && a.output === b.output && a.sta* 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.+ * the verification was running. Derived from the applier's own report — an entry+ * carries `idea` only when the write went through, never when it was skipped or+ * failed — 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@@ -1012,7 +1012,7 @@ const sameIdea = (a, b) => a.input === b.input && a.output === b.output && a.sta*/export const resolvedEpisodeEdits = (resolved) => (Array.isArray(resolved?.episodesResolved)? resolved.episodesResolved- .filter((entry) => entry?.issueId && !entry.skipped && entry.idea)+ .filter((entry) => entry?.issueId && entry.idea).map((entry) => ({ issueId: entry.issueId, idea: entry.idea })): []);@@ -1065,14 +1065,20 @@ export async function snapshotArcState(seriesId) {* `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.+ * standing — "differs from the snapshot" was never proof the round owned the+ * difference. Two deliberate limits on that:+ * - Volume reassignment is never manifest-gated. The volume list is being+ * restored wholesale, so an episode left pointing at a volume that is about+ * to disappear would be stranded.+ * - Neither are the arc, character arcs and volume records themselves. Nothing+ * records what the resolver wrote at that altitude, and a non-spine round is+ * expected to rewrite all three, so the false-revert exposure is small — but+ * it is the same reasoning, and closing it needs a manifest one level up.+ *+ * Omit `episodeEdits` and every differing episode is restored. That is the right+ * contract for `restoreFoundationState`, which verifies its own restore fidelity+ * by diffing episodes wholesale; the foundation gate's structure-repair rollbacks+ * merely inherit it, and are the next callers that should pass a manifest.** 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 keepdiff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 052b078bd8..addcc93122 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -78,6 +78,7 @@ export * from './seriesAutopilot/state.js';export * from './seriesAutopilot/config.js';export * from './seriesAutopilot/convergence.js';export * from './seriesAutopilot/discardedEvidence.js';+export * from './seriesAutopilot/arcMutationLedger.js';export * from './seriesAutopilot/stepResolver.js';export * from './seriesAutopilot/session.js';export * from './seriesAutopilot/diagnosisCore.js';diff --git a/server/services/pipeline/seriesAutopilot/arcMutationLedger.js b/server/services/pipeline/seriesAutopilot/arcMutationLedger.jsnew file mode 100644index 0000000000..2c98c6614f--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/arcMutationLedger.js@@ -0,0 +1,66 @@+/**+ * Rollback OWNERSHIP for the autopilot's arc gate.+ *+ * `restoreArcState` can put an episode's planning synopsis back, but nothing in+ * a snapshot says who wrote the difference: the rollback used to treat every+ * episode that differed from the pre-resolve snapshot as the rejected round's+ * own work, so a write that arrived from anywhere else during the round's+ * several provider calls was reverted with the candidate. The arc-SPINE gate+ * made that visible — its resolver may not touch episodes at all, yet a paused+ * run reported `resolve:round episodesEdited: 0` followed by+ * `resolve:rollback episodesReverted: 1`.+ *+ * This ledger is the answer: the resolver reports the episodes it wrote (see+ * `resolvedEpisodeEdits`), and a rollback is handed exactly the writes recorded+ * AFTER its snapshot was taken. Everything else in the store keeps whatever it+ * has.+ *+ * One ledger serves the whole gate — the round loop AND its per-finding+ * isolation pass — because a checkpoint outlives the round that took it:+ * rewinding to a `bestVerified` from three rounds back has to undo every+ * resolve that landed since, including the isolation pass's. Two hand-rolled+ * accumulators is how they drift while a reader assumes they haven't (the same+ * argument `discardedEvidence.js` makes for findings evidence).+ *+ * Pure except for the ledger's own closed-over state: no I/O, no broadcast, and+ * no import of the arc planner — the caller derives the writes and hands them+ * over, so this stays a bookkeeping module rather than a second door into the+ * store graph.+ */++/**+ * A gate-lifetime ledger of resolver-owned episode writes.+ *+ * hold(snapshot) → mark where this snapshot sits in the write history+ * note(edits) → append one resolve pass's writes+ * since(snapshot) → the writes recorded after that snapshot was held+ *+ * Snapshots are keyed in a `WeakMap`, so holding one costs nothing and the+ * ledger never keeps a snapshot (arc + volumes + every episode's synopsis)+ * alive past the caller's own reference to it. A snapshot that was never held+ * yields no writes, which restores no episode at all — the conservative answer,+ * since an unheld snapshot is one this ledger cannot vouch for.+ *+ * Nothing is ever removed. A write a rollback already undid stays in the+ * history and is simply skipped by the restore's own "is this still the value+ * the resolver wrote?" check, so there is no clear-after-restore rule for a+ * caller to forget.+ */+export function createArcMutationLedger() {+ const writes = [];+ const heldAt = new WeakMap();++ return {+ hold: (snapshot) => {+ if (snapshot) heldAt.set(snapshot, writes.length);+ return snapshot;+ },+ note: (edits) => {+ if (Array.isArray(edits) && edits.length) writes.push(...edits);+ },+ since: (snapshot) => {+ const from = snapshot ? heldAt.get(snapshot) : undefined;+ return from === undefined ? [] : writes.slice(from);+ },+ };+}diff --git a/server/services/pipeline/seriesAutopilot/arcMutationLedger.test.js b/server/services/pipeline/seriesAutopilot/arcMutationLedger.test.jsnew file mode 100644index 0000000000..99eadda461--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/arcMutationLedger.test.js@@ -0,0 +1,51 @@+import { describe, it, expect } from 'vitest';+import { createArcMutationLedger } from './arcMutationLedger.js';++const edit = (issueId, input) => ({ issueId, idea: { input, output: '', status: 'empty' } });++describe('createArcMutationLedger', () => {+ it('hands each snapshot only the writes recorded after it was held', () => {+ const ledger = createArcMutationLedger();+ const first = ledger.hold({ marker: 'first' });+ ledger.note([edit('iss-1', 'round 1')]);+ const second = ledger.hold({ marker: 'second' });+ ledger.note([edit('iss-2', 'round 2')]);++ // A rewind to the older checkpoint has to undo BOTH rounds; the newer one+ // already contains round 1, so it owns only what came after it.+ expect(ledger.since(first)).toEqual([edit('iss-1', 'round 1'), edit('iss-2', 'round 2')]);+ expect(ledger.since(second)).toEqual([edit('iss-2', 'round 2')]);+ });++ it('reports no writes for a snapshot it never held', () => {+ const ledger = createArcMutationLedger();+ ledger.hold({ marker: 'held' });+ ledger.note([edit('iss-1', 'round 1')]);+ // Restoring nothing is the conservative answer for a snapshot this ledger+ // cannot vouch for — it must never claim ownership it has no record of.+ expect(ledger.since({ marker: 'never held' })).toEqual([]);+ expect(ledger.since(null)).toEqual([]);+ });++ it('returns the snapshot from hold, and ignores an empty or absent note', () => {+ const ledger = createArcMutationLedger();+ const snapshot = { marker: 'only' };+ expect(ledger.hold(snapshot)).toBe(snapshot);+ ledger.note([]);+ ledger.note(undefined);+ expect(ledger.since(snapshot)).toEqual([]);+ });++ it('keeps a write that a rollback already undid, for the restore to skip', () => {+ // Nothing is ever removed: an entry the restore has already reverted no+ // longer matches the value standing in the store, so it is skipped there.+ // That is what lets both callers share one ledger with no clear-on-restore+ // rule to forget.+ const ledger = createArcMutationLedger();+ const snapshot = ledger.hold({ marker: 'isolation' });+ ledger.note([edit('iss-1', 'attempt 1')]);+ expect(ledger.since(snapshot)).toEqual([edit('iss-1', 'attempt 1')]);+ ledger.note([edit('iss-1', 'attempt 2')]);+ expect(ledger.since(snapshot)).toEqual([edit('iss-1', 'attempt 1'), edit('iss-1', 'attempt 2')]);+ });+});diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 027ff0a985..bbb82241d2 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -32,6 +32,7 @@ import {isIsolatedFixSafe,} from './convergence.js';import { createDiscardedBank } from './discardedEvidence.js';+import { createArcMutationLedger } from './arcMutationLedger.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';import { recordModelOutcome } from './modelPerformance.js';import { requiredScriptStages, textReady } from './stepResolver.js';@@ -87,7 +88,7 @@ async function resolveArcFindings(seriesId, record, { findings, avoid, spineOnly// Episode synopses one resolve pass actually rewrote, for the telemetry frames.// Read off the same mutation manifest the rollback is driven by, so-// `episodesEdited` and `episodesReverted` can no longer describe different sets:+// `episodesEdited` and `episodesReverted` cannot 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;@@ -211,6 +212,11 @@ async function verifyArcBlocking(seriesId, record, { spineOnly }) {* this loop reads as an attempt needing neither a rollback (nothing was written)* nor a verification round (the blocking set cannot have moved).*+ * `ledger` is the gate's shared mutation ledger: this pass holds its snapshot in+ * it and notes its own resolves, so a rejected attempt restores only the episode+ * synopses it actually wrote — and a RETAINED one is visible to a later rewind+ * in the round loop, which would otherwise have no record of it.+ ** Bounded by `attemptsLeft` and budget-gated per attempt like every other* resolve. Returns `{ accepted, attempts, verified }` — `verified` being the* full verification of the state now standing in the store, which the caller@@ -223,7 +229,7 @@ async function verifyArcBlocking(seriesId, record, { spineOnly }) {* resolve after a successful isolation gets too. Computing it once up front* made every attempt repeat the prompt the previous one had just failed with.*/-async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, baseline, bank, attemptsLeft }) {+async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, baseline, bank, ledger, attemptsLeft }) {// The last verification that DESCRIBES THE STORE: it advances only on an// accepted patch, because a rejected one is rolled straight back to the state// its predecessor verified. So later targets are judged against what the@@ -239,12 +245,6 @@ 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;@@ -261,10 +261,7 @@ 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);- ownedEdits = [];- }+ if (!snapshot) snapshot = ledger.hold(await snapshotArcState(seriesId));// 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@@ -274,7 +271,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));+ ledger.note(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@@ -303,7 +300,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, { episodeEdits: ownedEdits });+ await restoreArcState(seriesId, snapshot, { episodeEdits: ledger.since(snapshot) });return { accepted, attempts, verified: standing, outcome: verified.outcome };}const kept = isIsolatedFixSafe(target, blocking(), verified.blocking);@@ -323,8 +320,7 @@ 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, { episodeEdits: ownedEdits });- ownedEdits = [];+ await restoreArcState(seriesId, snapshot, { episodeEdits: ledger.since(snapshot) });// 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@@ -385,29 +381,14 @@ 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);- };+ // Which episode synopses each rollback is allowed to put back: the ones the+ // resolver reported writing after that checkpoint was taken, and nothing else+ // (see `createArcMutationLedger`). Shared with the isolation pass below, whose+ // retained patches a later rewind to an older checkpoint also has to undo.+ const ledger = createArcMutationLedger();+ const takeSnapshot = async () => ledger.hold(await snapshotArcState(seriesId));const restoreTo = (snapshot) => restoreArcState(seriesId, snapshot, {- episodeEdits: held.find((entry) => entry.snapshot === snapshot)?.episodeEdits ?? [],+ episodeEdits: ledger.since(snapshot),});let convergence = { best: null, sinceBest: 0 };let changed = false;@@ -533,7 +514,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })avoid: bank.avoid(discarded, rollbackTarget.blocking),spineOnly,});- noteResolverEdits(retried);+ ledger.note(resolvedEpisodeEdits(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@@ -557,6 +538,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })scope, round, spineOnly,baseline: rollbackTarget.blocking,bank,+ ledger,attemptsLeft: isolationLeft,});isolationLeft -= isolated.attempts;@@ -652,7 +634,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank })avoid: bank.avoid([], blocking),spineOnly,});- noteResolverEdits(resolved);+ ledger.note(resolvedEpisodeEdits(resolved));if (resolved?.applied === false) {await recordArcResolveOutcome({ blocking, runIds: arcResolveRunIds(resolved) },