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(branch-reconcile): check a branch's work is still wanted before finishing it
[._.]/ Adam Eivy2fbf7d921abb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7ce05674bf..9de9def95a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -39,6 +39,9 @@## CoS branch reconciliation+- **Branch Reconciliation now checks whether a branch's work is still wanted before it finishes it.** A branch that sat while the default branch moved may hold a feature that was solved there a different way in the meantime — merging it then undoes what already shipped. Nothing about the branch reveals this: its tests pass, its changelog entry reads fine, and the merge conflict it produces is perfectly resolvable. So each branch handed to the agent now arrives with how far behind it is and, more importantly, the list of files the default branch has *also* changed since that branch diverged. Reading those is step one, before any commit or conflict resolution, and if the default branch already solves that branch's problem the agent reports it as superseded and leaves the branch completely alone rather than merging a regression.+- The reconciliation agent is now told outright that a conflict it can resolve is not evidence the work is still needed — that is the specific path by which a superseded branch gets merged looking deliberate.+- Every branch is rebased onto the default branch *before* its pull request opens, so the PR is conflict-free rather than needing a merge patched up afterward, and the touched workspaces' test suites must be seen passing after that rebase before anything is pushed. A rebase onto a moved default branch can break code that passed on the old one.- **Work an agent left uncommitted is no longer invisible.** When a CoS agent exits before committing — it finished, crashed, or hit the idle reaper — the whole deliverable stays uncommitted in its worktree while its branch still points at the commit it started from. Branch Reconciliation read that branch as "already merged," correctly refused to delete a worktree with unsaved changes, and reported nothing further, so every run announced "no branches in flight" while real work sat there. Three such branches had accumulated on one install. These are now surfaced as in-flight and handed to the reconciliation agent, which reads the uncommitted changes, commits and ships them if the work is finished, and reports what's missing if it isn't — and never deletes them either way.- A worktree whose agent is still running is untouched, as before. So is a human `/claim` worktree, a locked worktree, and anything outside the machine-owned `agent-*` namespace. If the running-agent list can't be determined, every worktree stays protected rather than being assumed abandoned.- The new behavior can be turned off per app with the `finishAbandoned` action toggle, alongside the existing cleanup/PR/conflict/merge toggles.diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex c1995e1ac3..945617021e 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -191,15 +191,92 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {return !activeAgentIds.has(basename);}+/**+ * A worktree's real (non-lockfile) uncommitted paths, or [] when clean/unreadable.+ * @param {string} worktreePath+ * @returns {Promise<string[]>}+ */+async function worktreeDirtyPaths(worktreePath) {+ const { stdout } = await execGit(['status', '--porcelain'], worktreePath, { ignoreExitCode: true })+ .catch(() => ({ stdout: '' }));+ const dirt = classifyWorktreeDirt(stdout);+ return dirt.hasRealChanges ? (dirt.realChangePaths || []) : [];+}+/*** Is a worktree's working tree carrying real (non-lockfile) uncommitted changes?* @param {string} worktreePath* @returns {Promise<boolean>}*/async function isWorktreeDirty(worktreePath) {- const { stdout } = await execGit(['status', '--porcelain'], worktreePath, { ignoreExitCode: true })- .catch(() => ({ stdout: '' }));- return classifyWorktreeDirt(stdout).hasRealChanges;+ return (await worktreeDirtyPaths(worktreePath)).length > 0;+}++/** Newline-separated git stdout → trimmed non-empty lines. */+const gitLines = (stdout) => (stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);++// Files nearly every branch touches. They collide constantly and are real merge+// conflicts, so they stay in the collision list — but they never carry evidence+// that a feature was reimplemented, so they sort last and don't crowd out the+// source files that do. Without this the changelog leads the list alphabetically+// on virtually every branch.+const CHURN_COLLISION_RE = /(^|\/)(\.changelog\/|CHANGELOG|README|package-lock\.json$|package\.json$|PLAN\.md$)/i;++/** Sort collisions so supersession-bearing source files come before churn files. */+const byCollisionSignal = (a, b) => {+ const rank = (p) => (CHURN_COLLISION_RE.test(p) ? 1 : 0);+ return rank(a) - rank(b) || a.localeCompare(b);+};++/**+ * How far a branch has drifted from the default branch, and — the part that+ * matters — WHICH of the files it touches the default branch has ALSO changed+ * since the two diverged.+ *+ * That intersection is the deterministic evidence for "is this work still+ * needed?". A branch that sat for a hundred commits may hold a feature someone+ * solved a different (usually better) way on the default branch in the meantime;+ * merging it then REGRESSES the default branch rather than adding to it. Neither+ * `git status` nor the branch's own changelog entry shows this — both look like+ * healthy work-in-progress. The collision set does, and it points the agent at+ * exactly the files to read before it commits to anything.+ *+ * Covers uncommitted work too: for an abandoned worktree the branch has no+ * commits of its own, so the dirty paths ARE the change set, and a `merge-tree`+ * probe against the branch tip would report a clean merge while the real+ * collision sits in the working tree.+ *+ * Every field degrades to a safe unknown (`null` counts, `[]` collisions) rather+ * than a wrong answer — a git failure here must not read as "no drift".+ *+ * @param {string} repoPath+ * @param {string} branch+ * @param {string} defaultBranch+ * @param {string[]} [dirtyPaths] - uncommitted paths from the branch's worktree+ * @returns {Promise<{ behind:number|null, ahead:number|null, collisionPaths:string[] }>}+ */+export async function gatherDivergence(repoPath, branch, defaultBranch, dirtyPaths = []) {+ const counts = await execGit(+ ['rev-list', '--left-right', '--count', `${defaultBranch}...${branch}`], repoPath, { ignoreExitCode: true }+ ).catch(() => null);+ const [behindRaw, aheadRaw] = (counts?.stdout || '').trim().split(/\s+/);+ const behind = Number.isFinite(Number(behindRaw)) && behindRaw !== '' ? Number(behindRaw) : null;+ const ahead = Number.isFinite(Number(aheadRaw)) && aheadRaw !== '' ? Number(aheadRaw) : null;++ const base = await execGit(['merge-base', branch, defaultBranch], repoPath, { ignoreExitCode: true })+ .catch(() => null);+ const mergeBase = (base?.stdout || '').trim();+ if (!mergeBase) return { behind, ahead, collisionPaths: [] };++ const [defaultChanged, branchChanged] = await Promise.all([+ execGit(['diff', '--name-only', mergeBase, defaultBranch], repoPath, { ignoreExitCode: true }).catch(() => null),+ execGit(['diff', '--name-only', mergeBase, branch], repoPath, { ignoreExitCode: true }).catch(() => null)+ ]);+ const defaultSet = new Set(gitLines(defaultChanged?.stdout));+ if (defaultSet.size === 0) return { behind, ahead, collisionPaths: [] };++ const touched = new Set([...gitLines(branchChanged?.stdout), ...dirtyPaths]);+ return { behind, ahead, collisionPaths: [...touched].filter((p) => defaultSet.has(p)).sort(byCollisionSignal) };}/**@@ -226,7 +303,8 @@ 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, abandonedAgentWorktree, openPr }+ * { branch, hasUpstream, isMerged, hasWorktree, worktreePath, worktreeDirty, dirtyPaths,+ * behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }*/export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null }) {const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);@@ -254,7 +332,9 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdconst worktreePath = wt?.path || null;const worktreeLocked = Boolean(wt?.locked);const worktreeAge = worktreePath ? await worktreeAgeMs(worktreePath) : null;- const worktreeDirty = worktreePath ? await isWorktreeDirty(worktreePath) : false;+ const dirtyPaths = worktreePath ? await worktreeDirtyPaths(worktreePath) : [];+ const worktreeDirty = dirtyPaths.length > 0;+ const divergence = await gatherDivergence(repoPath, b.name, defaultBranch, dirtyPaths);// getBranches' `merged` is ancestor-based (misses squash/rebase); confirm// the harder cases via isBranchMergedInto (covers squash + rebase). Short// -circuit when the cheap check already proved it merged.@@ -268,6 +348,10 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdworktreeLocked,worktreeAgeMs: worktreeAge,worktreeDirty,+ dirtyPaths,+ behind: divergence.behind,+ ahead: divergence.ahead,+ collisionPaths: divergence.collisionPaths,abandonedAgentWorktree: isAbandonedAgentWorktree({ path: worktreePath, locked: worktreeLocked, activeAgentIds }),openPr: prsByHead.get(b.name) || null});@@ -388,6 +472,53 @@ export function filterActionable(inFlight, actions) {});}+// A branch is only worth finishing if its work is still NEEDED. Anything that+// sat while the default branch moved may hold a feature that was since solved a+// different way there — merging it then REGRESSES the default branch instead of+// adding to it, and it is the one failure a "verify the work is complete" gate+// cannot catch, because the work IS complete; it is just no longer wanted.+//+// The tell is never `git status` or the branch's own changelog entry — both read+// as healthy WIP. It is the collision set: the files this branch touches that the+// default branch has also changed since they diverged. So the deterministic pass+// hands the agent that list, and this gate makes reading it step one, BEFORE any+// commit, rebase, or conflict resolution. Resolving a conflict is the trap —+// mechanically reconcilable and semantically wrong, it launders a regression into+// a merge that looks intentional.+//+// Precedent: a branch 101 commits behind held "merge a task's PR on green CI when+// no reviewer is configured", whose collision files (agentWorktreeCleanup.js,+// the CoS constants) had meanwhile grown a strictly richer three-way completion+// policy on the default branch. Its tests passed and its changelog entry read+// fine; only the collision files showed it had been superseded.+const supersessionGate = ({ collisionPaths = [], behind } = {}) => {+ const drift = typeof behind === 'number' && behind > 0+ ? `This branch is ${behind} commit(s) behind the default branch.`+ : 'This branch may have drifted from the default branch.';+ if (!collisionPaths.length) {+ return `${drift} Nothing it touches has changed on the default branch since it diverged, so supersession is unlikely — but if a rebase does surface a conflict, treat it as the signal below rather than something to mechanically resolve.`;+ }+ // The full set already has its own line in the prompt block; the prose needs+ // only enough to make the instruction concrete. Collisions are ranked+ // signal-first, so the head of the list is the part worth naming inline.+ const shown = collisionPaths.slice(0, 6);+ const more = collisionPaths.length > shown.length ? ` (+${collisionPaths.length - shown.length} more, listed above)` : '';+ return [+ `${drift} **Before anything else, check the work is still needed.**`,+ `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.',+ 'Only once you have confirmed the work is still needed, continue.'+ ].join(' ');+};++// Nothing reaches a PR unverified. `/do:pr` runs its own reviewer loop, but the+// branch has to be sound BEFORE that — a rebase onto a default branch that moved+// can break code that passed on the old base, and CI failing on an already-open+// PR costs a whole round trip. Rebase first (so the PR is conflict-free by+// construction), then run the touched workspaces' suites locally.+const verifyGate = 'Rebase onto the default branch before opening or updating a PR, so the PR is conflict-free by construction rather than needing a merge fixed up later. Then run the test suites for the workspaces the diff touches (`cd server && npm test`, `cd client && npm test`) plus lint, and read the result — the rebase can break code that passed on the old base. If anything fails, fix it on the branch and re-run; if you cannot get it green, stop and report which suite fails and why. Never push a branch whose tests you have not seen pass.';+// The terminal state of an auto-mergeable branch is MERGED — not "PR opened",// not "PR green and waiting". Every drive-to-merge instruction ends with this// tail so the agent waits CI out IN-SESSION instead of handing back an open PR@@ -411,12 +542,14 @@ const driveToMerge = (pr) => [* Per-state instruction to the coordinator/sub-agent.* @param {string} state* @param {object} actions - per-app action toggles- * @param {{ prNumber?: number, worktreePath?: string }} [ctx] - the branch's open PR- * number (when it has one) and its worktree path (ABANDONED_WIP needs it — the- * uncommitted work only exists there, never in the primary checkout)+ * @param {{ prNumber?: number, worktreePath?: string, collisionPaths?: string[], behind?: number }} [ctx]+ * the branch's open PR number (when it has one), its worktree path+ * (ABANDONED_WIP needs it — the uncommitted work only exists there, never in+ * the primary checkout), and the drift facts feeding the supersession gate*/-export function desiredEndState(state, actions, { prNumber, worktreePath } = {}) {+export function desiredEndState(state, actions, { prNumber, worktreePath, collisionPaths, behind } = {}) {const pr = prNumber ? String(prNumber) : '<num>';+ const stillNeeded = supersessionGate({ collisionPaths, behind });if (state === 'ABANDONED_WIP') {// The branch has NO commits of its own — the entire deliverable is the// uncommitted tree. So the first move is to READ it, and the loudest rule is@@ -429,12 +562,12 @@ export function desiredEndState(state, actions, { prNumber, worktreePath } = {})const bail = 'If it is NOT finished, do not commit it and do not delete it — leave every file exactly as it is and report what the work appears to be, how far it got, and what is missing, so a human can decide whether to finish or discard it.';const commit = 'If it IS finished, commit it on this branch (a message that states what changed and why — never a bare "wip"), then ship it with `/do:pr --no-merge` (by hand, if slash commands are unavailable: self-review the diff, `git push -u origin <branch>`, then `gh pr create` with a Summary + Test plan).';if (!actionOn(actions, 'autoMerge')) {- return `${assess} ${bail} ${commit} Do NOT merge (auto-merge is disabled) — stop once the PR is open and report its URL.`;+ return `${stillNeeded} ${assess} ${bail} ${commit} ${verifyGate} Do NOT merge (auto-merge is disabled) — stop once the PR is open and report its URL.`;}- return `${assess} ${bail} ${commit} ${driveToMerge(pr)}`;+ return `${stillNeeded} ${assess} ${bail} ${commit} ${verifyGate} ${driveToMerge(pr)}`;}if (state === 'NEEDS_PR') {- const verify = 'Verify the branch\'s work is complete and ready (tests pass, no stubs/TODO markers, changelog present). If NOT ready, report it as incomplete and leave the branch untouched — do not open a half-baked PR.';+ const verify = `${stillNeeded} Verify the branch's work is complete and ready (tests pass, no stubs/TODO markers, changelog present). If NOT ready, report it as incomplete and leave the branch untouched — do not open a half-baked PR.`;// `--no-merge` is passed explicitly on BOTH paths — not to disable merging,// but to keep the merge decision here rather than inside slashdo. Under// `--merge`, /do:pr first tries GitHub-native auto-merge and reports the PR@@ -445,12 +578,16 @@ export function desiredEndState(state, actions, { prNumber, worktreePath } = {})// (which may set `merge: true`) can't decide it either way.const openPr = '`/do:pr --no-merge` — its reviewer loop runs, and the PR is left for the gate below rather than queued for auto-merge (by hand, if slash commands aren\'t available in your context: self-review the diff and fix what you find, `git push -u origin <branch>`, then `gh pr create` with a Summary + Test plan)';if (!actionOn(actions, 'autoMerge')) {- return `${verify} If ready, ship it with ${openPr}. Do NOT merge (auto-merge is disabled) — stop once the PR is open and report its URL.`;+ return `${verify} If ready, ship it with ${openPr}. ${verifyGate} Do NOT merge (auto-merge is disabled) — stop once the PR is open and report its URL.`;}- return `${verify} If ready, ship it with ${openPr}. ${driveToMerge(pr)}`;+ return `${verify} If ready, ship it with ${openPr}. ${verifyGate} ${driveToMerge(pr)}`;}if (state === 'CONFLICTED') {- return 'Rebase the branch onto the default branch, resolve all conflicts, run the tests, and push.';+ // The conflict IS the supersession signal here — this PR has already been+ // told by GitHub that it collides with the default branch, so "resolve the+ // conflicts" without first asking whether the work is still wanted is+ // precisely how a superseded branch gets merged looking deliberate.+ return `${stillNeeded} If it is still needed: rebase the branch onto the default branch, resolve all conflicts, run the tests, and push. ${verifyGate}`;}// IN_REVIEWconst canMerge = actionOn(actions, 'autoMerge');@@ -495,7 +632,20 @@ export function formatInFlightForPrompt(inFlight, { defaultBranch, actions }) {const pr = b.openPr ? ` — PR #${b.openPr.number} (${b.openPr.mergeable})${b.openPr.url ? ` ${b.openPr.url}` : ''}` : ' — no PR';lines.push(`### \`${b.branch}\` [${b.state}]${pr}`);if (b.worktreePath) lines.push(`- Worktree: \`${b.worktreePath}\`${b.state === 'ABANDONED_WIP' ? ' (holds UNCOMMITTED work — read it before doing anything)' : ''}`);- lines.push(`- Do: ${desiredEndState(b.state, actions, { prNumber: b.openPr?.number, worktreePath: b.worktreePath })}`);+ if (typeof b.behind === 'number') {+ lines.push(`- Drift: ${b.behind} commit(s) behind \`${defaultBranch}\`${typeof b.ahead === 'number' ? `, ${b.ahead} ahead` : ''}`);+ }+ // Listed as their own line, not just inside the prose instruction, so the+ // agent can act on the set directly (open these files) without re-deriving it.+ if (b.collisionPaths?.length) {+ lines.push(`- Also changed on \`${defaultBranch}\` since this branch diverged (**read these first — they are where supersession shows up**): ${b.collisionPaths.map((p) => `\`${p}\``).join(', ')}`);+ }+ lines.push(`- Do: ${desiredEndState(b.state, actions, {+ prNumber: b.openPr?.number,+ worktreePath: b.worktreePath,+ collisionPaths: b.collisionPaths,+ behind: b.behind+ })}`);lines.push('');}return lines.join('\n');diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex fda3853d67..b5c4ec8c81 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -22,8 +22,17 @@ vi.mock('../lib/execGit.js', () => ({vi.mock('./worktreeManager.js', () => ({listWorktrees: vi.fn(async () => []),forceRemoveWorktreeDir: vi.fn(async () => {}),- // Real pure classifier semantics: empty porcelain = clean.- classifyWorktreeDirt: vi.fn((p) => ({ hasRealChanges: Boolean((p || '').trim()) })),+ // Real pure classifier semantics: empty porcelain = clean, and every non-empty+ // line is a real change path (the suite never feeds it lockfile churn). The+ // paths matter — gatherDivergence intersects them with the default branch's+ // changes to find work that may have been superseded.+ classifyWorktreeDirt: vi.fn((p) => {+ const lines = (p || '').split('\n').map((l) => l.trim()).filter(Boolean);+ return {+ hasRealChanges: lines.length > 0,+ realChangePaths: lines.map((l) => l.replace(/^\s*\S+\s+/, ''))+ };+ }),isHumanClaimWorktree: vi.fn((id) => typeof id === 'string' && id.startsWith('claim-'))}));vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));@@ -39,7 +48,7 @@ vi.mock('../lib/fileUtils.js', () => ({import {classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,- isAbandonedAgentWorktree,+ isAbandonedAgentWorktree, gatherDivergence,actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature} from './branchReconcile.js';import * as git from './git.js';@@ -302,6 +311,78 @@ describe('isAbandonedAgentWorktree', () => {});});+describe('gatherDivergence', () => {+ // Drives execGit by subcommand so each probe can be answered independently.+ const mockGit = ({ counts = '3\t2', mergeBase = 'base1', defaultChanged = '', branchChanged = '' } = {}) => {+ execGit.mockImplementation(async (args) => {+ if (args[0] === 'rev-list') return { stdout: counts, exitCode: 0 };+ if (args[0] === 'merge-base') return { stdout: mergeBase, exitCode: 0 };+ if (args[0] === 'diff' && args[args.length - 1] === 'main') return { stdout: defaultChanged, exitCode: 0 };+ if (args[0] === 'diff') return { stdout: branchChanged, exitCode: 0 };+ return { stdout: '', exitCode: 0 };+ });+ };++ it('reports drift counts and the files BOTH sides changed since the merge base', async () => {+ mockGit({+ counts: '101\t1',+ defaultChanged: 'server/services/agentWorktreeCleanup.js\nserver/lib/prDisposition.js\ndocs/UNRELATED.md',+ branchChanged: 'server/services/agentWorktreeCleanup.js\nserver/services/prAutoMerge.js'+ });+ const d = await gatherDivergence('/repo', 'stale-branch', 'main');+ expect(d.behind).toBe(101);+ expect(d.ahead).toBe(1);+ // Only the shared file — the branch's own new file and main's unrelated doc are not collisions.+ expect(d.collisionPaths).toEqual(['server/services/agentWorktreeCleanup.js']);+ });++ // An abandoned worktree's branch has NO commits, so its change set lives+ // entirely in the working tree. Probing only committed diffs would report a+ // clean, collision-free branch while the real collision sits uncommitted —+ // exactly the case this whole check exists for.+ it('counts uncommitted paths as part of the branch\'s change set', async () => {+ mockGit({ defaultChanged: 'server/services/agentWorktreeCleanup.js', branchChanged: '' });+ const d = await gatherDivergence('/repo', 'abandoned', 'main', ['server/services/agentWorktreeCleanup.js', 'server/services/prAutoMerge.js']);+ expect(d.collisionPaths).toEqual(['server/services/agentWorktreeCleanup.js']);+ });++ // Every branch touches the changelog, so alphabetical order would put it first+ // on virtually every entry and bury the source files that actually reveal a+ // reimplementation. It stays listed (it IS a real conflict) but ranks last.+ it('ranks always-churning files (changelog, lockfiles, README) below source files', async () => {+ const shared = '.changelog/NEXT.md\nserver/lib/README.md\npackage-lock.json\nserver/services/agentWorktreeCleanup.js\nclient/src/components/cos/constants.js';+ mockGit({ defaultChanged: shared, branchChanged: shared });+ const { collisionPaths } = await gatherDivergence('/repo', 'b', 'main');+ expect(collisionPaths).toEqual([+ 'client/src/components/cos/constants.js',+ 'server/services/agentWorktreeCleanup.js',+ '.changelog/NEXT.md',+ 'package-lock.json',+ 'server/lib/README.md'+ ]);+ });++ it('reports no collisions when the default branch has not touched the same files', async () => {+ mockGit({ defaultChanged: 'docs/OTHER.md', branchChanged: 'server/services/thing.js' });+ expect((await gatherDivergence('/repo', 'b', 'main')).collisionPaths).toEqual([]);+ });++ // A git failure must degrade to "unknown", never to a confident "no drift" —+ // the gate keys off these values to decide how hard to look for supersession.+ it('degrades to null counts and no collisions when git fails', async () => {+ execGit.mockRejectedValue(new Error('not a git repository'));+ const d = await gatherDivergence('/repo', 'b', 'main');+ expect(d).toEqual({ behind: null, ahead: null, collisionPaths: [] });+ });++ it('degrades when the branches share no history (no merge base)', async () => {+ mockGit({ counts: '5\t5', mergeBase: '' });+ const d = await gatherDivergence('/repo', 'orphan', 'main');+ expect(d.behind).toBe(5);+ expect(d.collisionPaths).toEqual([]);+ });+});+describe('reconcile', () => {it('cleans merged, returns in-flight + wip partitions', async () => {git.getBranches.mockResolvedValue([@@ -409,6 +490,48 @@ describe('desiredEndState', () => {expect(desiredEndState('IN_REVIEW', { autoMerge: false })).toContain('Do NOT merge');});+ // The supersession gate is the answer to "is this work still needed?" — the one+ // failure a completeness check cannot catch, because superseded work IS+ // complete. It has to reach every state that can end in a merge, and it has to+ // come FIRST: once an agent has resolved the conflicts, the regression looks+ // like a deliberate merge.+ it.each(['ABANDONED_WIP', 'NEEDS_PR', 'CONFLICTED'])('opens the %s instruction with the supersession gate', (state) => {+ const instruction = desiredEndState(state, {}, {+ behind: 101,+ collisionPaths: ['server/services/agentWorktreeCleanup.js', 'client/src/components/cos/constants.js'],+ worktreePath: '/wt/agent-deadbeef'+ });+ expect(instruction).toContain('101 commit(s) behind');+ expect(instruction).toContain('`server/services/agentWorktreeCleanup.js`');+ expect(instruction).toContain('SUPERSEDED');+ expect(instruction).toContain('still needed');+ // Ordering: the gate precedes any instruction to commit/rebase/resolve.+ const gateAt = instruction.indexOf('still needed');+ for (const later of ['/do:pr', 'resolve all conflicts', 'commit it on this branch']) {+ const at = instruction.indexOf(later);+ if (at !== -1) expect(at).toBeGreaterThan(gateAt);+ }+ });++ it('names a resolvable conflict as NOT proof the work is wanted', () => {+ const instruction = desiredEndState('CONFLICTED', {}, { behind: 40, collisionPaths: ['server/services/thing.js'] });+ expect(instruction).toContain('a conflict you can resolve is exactly how a regression gets in');+ });++ it('softens the gate but keeps it when nothing collides', () => {+ const instruction = desiredEndState('NEEDS_PR', {}, { behind: 2, collisionPaths: [] });+ expect(instruction).toContain('supersession is unlikely');+ expect(instruction).not.toContain('read the default branch\'s current version');+ });++ // A rebase onto a moved default branch can break code that passed on the old+ // base, and a red PR costs a full round trip to notice.+ it.each(['ABANDONED_WIP', 'NEEDS_PR', 'CONFLICTED'])('makes %s rebase and run the suites before pushing', (state) => {+ const instruction = desiredEndState(state, {}, { worktreePath: '/wt/agent-deadbeef' });+ expect(instruction).toContain('Rebase onto the default branch before opening or updating a PR');+ expect(instruction).toContain('Never push a branch whose tests you have not seen pass');+ });+it('tells ABANDONED_WIP to read the worktree first, refuse a half-finished commit, then ship', () => {const instruction = desiredEndState('ABANDONED_WIP', {}, { worktreePath: '/wt/agent-deadbeef' });expect(instruction).toContain('/wt/agent-deadbeef');@@ -538,4 +661,30 @@ describe('formatInFlightForPrompt', () => {expect(block).toContain('### `next/issue-2` [NEEDS_PR] — no PR');expect(block).toContain('- Do: ');});++ // The collision set gets its own line, not just prose inside the Do: text, so+ // the agent can open those files directly instead of re-deriving the set.+ it('surfaces drift and the collision files as their own lines', () => {+ const block = formatInFlightForPrompt([{+ branch: 'cos/task-x/agent-deadbeef',+ state: 'ABANDONED_WIP',+ worktreePath: '/wt/agent-deadbeef',+ behind: 101,+ ahead: 0,+ collisionPaths: ['server/services/agentWorktreeCleanup.js']+ }], { defaultBranch: 'main', actions: {} });+ expect(block).toContain('- Drift: 101 commit(s) behind `main`, 0 ahead');+ expect(block).toContain('**read these first — they are where supersession shows up**');+ expect(block).toContain('`server/services/agentWorktreeCleanup.js`');+ expect(block).toContain('holds UNCOMMITTED work');+ });++ it('omits the drift and collision lines when there is nothing to report', () => {+ const block = formatInFlightForPrompt(+ [{ branch: 'fresh', state: 'NEEDS_PR', behind: 0, ahead: 3, collisionPaths: [] }],+ { defaultBranch: 'main', actions: {} }+ );+ expect(block).toContain('- Drift: 0 commit(s) behind');+ expect(block).not.toContain('supersession shows up');+ });});diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex a5863e9302..b8a154bcfc 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -155,18 +155,37 @@ describe('taskPromptDefaults integrity snapshot', () => {// branch. v1's blanket "never merge unreviewed work" rule read as a veto on// the per-branch merge instruction, so a coordinator opened a PR and exited// while CI was still running — leaving a green, MERGEABLE PR sitting open.- it('branch-reconcile v2 makes merged (not PR-opened) the end state, preserving the v1 default', () => {+ it('branch-reconcile keeps merged (not PR-opened) as the end state', () => {const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];expect(current).toContain('not finished until it IS merged');expect(current).not.toContain('never merge unreviewed work');- expect(PROMPT_VERSIONS['branch-reconcile']).toBe(2);- // The outgoing v1 default carried the blanket ban and no CI-wait rule; it is+ // The v1 default carried the blanket ban and no CI-wait rule; it is// preserved verbatim so installs holding it are recognized and upgraded.- const previous = PREVIOUS_DEFAULT_PROMPTS['branch-reconcile'];- const v1 = previous[previous.length - 1];+ const [v1] = PREVIOUS_DEFAULT_PROMPTS['branch-reconcile'];expect(v1).toContain('never merge unreviewed work');expect(v1).not.toContain('not finished until it IS merged');expect(v1).not.toBe(current);});++ // branch-reconcile v3: a branch can be finished, correct, and still unwanted —+ // its problem solved a different way on the default branch while it sat. v2 had+ // nowhere to put that: every branch was merge-or-blocked, so the coordinator's+ // only route for a superseded branch was to resolve its conflicts and merge a+ // regression. The tell is the conflict itself, which is why the prompt has to+ // say outright that a resolvable conflict proves nothing.+ it('branch-reconcile v3 makes SUPERSEDED an outcome and denies conflicts as evidence, preserving the v2 default', () => {+ const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];+ expect(current).toContain('SUPERSEDED');+ expect(current).toContain('not evidence the work is still needed');+ expect(current).toContain('Nothing reaches a PR unverified');+ expect(PROMPT_VERSIONS['branch-reconcile']).toBe(3);++ const previous = PREVIOUS_DEFAULT_PROMPTS['branch-reconcile'];+ const v2 = previous[previous.length - 1];+ // v2 already drove branches to merged, but had no supersession concept.+ expect(v2).toContain('not finished until it IS merged');+ expect(v2).not.toContain('SUPERSEDED');+ expect(v2).not.toBe(current);+ });});diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 46e3603267..38659aeb84 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -24,7 +24,7 @@"do-replan": "59a57f1bb445138c30ab4fa23630c6f8","jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5","branch-cleanup": "8fdeb4acc2749816a47ca318b6602721",- "branch-reconcile": "ecb0621588a751b1383ecd89cf514382",+ "branch-reconcile": "16479f4b64395103fd222dc9608830b1","issue-reconcile": "a30f5d76b980bc9016f576047c9d5bb1","pr-reviewer": "add27b67daa6aa2c75717ac96a6bd625","pr-reviewer-security": "2050297d1cdb081a8576a781828ee44f",@@ -44,7 +44,7 @@"code-reviewer-b": 1,"reference-watch": 3,"pr-watcher": 1,- "branch-reconcile": 2,+ "branch-reconcile": 3,"issue-reconcile": 3,"refresh-local-llm-catalog": 1,"security": 2,@@ -149,7 +149,8 @@"9c7508598ee772d1cee8f609f9ed7372"],"branch-reconcile": [- "7ef2b5f7d8f05937d4912b26ad45f42e"+ "7ef2b5f7d8f05937d4912b26ad45f42e",+ "ecb0621588a751b1383ecd89cf514382"],"issue-reconcile": ["c57a39aaa118173a496f030f5878bfc1",diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex cfcb8b235c..4a1b5d94f1 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -4833,6 +4833,11 @@ IMPORTANT: Always use \`git pull --rebase --autostash\` before pushing (dev bran// the terminal state for an auto-mergeable branch. v1's blanket "never merge// unreviewed work" rule read as a veto on the per-branch merge instruction,// so a NEEDS_PR branch ended with a green PR left sitting open.+ //+ // (v2 follows this entry; it is superseded by v3, which adds SUPERSEDED as a+ // first-class outcome — neither v1 nor v2 gave the coordinator anywhere to+ // put "this work already shipped a different way on the default branch", so+ // a stale branch's only paths were merge or "blocked".)`[Improvement: {appName}] Branch & PR ReconciliationYou are the coordinator for finishing {appName}'s unfinished local git work. The scheduler has already run the deterministic pass (removed fully-merged, orphaned local branches + their worktrees) and handed you ONLY the branches that need judgment.@@ -4850,6 +4855,29 @@ Spawn ONE sub-agent per branch (they are independent — run them in parallel) t- Never force-push the default branch and never merge unreviewed work.- If a sub-agent reports a branch is incomplete or blocked, leave it as-is and note it in your summary.- Summarize what each branch ended up doing (PR opened / conflicts resolved / merged / left incomplete).`,+ // v2 default — superseded by v3, which adds the SUPERSEDED outcome (work+ // already shipped a different way on the default branch → report, never+ // merge) and forbids treating a resolvable conflict as proof the work is+ // still wanted.+ `[Improvement: {appName}] Branch & PR Reconciliation++You are the coordinator for finishing {appName}'s unfinished local git work. The scheduler has already run the deterministic pass (removed fully-merged, orphaned local branches + their worktrees) and handed you ONLY the branches that need judgment.++Repository: {repoPath}++Each branch listed below is a LOCAL branch in THIS clone of {appName}. On a machine that is a federated sync peer, branches created on OTHER machines exist here only as remote-tracking refs (\`origin/*\`) and are deliberately NOT listed — never open, rebase, or merge anything that is not in the list below.++{inFlightBranches}++Spawn ONE sub-agent per branch (they are independent — run them in parallel) to carry out that branch's "Do:" instruction, each working in the branch's existing worktree when it has one.++## Rules+- Work ONLY on the branches listed above. Never touch a branch that is not listed.+- Never force-push the default branch.+- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.+- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.+- If a sub-agent reports a branch is incomplete or blocked, leave it as-is and note it in your summary.+- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / left incomplete). When a PR is left open, name the check or review that blocked it.`,],'issue-reconcile': [diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 708e3435a7..f47ec57426 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -1273,10 +1273,13 @@ Spawn ONE sub-agent per branch (they are independent — run them in parallel) t## Rules- Work ONLY on the branches listed above. Never touch a branch that is not listed.- Never force-push the default branch.+- **A branch can be finished, correct, and still not wanted.** Work that sat while the default branch moved may have been solved there a different way in the meantime; merging it then UNDOES what already shipped. Each branch's "Do:" line opens with the files the default branch has also changed since that branch diverged — the sub-agent reads those first and reports **SUPERSEDED** if the default branch already solves that branch's problem, by any means (a differently-named function, a policy object where the branch has a boolean, a scheduled tick where the branch has a watcher). A SUPERSEDED branch is left completely untouched: no commit, no rebase, no conflict resolution, no merge.+- **A conflict you can resolve is not evidence the work is still needed.** It is the most common way a superseded branch gets merged looking deliberate — the resolution is mechanically sound and semantically a regression. Treat every conflict as a question about supersession first and a merge chore second.+- **Nothing reaches a PR unverified.** Each sub-agent rebases onto the default branch before opening or updating a PR (so the PR is conflict-free by construction), then runs the touched workspaces' test suites and lint and reads the result — a rebase can break code that passed on the old base. A branch whose tests the sub-agent has not seen pass is never pushed.- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.-- If a sub-agent reports a branch is incomplete or blocked, leave it as-is and note it in your summary.-- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / left incomplete). When a PR is left open, name the check or review that blocked it.`,+- If a sub-agent reports a branch is incomplete, superseded, or blocked, leave it as-is and note it in your summary.+- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For a SUPERSEDED branch, name the file(s) and what on the default branch replaced it, so the user can delete the branch with confidence. When a PR is left open, name the check or review that blocked it.`,'issue-reconcile': `[Improvement: {appName}] Zombie Issue Reconciliationdiff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex aa60b80099..3f3402d226 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -17,7 +17,7 @@ export const PROMPT_VERSIONS = {'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'reference-watch': 3, // v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)'pr-watcher': 1, // v1: review-and-comment default for newly-opened PRs on the app's default branch- 'branch-reconcile': 2, // v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.+ 'branch-reconcile': 3, // v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.'issue-reconcile': 3, // v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.'refresh-local-llm-catalog': 1, // v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex af7405402c..13918303d1 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -184,23 +184,32 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =* lockfile churn. Pure (testable) — callers decide what to do with the result.** @param {string} porcelain - raw `git status --porcelain` stdout- * @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], hasRealChanges: boolean }}+ * @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], realChangePaths: string[], hasRealChanges: boolean }}* - clean: no changes at all* - lockfileOnly: every change is an auto-generated lockfile (safe to discard)* - lockfilePaths: paths of those lockfiles (strip the porcelain `XY ` status prefix)+ * - realChangePaths: paths of the NON-lockfile changes, same prefix stripping.+ * Branch reconciliation intersects these with what the default branch has+ * touched since the branch diverged, to spot work that may have been+ * superseded while it sat uncommitted.* - hasRealChanges: at least one non-lockfile change (worktree must be preserved)*/export function classifyWorktreeDirt(porcelain) {const lines = (porcelain || '').split('\n').map(l => l.trim()).filter(Boolean);if (lines.length === 0) {- return { clean: true, lockfileOnly: false, lockfilePaths: [], hasRealChanges: false };+ return { clean: true, lockfileOnly: false, lockfilePaths: [], realChangePaths: [], hasRealChanges: false };}- const lockfileLines = lines.filter(line => AUTO_GENERATED_LOCKFILES.some(f => line.endsWith(f)));+ const isLockfile = (line) => AUTO_GENERATED_LOCKFILES.some(f => line.endsWith(f));+ // `R old -> new` (rename) names two paths; the post-rename path is the one+ // that exists on disk and the one a diff against the default branch reports.+ const toPath = (line) => line.replace(/^\s*\S+\s+/, '').split(' -> ').pop();+ const lockfileLines = lines.filter(isLockfile);const lockfileOnly = lockfileLines.length === lines.length;return {clean: false,lockfileOnly,- lockfilePaths: lockfileLines.map(line => line.replace(/^\s*\S+\s+/, '')),+ lockfilePaths: lockfileLines.map(toPath),+ realChangePaths: lines.filter((line) => !isLockfile(line)).map(toPath),hasRealChanges: !lockfileOnly};}diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 08b2c43bc7..8e330f3544 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -260,7 +260,7 @@ describe('Auto-generated Lockfile Detection', () => {describe('classifyWorktreeDirt (real exported helper)', () => {it('reports clean for empty / whitespace-only porcelain', () => {- expect(classifyWorktreeDirt('')).toEqual({ clean: true, lockfileOnly: false, lockfilePaths: [], hasRealChanges: false });+ expect(classifyWorktreeDirt('')).toEqual({ clean: true, lockfileOnly: false, lockfilePaths: [], realChangePaths: [], hasRealChanges: false });expect(classifyWorktreeDirt(' \n ').clean).toBe(true);expect(classifyWorktreeDirt(null).clean).toBe(true);});@@ -285,6 +285,15 @@ describe('classifyWorktreeDirt (real exported helper)', () => {expect(r.hasRealChanges).toBe(true);});+ // realChangePaths feeds branch reconciliation's supersession check — it+ // intersects them with what the default branch changed since the branch+ // diverged, so the paths must be bare and lockfile-free.+ it('extracts the non-lockfile paths, excluding lockfiles and untangling renames', () => {+ const r = classifyWorktreeDirt(' M package-lock.json\n M src/app.js\n?? src/new.js\nR src/old.js -> src/renamed.js');+ expect(r.realChangePaths).toEqual(['src/app.js', 'src/new.js', 'src/renamed.js']);+ expect(r.realChangePaths).not.toContain('package-lock.json');+ });+it('handles a trimmed first line (no leading status space)', () => {const r = classifyWorktreeDirt('M yarn.lock');expect(r.lockfileOnly).toBe(true);