Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: cache SUPERSEDED branch verdicts so branch-reconcile stops re-deriving them
[._.]/ Adam Eivy09e4dfabf253
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fffbe8eff8..52d4cee900 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **Branch reconciliation stops re-deriving the same superseded verdict forever.** A branch whose work already landed on the default branch under different file and function names is correctly left untouched — merging it would regress shipped code — but nothing ever reaped it either: git can't see it as merged, so it stayed in-flight and every recheck paid a full agent run to reach the identical conclusion. Two abandoned worktrees in one install were analyzed sixteen times that way. A coordinator that concludes SUPERSEDED now records the verdict — the branch tip, its uncommitted change set, the collision paths it judged against, and the commits on the default branch that replaced it — and later passes skip the analysis while all of that still holds. The branch is still reported, in its own "awaiting reap" section with the replacing commits and the exact removal commands, and nothing is ever auto-deleted. The cache expires the moment the judgment could change: the branch tip moves, its uncommitted files change, its collision set grows, or the commit that superseded it is reverted off the default branch. A missing or malformed ledger falls back to full analysis rather than hiding a branch that still needs work.+- **Daily Log no longer parks autosave when voice dictation lands mid-edit.** A spoken segment is merged into the textarea (append-at-end, caret restored) instead of leaving the user to Save or refresh, and full-content saves send the last-seen `updatedAt` as `ifMatchUpdatedAt`. When a concurrent append advances that clock, the server returns 409 `STALE_JOURNAL` with the current entry in `context.entry`; the client folds in any missing voice segments and retries a few times so an in-flight PUT cannot silently drop dictation.- **Series Autopilot can learn which models actually work at each step.** AI run history now distinguishes technical completion from a later editorial keep/revert decision and aggregates evidence by orchestration step, creative-versus-judge role, provider, model, and reasoning effort. The new opt-in selector requires multiple quality-reviewed samples plus a positive reliability threshold, ignores disabled providers and removed models, and remains a soft default beneath explicit run choices and exact prompt-stage pins. The Options panel reports how much attributed and quality-reviewed evidence exists, while local APIs expose the full metrics and allow an operator to correct or backfill a historical outcome, including its effort when the older run predates effort telemetry. Concurrent metadata updates for one run are serialized so provider telemetry cannot overwrite its Autopilot step/role attribution, and internal structure-verification calls retain the judge role instead of inheriting their repairer's creative role. Foundation judges record contract-valid responses separately from true editorial approval, and foundation repairs automatically record accepted versus rolled-back outcomes. Arc repairs now do the same after normal rounds, corrective retries, and isolated-finding attempts, while canceled candidates remain deliberately unevaluated, so a model that finishes a long run but makes the story worse is not learned as a success.diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex d53b3173fd..22cc413f72 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -25,6 +25,7 @@ import { getOriginInfo } from '../lib/gitRemote.js';import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';+import { readVerdictLedger, partitionSuperseded, recordVerdictInstruction } from './supersededLedger.js';// Never reconciled — the canonical long-lived-branch set (`main`/`master`/`dev`/// `develop`/`release`/`gh-pages`) shared with the git branch-cleanup guards in@@ -367,7 +368,7 @@ async function worktreeAgeMs(worktreePath) {* distinguishes a live agent's worktree from an abandoned one (see* `isAbandonedAgentWorktree`); omitting it leaves every agent worktree protected.* @returns {Promise<object[]>} one entry per candidate branch:- * { branch, hasUpstream, isMerged, hasWorktree, worktreePath, worktreeDirty, dirtyPaths,+ * { branch, tip, hasUpstream, isMerged, hasWorktree, worktreePath, worktreeDirty, dirtyPaths,* behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }*/export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null }) {@@ -407,8 +408,14 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId// the harder cases via isBranchMergedInto (covers squash + rebase). Short// -circuit when the cheap check already proved it merged.const isMerged = b.merged || await isBranchMergedInto(repoPath, b.name, defaultBranch);+ // Tip SHA is the primary cache key for a recorded SUPERSEDED verdict (see+ // supersededLedger.js) — a branch that moved must be re-analyzed. `null` on+ // failure so an unreadable tip can never match a recorded one.+ const tipOut = await execGit(['rev-parse', b.name], repoPath, { ignoreExitCode: true }).catch(() => null);+ const tip = (tipOut?.stdout || '').trim() || null;inputs.push({branch: b.name,+ tip,hasUpstream: Boolean(b.tracking),isMerged,hasWorktree: Boolean(worktreePath),@@ -529,16 +536,59 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeA// Priority-ordered so the coordinator agent works recognized work branches// (claim/cos/next/feature/fix/…) before anything unrecognized. The order flows// straight through filterActionable (a stable filter) into the prompt block.- const inFlight = prioritizeBranches(+ const allInFlight = prioritizeBranches(classified.filter((c) => ['ABANDONED_WIP', 'CONFLICTED', 'IN_REVIEW', 'NEEDS_PR'].includes(c.state)));+ // A branch already judged SUPERSEDED is left untouched by design and is never+ // `isMerged` (its work landed under other names), so nothing reaps it and it+ // stays in-flight forever — re-analyzed at full cost on every recheck. Drop it+ // out of the actionable set on a cached verdict that still verifies (#3842).+ const { actionable: inFlight, superseded } = await applySupersededLedger(repoPath, allInFlight, defaultBranch);const wip = classified.filter((c) => c.state === 'WIP');const { cleaned, skipped } = cleanup? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds }): { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };- return { defaultBranch, cleaned, inFlight, wip, skipped, prStateUnavailable };+ return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, prStateUnavailable };+}++/**+ * Resolve each cached SUPERSEDED verdict against the repo as it stands now and+ * split the in-flight set accordingly. A verdict survives only while its+ * `replacedBy` commits are still reachable from the default branch — a revert of+ * what superseded the branch makes the branch wanted again, and that is the one+ * change the pure freshness check can't see on its own.+ *+ * Fails OPEN in every direction: an unreadable ledger, an unresolvable SHA, or a+ * git error all yield "not cached", which restores full analysis rather than+ * silently hiding a branch that needs work.+ *+ * @param {string} repoPath+ * @param {object[]} inFlight+ * @param {string} defaultBranch+ * @returns {Promise<{ actionable: object[], superseded: object[] }>}+ */+async function applySupersededLedger(repoPath, inFlight, defaultBranch) {+ const entries = await readVerdictLedger().catch(() => []);+ if (!entries.length || !inFlight.length) return { actionable: inFlight, superseded: [] };++ // Only the SHAs belonging to entries that could still match are probed, so a+ // large stale ledger costs nothing.+ const relevant = new Set(inFlight.map((b) => b.branch));+ const shas = [...new Set(+ entries.filter((e) => e.repoPath === repoPath && relevant.has(e.branch)).flatMap((e) => e.replacedBy || [])+ )];+ const reachable = new Set();+ for (const sha of shas) {+ const ok = await execGit(['merge-base', '--is-ancestor', sha, defaultBranch], repoPath, { ignoreExitCode: true })+ .then((r) => r?.exitCode === 0)+ .catch(() => false);+ if (ok) reachable.add(sha);+ }+ return partitionSuperseded(+ inFlight, entries, (e) => (e.replacedBy || []).every((s) => reachable.has(s)), { repoPath }+ );}// ============================================================@@ -608,6 +658,7 @@ const supersessionGate = ({ collisionPaths = [], behind } = {}) => {`The default branch has ALSO changed these files since this branch diverged: ${shown.map((p) => `\`${p}\``).join(', ')}${more}.`,'For each, read the default branch\'s current version and compare it to what this branch does there. You are looking for one thing: has the default branch already solved this branch\'s problem, by any means? A differently-named function, a policy object where this branch has a boolean, a scheduled tick where this branch has a watcher — all count. It does not need to look like this branch\'s approach to have replaced it.','If it HAS been solved there, this branch is SUPERSEDED: stop, do not commit, rebase, resolve, or merge anything, and report it as superseded naming the file(s) and what on the default branch replaced it. Merging it would undo work already shipped. Say so plainly rather than resolving the conflict — a conflict you can resolve is exactly how a regression gets in looking deliberate.',+ recordVerdictInstruction(),'Only once you have confirmed the work is still needed, continue.'].join(' ');};diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 7c9ee79a9f..081134c668 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -45,9 +45,15 @@ vi.mock('../lib/gitRemote.js', () => ({hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'}))}));+// `tryReadFile`/`atomicWrite` are reached through supersededLedger.js (the+// SUPERSEDED verdict cache); the default `tryReadFile` returns null = no ledger,+// which is the fail-open "analyze everything" path the pre-#3842 suite assumes.+const tryReadFileMock = vi.fn(async () => null);vi.mock('../lib/fileUtils.js', () => ({- PATHS: { root: '/repo' },- safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } }+ PATHS: { root: '/repo', cos: '/repo/data/cos' },+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },+ tryReadFile: (...args) => tryReadFileMock(...args),+ atomicWrite: vi.fn(async () => {})}));import {@@ -74,6 +80,7 @@ beforeEach(() => {git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });wt.forceRemoveWorktreeDir.mockResolvedValue(undefined);execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ tryReadFileMock.mockResolvedValue(null);});describe('classifyBranch', () => {@@ -608,6 +615,121 @@ describe('reconcile', () => {});});+// #3842 — a SUPERSEDED branch is left untouched by design and is never `isMerged`+// (its work landed on the default branch under other names), so nothing reaps it+// and every recheck paid a full coordinator run to re-derive the same verdict.+// Two branches in this install were analyzed sixteen times that way.+describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {+ const BRANCH = 'cos/task-x/agent-deadbeef';+ const WORKTREE = '/repo/data/cos/worktrees/agent-deadbeef';+ const DIRTY = ' M server/services/thing.js\n';++ // The abandoned-worktree shape: branch fully behind main, uncommitted work in a+ // dead agent's worktree, one collision path with the default branch.+ const setupAbandoned = ({ tip = 'aaaaaaa', replacedByReachable = true } = {}) => {+ git.getBranches.mockResolvedValue([+ { name: BRANCH, isDefault: false, current: false, tracking: 'origin/main', merged: false }+ ]);+ wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);+ git.isBranchMergedInto.mockResolvedValue(false);+ execGit.mockImplementation(async (args) => {+ const [cmd] = args;+ if (cmd === 'rev-parse') return { stdout: `${tip}\n`, exitCode: 0 };+ if (cmd === 'merge-base' && args[1] === '--is-ancestor') {+ return { stdout: '', exitCode: replacedByReachable ? 0 : 1 };+ }+ if (cmd === 'merge-base') return { stdout: 'base000\n', exitCode: 0 };+ // `diff --name-only` on BOTH sides yields the same path → one collision.+ if (cmd === 'diff') return { stdout: 'server/services/thing.js\n', exitCode: 0 };+ if (cmd === 'rev-list') return { stdout: '301\t0\n', exitCode: 0 };+ // `status --porcelain` in the worktree.+ return { stdout: DIRTY, exitCode: 0 };+ });+ };++ const ledger = (over = {}) => JSON.stringify({+ version: 1,+ entries: [{+ branch: BRANCH,+ repoPath: '/repo',+ verdict: 'SUPERSEDED',+ tip: 'aaaaaaa',+ dirtyPaths: ['server/services/thing.js'],+ collisionPaths: ['server/services/thing.js'],+ replacedBy: ['ffffff1'],+ replacedByNote: 'thing.js now exports doTheThing()',+ ...over+ }]+ });++ it('drops a branch with a fresh cached verdict out of the actionable set', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger());++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight).toEqual([]);+ expect(res.superseded.map((s) => s.branch)).toEqual([BRANCH]);+ // Left completely alone — the whole point is that merging it would regress main.+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('re-analyzes when the branch tip moved', async () => {+ setupAbandoned({ tip: 'bbbbbbb' });+ tryReadFileMock.mockResolvedValue(ledger());++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ expect(res.superseded).toEqual([]);+ });++ it('re-analyzes when the uncommitted change set moved', async () => {+ // An ABANDONED_WIP branch's entire deliverable is its dirty tree, so a tip SHA+ // alone would not notice a human editing the worktree.+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger({ dirtyPaths: ['server/services/other.js'] }));++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ expect(res.superseded).toEqual([]);+ });++ it('re-analyzes when the collision set changed', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger({ collisionPaths: [] }));++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ });++ it('re-analyzes when what superseded the branch was reverted off the default branch', async () => {+ setupAbandoned({ replacedByReachable: false });+ tryReadFileMock.mockResolvedValue(ledger());++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ expect(res.superseded).toEqual([]);+ });++ it('fails open on a malformed ledger rather than hiding the branch', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue('{ not json');++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ });++ // One ledger serves every managed app; `feature/x` in two apps is two branches.+ it('ignores a verdict recorded against a different app\'s repo', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger({ repoPath: '/some/other-app' }));++ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);+ expect(res.superseded).toEqual([]);+ });+});+describe('actionOn', () => {it('is ON for absent/true, OFF only for explicit false', () => {expect(actionOn(undefined, 'openPr')).toBe(true);diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 4861897715..3ef87e0e66 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2209,6 +2209,7 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, iasync function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule) {if (taskType !== 'branch-reconcile') return { skip: false, block: '' };const { reconcile, filterActionable, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');+ const { formatSupersededForPrompt } = await import('./supersededLedger.js');const { getActiveAgentIds } = await import('./agentState.js');// Action toggles were merged (global → per-app override) + value-constrained// by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.@@ -2248,6 +2249,15 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskScheduleif (result.cleaned.length) {emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });}+ // Branches whose SUPERSEDED verdict is already cached and still verifies were+ // dropped from `inFlight` by the reconciler (#3842). They are real branches a+ // human still has to reap, so name them rather than letting them vanish into a+ // quiet park — the invisibility is the same failure mode as a lingering worktree+ // reported as "cleaned 0".+ const supersededCount = result.superseded?.length || 0;+ const supersededSuffix = supersededCount+ ? `, ${supersededCount} branch(es) already verified superseded and awaiting human reap`+ : '';const actionable = filterActionable(result.inFlight, actions);if (actionable.length === 0) {// Definitive idle: nothing in-flight to drive. Park on the recheck cadence@@ -2267,7 +2277,7 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskScheduleconst gatedSuffix = gatedOff? `, ${gatedOff} in-flight branch(es) skipped by disabled action toggles (${[...new Set(result.inFlight.map((b) => b.state))].join(', ')})`: '';- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix})`, { appId: app.id });+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix}${supersededSuffix})`, { appId: app.id });return { skip: true };}// Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling@@ -2285,8 +2295,12 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskScheduleawait taskSchedule.clearPerpetualPark(taskType, app.id);await taskSchedule.setPerpetualSignature(taskType, app.id, signature);metadata.perpetual = true;- const block = formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions });- emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)`, { appId: app.id, analysisType: taskType });+ const supersededBlock = formatSupersededForPrompt(result.superseded || []);+ const block = [+ formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions }),+ supersededBlock+ ].filter(Boolean).join('\n');+ emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)${supersededSuffix}`, { appId: app.id, analysisType: taskType });return { skip: false, block };}diff --git a/server/services/supersededLedger.js b/server/services/supersededLedger.jsnew file mode 100644index 0000000000..525b44d568--- /dev/null+++ b/server/services/supersededLedger.js@@ -0,0 +1,196 @@+/**+ * Superseded-branch verdict ledger (#3842).+ *+ * `branch-reconcile` can never converge on a SUPERSEDED branch. The verdict is+ * correct — merging the branch would regress shipped work — but nothing acts on+ * it: the branch is left untouched by design, and the deterministic cleanup in+ * `cleanupMerged()` only reaps what git can see as merged. Work that landed on+ * the default branch under different file and function names is never `isMerged`,+ * so the branch stays ABANDONED_WIP, stays actionable, and the next recheck pays+ * a full coordinator run to re-derive the identical verdict. Two branches in this+ * install were analyzed sixteen times that way.+ *+ * The scheduler's `parkPerpetual()` already notices the actionable SET is+ * unchanged — but it caches only *that*, never *what was concluded*. This module+ * caches the conclusion.+ *+ * The ledger is per-install runtime state (`data/cos/branch-reconcile-verdicts.json`,+ * gitignored) — verdicts are facts about THIS clone's local branches, so there is+ * nothing to seed, migrate, or federate. Every read fails OPEN: a missing,+ * unreadable, or malformed ledger yields no entries, which restores the old+ * re-analyze-everything behavior rather than silently hiding a branch.+ *+ * DELIBERATELY NOT auto-reap. A superseded branch's uncommitted work is+ * redundant, not worthless, and deleting a worktree is irreversible. The+ * expensive part of the loop is the *analysis*, so caching the verdict removes+ * the cost while the destructive step stays a human action.+ */++import { PATHS, tryReadFile, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';+import { join } from 'node:path';++export const LEDGER_VERSION = 1;++/** Absolute path to an install's verdict ledger. */+export const ledgerPath = (cosDir = PATHS.cos) => join(cosDir, 'branch-reconcile-verdicts.json');++/** Order-independent set equality over two path lists. Pure. */+const sameSet = (a = [], b = []) => {+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;+ const left = new Set(a);+ return b.every((x) => left.has(x)) && left.size === new Set(b).size;+};++/**+ * Read the ledger. Never throws and never partially trusts a malformed file —+ * an unparseable ledger is treated as no ledger (fail open → re-analyze).+ * @param {string} [cosDir]+ * @returns {Promise<object[]>} verdict entries (possibly empty)+ */+export async function readVerdictLedger(cosDir = PATHS.cos) {+ const raw = await tryReadFile(ledgerPath(cosDir));+ if (raw === null) return [];+ const parsed = safeJSONParse(raw, null);+ const entries = Array.isArray(parsed) ? parsed : parsed?.entries;+ return Array.isArray(entries) ? entries.filter((e) => e && typeof e.branch === 'string') : [];+}++/**+ * Persist the ledger, replacing any existing entry for the same branch.+ * @param {object[]} entries+ * @param {string} [cosDir]+ */+export async function writeVerdictLedger(entries, cosDir = PATHS.cos) {+ await atomicWrite(ledgerPath(cosDir), { version: LEDGER_VERSION, entries });+ return entries;+}++/**+ * Record (or refresh) one branch's verdict. Last write wins per (repo, branch) —+ * one ledger serves every managed app, and a branch name alone does not identify+ * a branch across them.+ * @param {object} entry - at minimum { branch, repoPath, verdict, tip }+ * @param {string} [cosDir]+ */+export async function recordVerdict(entry, cosDir = PATHS.cos) {+ const existing = await readVerdictLedger(cosDir);+ const isSame = (e) => e.branch === entry.branch && e.repoPath === entry.repoPath;+ return writeVerdictLedger(+ [...existing.filter((e) => !isSame(e)), { decidedAt: new Date().toISOString(), ...entry }],+ cosDir+ );+}++/**+ * Is a recorded verdict still trustworthy for the branch as it stands NOW? Pure.+ *+ * Three things can make a verdict stale, and each maps to a real way the+ * judgment could change:+ * - the branch moved (`tip`) or its uncommitted change set moved (`dirtyPaths`)+ * — an ABANDONED_WIP branch's whole deliverable is its dirty tree, so a tip+ * SHA alone would not notice someone editing the worktree;+ * - the collision set changed — the branch now touches files the judgment was+ * never made against;+ * - a commit recorded as the replacement is no longer reachable from the+ * default branch (a revert), so what superseded the branch is gone.+ *+ * Note what is deliberately NOT a staleness signal: the CONTENT of a collision+ * path changing on the default branch. `.changelog/NEXT.md` is a collision path+ * on essentially every long-lived branch and is rewritten by every merge, so+ * content-hash invalidation would expire every entry within minutes and cache+ * nothing. Continued churn in a file the default branch already solved makes+ * supersession *more* certain, not less; a revert is the case that actually+ * undoes it, and `replacedBy` reachability catches that directly.+ *+ * @param {object} entry - a ledger entry+ * @param {object} branch - the live reconcile entry { branch, tip, collisionPaths, dirtyPaths }+ * @param {{ replacedByPresent?: boolean, repoPath?: string }} [ctx] - resolved reachability of+ * `entry.replacedBy`, and the repo being reconciled+ * @returns {boolean}+ */+export function isVerdictFresh(entry, branch, { replacedByPresent = true, repoPath = null } = {}) {+ if (!entry || entry.verdict !== 'SUPERSEDED') return false;+ if (!entry.branch || entry.branch !== branch?.branch) return false;+ // One ledger serves every managed app, and branch names are not unique across+ // repos — `feature/x` in two apps is two different branches. An entry that+ // doesn't name the repo it was decided in is not allowed to speak for any of them.+ if (!entry.repoPath || entry.repoPath !== repoPath) return false;+ // A verdict with no recorded replacement can't be re-verified cheaply, so it+ // is not allowed to suppress analysis — the evidence IS the cache key.+ if (!Array.isArray(entry.replacedBy) || entry.replacedBy.length === 0) return false;+ if (!replacedByPresent) return false;+ if (!entry.tip || entry.tip !== branch.tip) return false;+ if (!sameSet(entry.collisionPaths, branch.collisionPaths)) return false;+ return sameSet(entry.dirtyPaths || [], branch.dirtyPaths || []);+}++/**+ * Split the in-flight set into branches still worth analyzing and branches whose+ * SUPERSEDED verdict is cached and still fresh. Pure — reachability of each+ * entry's `replacedBy` commits is resolved by the caller and passed in.+ *+ * @param {object[]} inFlight+ * @param {object[]} entries - ledger entries+ * @param {(entry:object) => boolean} [replacedByPresent] - predicate per entry+ * @param {{ repoPath?: string }} [ctx] - the repo being reconciled; entries decided+ * in a different repo never apply (branch names are not unique across apps)+ * @returns {{ actionable: object[], superseded: object[] }} `superseded` entries are+ * the live branch objects annotated with `{ verdict }` from the ledger+ */+export function partitionSuperseded(inFlight, entries, replacedByPresent = () => true, { repoPath = null } = {}) {+ const byBranch = new Map((entries || []).filter((e) => e.repoPath === repoPath).map((e) => [e.branch, e]));+ const actionable = [];+ const superseded = [];+ for (const b of inFlight || []) {+ const entry = byBranch.get(b.branch);+ if (entry && isVerdictFresh(entry, b, { replacedByPresent: replacedByPresent(entry), repoPath })) {+ superseded.push({ ...b, verdict: entry });+ } else {+ actionable.push(b);+ }+ }+ return { actionable, superseded };+}++/**+ * Render the cached-superseded set for the coordinator prompt. These branches are+ * NOT work — they are named so the coordinator doesn't re-discover them, and so+ * the reap commands are one copy away for the human who authorizes them.+ * @param {object[]} superseded - partitionSuperseded()'s `superseded`+ * @returns {string}+ */+export function formatSupersededForPrompt(superseded) {+ if (!superseded?.length) return '';+ const lines = [+ `## Already verified SUPERSEDED — awaiting reap (${superseded.length}) — DO NOT ANALYZE`,+ '',+ 'Each branch below was analyzed by an earlier run and confirmed superseded: the default branch already solves its problem, so merging it would REGRESS shipped work. The verdict is cached and still valid (branch tip, uncommitted change set, and collision paths all unchanged; the replacing commits are still on the default branch). Do not read these worktrees, do not re-derive the verdict, do not commit, rebase, resolve, or merge anything on them. They are listed only so you can report them — reaping is a human action.',+ ''+ ];+ for (const b of superseded) {+ const v = b.verdict || {};+ lines.push(`### \`${b.branch}\` — SUPERSEDED${v.decidedAt ? ` (verdict recorded ${v.decidedAt})` : ''}`);+ if (v.was) lines.push(`- Was: ${v.was}`);+ if (v.replacedBy?.length) lines.push(`- Replaced on the default branch by: ${v.replacedBy.map((s) => `\`${s}\``).join(', ')}${v.replacedByNote ? ` — ${v.replacedByNote}` : ''}`);+ if (v.backupPatch) lines.push(`- Uncommitted work backed up at: \`${v.backupPatch}\``);+ if (b.worktreePath) {+ lines.push('- Reap (destructive — report these commands, do NOT run them):');+ lines.push(` \`git worktree remove --force ${b.worktreePath} && git branch -D ${b.branch}\``);+ }+ lines.push('');+ }+ return lines.join('\n');+}++/**+ * The instruction appended to the supersession gate so a coordinator that REACHES+ * a SUPERSEDED verdict writes it down. Without this the analysis is paid for and+ * then thrown away, which is the whole defect in #3842.+ * @param {string} [file]+ * @returns {string}+ */+export const recordVerdictInstruction = (file = 'data/cos/branch-reconcile-verdicts.json') => [+ `If you conclude SUPERSEDED, RECORD IT so no future run pays to re-derive it: read \`${file}\` (a JSON \`{ "version": 1, "entries": [...] }\`; treat a missing or unparseable file as \`{ "version": 1, "entries": [] }\`), replace any entry with the same \`branch\` AND \`repoPath\`, and write it back.`,+ 'The entry must be: `{ "branch": "<full branch name>", "repoPath": "<absolute path of the repo being reconciled>", "verdict": "SUPERSEDED", "tip": "<full SHA of `git rev-parse <branch>`>", "dirtyPaths": [<every path `git status --porcelain` reports in its worktree, exactly as reconcile listed them>], "collisionPaths": [<the collision list given to you above, verbatim>], "replacedBy": ["<full SHA on the default branch that replaced it>", ...], "replacedByNote": "<one line naming the file and what replaced it>", "was": "<one line: what the branch was trying to do>", "decidedAt": "<ISO 8601 UTC>" }`.',+ '`repoPath` and `replacedBy` are both mandatory: one ledger serves every managed app so a bare branch name identifies nothing, and the replacing commits are the evidence the cache re-checks. An entry missing either is ignored. If you cannot name a replacing commit, you have not actually confirmed supersession; keep analyzing.'+].join(' ');diff --git a/server/services/supersededLedger.test.js b/server/services/supersededLedger.test.jsnew file mode 100644index 0000000000..57539bd50d--- /dev/null+++ b/server/services/supersededLedger.test.js@@ -0,0 +1,258 @@+/**+ * Unit tests for the superseded-branch verdict ledger (#3842).+ *+ * The pure parts (isVerdictFresh / partitionSuperseded / formatSupersededForPrompt)+ * carry the safety property that matters: a verdict may only suppress analysis+ * while every piece of evidence it was based on still holds. Everything else+ * fails OPEN — back to full analysis, never to a silently hidden branch.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const files = new Map();+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { cos: '/repo/data/cos' },+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },+ tryReadFile: async (p) => (files.has(p) ? files.get(p) : null),+ atomicWrite: async (p, data) => { files.set(p, typeof data === 'string' ? data : JSON.stringify(data, null, 2)); }+}));++import {+ ledgerPath, readVerdictLedger, writeVerdictLedger, recordVerdict,+ isVerdictFresh, partitionSuperseded, formatSupersededForPrompt, recordVerdictInstruction+} from './supersededLedger.js';++const PATH = '/repo/data/cos/branch-reconcile-verdicts.json';++const entry = (over = {}) => ({+ branch: 'cos/task-x/agent-dead',+ repoPath: '/repo',+ verdict: 'SUPERSEDED',+ tip: 'aaa111',+ dirtyPaths: ['a.js', 'b.js'],+ collisionPaths: ['a.js'],+ replacedBy: ['fff999'],+ ...over+});++const branch = (over = {}) => ({+ branch: 'cos/task-x/agent-dead',+ tip: 'aaa111',+ dirtyPaths: ['b.js', 'a.js'], // order must not matter+ collisionPaths: ['a.js'],+ state: 'ABANDONED_WIP',+ worktreePath: '/repo/data/cos/worktrees/agent-dead',+ ...over+});++beforeEach(() => files.clear());++describe('ledgerPath', () => {+ it('lands in the install\'s cos data dir', () => {+ expect(ledgerPath()).toBe(PATH);+ expect(ledgerPath('/other/cos')).toBe('/other/cos/branch-reconcile-verdicts.json');+ });+});++describe('readVerdictLedger', () => {+ it('is empty when the file does not exist', async () => {+ expect(await readVerdictLedger()).toEqual([]);+ });++ it('is empty (not partial) on malformed JSON — fail open to re-analysis', async () => {+ files.set(PATH, '{ "entries": [');+ expect(await readVerdictLedger()).toEqual([]);+ });++ it('reads the wrapped { version, entries } shape', async () => {+ files.set(PATH, JSON.stringify({ version: 1, entries: [entry()] }));+ expect((await readVerdictLedger()).map((e) => e.branch)).toEqual(['cos/task-x/agent-dead']);+ });++ it('also accepts a bare array', async () => {+ files.set(PATH, JSON.stringify([entry()]));+ expect(await readVerdictLedger()).toHaveLength(1);+ });++ it('drops entries with no branch name rather than trusting them', async () => {+ files.set(PATH, JSON.stringify({ entries: [entry(), { verdict: 'SUPERSEDED' }, null] }));+ expect(await readVerdictLedger()).toHaveLength(1);+ });+});++describe('writeVerdictLedger / recordVerdict', () => {+ it('round-trips through the versioned wrapper', async () => {+ await writeVerdictLedger([entry()]);+ expect(JSON.parse(files.get(PATH)).version).toBe(1);+ expect(await readVerdictLedger()).toHaveLength(1);+ });++ it('replaces the entry for a (repo, branch) pair instead of appending a duplicate', async () => {+ await recordVerdict(entry());+ await recordVerdict(entry({ tip: 'bbb222' }));+ const all = await readVerdictLedger();+ expect(all).toHaveLength(1);+ expect(all[0].tip).toBe('bbb222');+ });++ it('stamps decidedAt when the caller did not', async () => {+ await recordVerdict(entry());+ expect((await readVerdictLedger())[0].decidedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ });++ it('keeps other branches\' verdicts', async () => {+ await recordVerdict(entry());+ await recordVerdict(entry({ branch: 'cos/task-y/agent-other' }));+ expect((await readVerdictLedger()).map((e) => e.branch).sort())+ .toEqual(['cos/task-x/agent-dead', 'cos/task-y/agent-other']);+ });++ it('keeps a same-named branch in a different repo as its own entry', async () => {+ await recordVerdict(entry());+ await recordVerdict(entry({ repoPath: '/other-app', tip: 'ccc333' }));+ const all = await readVerdictLedger();+ expect(all).toHaveLength(2);+ expect(all.map((e) => e.repoPath).sort()).toEqual(['/other-app', '/repo']);+ });+});++describe('isVerdictFresh', () => {+ const REPO = { repoPath: '/repo' };+ const fresh = (e, b, ctx = {}) => isVerdictFresh(e, b, { ...REPO, ...ctx });++ it('is fresh when tip, dirty set and collision set all still match', () => {+ expect(fresh(entry(), branch())).toBe(true);+ });++ it('ignores ordering within the recorded path lists', () => {+ expect(fresh(entry({ collisionPaths: ['a.js', 'z.js'] }), branch({ collisionPaths: ['z.js', 'a.js'] })))+ .toBe(true);+ });++ it('is stale when the branch tip moved', () => {+ expect(fresh(entry(), branch({ tip: 'ccc333' }))).toBe(false);+ });++ it('is stale when the tip is unreadable — an unknown tip can never match', () => {+ expect(fresh(entry(), branch({ tip: null }))).toBe(false);+ expect(fresh(entry({ tip: null }), branch({ tip: null }))).toBe(false);+ });++ it('is stale when the uncommitted change set moved', () => {+ expect(fresh(entry(), branch({ dirtyPaths: ['a.js'] }))).toBe(false);+ });++ it('is stale when the collision set grew', () => {+ expect(fresh(entry(), branch({ collisionPaths: ['a.js', 'new.js'] }))).toBe(false);+ });++ it('is stale when the replacing commits are no longer reachable (a revert)', () => {+ expect(fresh(entry(), branch(), { replacedByPresent: false })).toBe(false);+ });++ it('refuses a verdict that names no replacing commit — the evidence IS the cache key', () => {+ expect(fresh(entry({ replacedBy: [] }), branch())).toBe(false);+ expect(fresh(entry({ replacedBy: undefined }), branch())).toBe(false);+ });++ it('only ever suppresses a SUPERSEDED verdict', () => {+ expect(fresh(entry({ verdict: 'INCOMPLETE' }), branch())).toBe(false);+ expect(fresh(null, branch())).toBe(false);+ });++ it('will not let one branch\'s verdict speak for another', () => {+ expect(fresh(entry(), branch({ branch: 'cos/task-y/agent-other' }))).toBe(false);+ });++ // One ledger serves every managed app, and `feature/x` in two apps is two+ // different branches — a verdict must never cross that boundary.+ it('will not let one repo\'s verdict speak for a same-named branch in another repo', () => {+ expect(isVerdictFresh(entry(), branch(), { repoPath: '/other-app' })).toBe(false);+ });++ it('refuses an entry that does not name the repo it was decided in', () => {+ expect(fresh(entry({ repoPath: undefined }), branch())).toBe(false);+ });+});++describe('partitionSuperseded', () => {+ const REPO = { repoPath: '/repo' };+ const split = (inFlight, entries, pred = () => true) => partitionSuperseded(inFlight, entries, pred, REPO);++ it('splits cached-superseded out of the actionable set and annotates the verdict', () => {+ const other = branch({ branch: 'feature/live', tip: 'zzz', dirtyPaths: [], collisionPaths: [] });+ const { actionable, superseded } = split([branch(), other], [entry()]);+ expect(actionable.map((b) => b.branch)).toEqual(['feature/live']);+ expect(superseded).toHaveLength(1);+ expect(superseded[0].verdict.replacedBy).toEqual(['fff999']);+ });++ it('leaves everything actionable when the ledger is empty', () => {+ const { actionable, superseded } = split([branch()], []);+ expect(actionable).toHaveLength(1);+ expect(superseded).toEqual([]);+ });++ it('consults the reachability predicate per entry', () => {+ expect(split([branch()], [entry()], () => false).actionable).toHaveLength(1);+ });++ it('ignores verdicts recorded against a different repo', () => {+ const { actionable, superseded } = split([branch()], [entry({ repoPath: '/other-app' })]);+ expect(actionable).toHaveLength(1);+ expect(superseded).toEqual([]);+ });++ it('preserves the incoming priority order of the actionable set', () => {+ const a = branch({ branch: 'claim/one' });+ const b = branch({ branch: 'feature/two' });+ const c = branch({ branch: 'scratch' });+ const { actionable } = split([a, b, c], [entry()]);+ expect(actionable.map((x) => x.branch)).toEqual(['claim/one', 'feature/two', 'scratch']);+ });++ it('tolerates a null in-flight set', () => {+ expect(split(null, [entry()])).toEqual({ actionable: [], superseded: [] });+ });+});++describe('formatSupersededForPrompt', () => {+ it('is empty when nothing is cached — no dead section in the prompt', () => {+ expect(formatSupersededForPrompt([])).toBe('');+ expect(formatSupersededForPrompt(undefined)).toBe('');+ });++ it('names the branch, the replacing commits, the backup and the reap commands', () => {+ const out = formatSupersededForPrompt([{+ ...branch(),+ verdict: entry({+ was: 'honor the video backend pin',+ replacedByNote: 'backendPin.js now exports resolveVideoBackendPin()',+ backupPatch: 'data/cos/abandoned-worktree-backups/agent-dead.patch',+ decidedAt: '2026-08-12T00:00:00.000Z'+ })+ }]);+ expect(out).toContain('DO NOT ANALYZE');+ expect(out).toContain('cos/task-x/agent-dead');+ expect(out).toContain('honor the video backend pin');+ expect(out).toContain('fff999');+ expect(out).toContain('agent-dead.patch');+ expect(out).toContain('git worktree remove --force /repo/data/cos/worktrees/agent-dead');+ expect(out).toContain('git branch -D cos/task-x/agent-dead');+ });++ it('tells the agent the reap is a human action, not something to run', () => {+ const out = formatSupersededForPrompt([{ ...branch(), verdict: entry() }]);+ expect(out).toMatch(/do NOT run them/i);+ });+});++describe('recordVerdictInstruction', () => {+ it('names the ledger file and makes repoPath + replacedBy mandatory', () => {+ const text = recordVerdictInstruction();+ expect(text).toContain('data/cos/branch-reconcile-verdicts.json');+ expect(text).toContain('"verdict": "SUPERSEDED"');+ expect(text).toContain('"repoPath"');+ expect(text).toMatch(/`repoPath` and `replacedBy` are both mandatory/);+ });+});