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: sweep origin for merged branches nothing local points at
[._.]/ Adam Eivy98093990bc10
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 52d4cee900..d278591f31 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **Branch reconciliation now notices the branches its own cleanup leaves on the remote.** Deleting a merged local branch never touched `origin`, so every reaped branch left a remote counterpart behind that nothing local pointed at and nothing ever looked at again. Reconcile now sweeps the remote each cycle and reports those orphans, judging each one against the SHA the remote reports right now rather than a remote-tracking ref that may be arbitrarily out of date. Deletion stays opt-in and off by default: pushing a branch deletion reaches a shared forge and can't be undone locally, so an unattended cycle reports and leaves everything in place. Peer safety comes from the branch's state rather than its owner — a branch is only ever deletable once the default branch already contains its work, so no machine can lose anything, and an unmerged remote-only branch (which is what a federated peer's in-progress work looks like from here) is reported and never touched. A remote that can't be read, a local branch list that can't be read, and a commit this clone has never fetched all fail closed to report-only rather than guessing.+- **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.diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 22cc413f72..d62303e2a9 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -9,11 +9,17 @@* coordinator CoS agent — this module never spawns an agent, so it stays pure* enough to unit-test.*- * PEER SAFETY: only `refs/heads/` (local) branches are ever considered. A branch+ * PEER SAFETY: only `refs/heads/` (local) branches are ever *driven*. A branch* created on a federated peer exists here only as a remote-tracking ref- * (`origin/*`), never as a local branch, so it is structurally invisible. We- * never author-filter — every machine shares one GitHub login, so authorship- * can't distinguish machines; local-branch existence can.+ * (`origin/*`), never as a local branch, so it is structurally invisible to the+ * classifier. We never author-filter — every machine shares one GitHub login, so+ * authorship can't distinguish machines; local-branch existence can.+ *+ * The one thing that DOES look at the remote is the orphan sweep+ * (`reapOrphanedRemotes`), and it stays peer-safe by only ever deleting a remote+ * branch whose work is already merged into the default branch — a state in which+ * no machine, ours or a peer's, can lose anything. An unmerged remote-only branch+ * is reported, never touched.*/import { stat } from 'node:fs/promises';@@ -344,6 +350,173 @@ export async function gatherDivergence(repoPath, branch, defaultBranch, dirtyPatreturn { behind, ahead, collisionPaths: [...touched].filter((p) => defaultSet.has(p)).sort(byCollisionSignal) };}+// The only remote branch-reconcile acts on. `deleteBranch(…, { remote: true })`+// hardcodes `git push origin --delete`, so a branch tracking anything else is+// reported rather than reaped — there is no code path that could delete it+// correctly, and guessing one is how you delete the wrong ref.+const RECONCILED_REMOTE = 'origin';++/**+ * The remote branch name behind an upstream ref, or null when the branch tracks+ * no remote or tracks one we don't reconcile. Pure.+ *+ * `%(upstream:short)` renders as `origin/<branch>` — and `<branch>` may itself+ * contain slashes (`origin/cos/task-x/agent-y`), so this strips exactly the+ * `origin/` prefix rather than splitting on `/`.+ * @param {string|null|undefined} tracking+ * @returns {string|null}+ */+export function upstreamBranchName(tracking) {+ const prefix = `${RECONCILED_REMOTE}/`;+ if (typeof tracking !== 'string' || !tracking.startsWith(prefix)) return null;+ return tracking.slice(prefix.length) || null;+}++/**+ * Parse `git ls-remote --heads` output into branch → SHA. Pure.+ * @param {string} stdout+ * @returns {Map<string,string>}+ */+export function parseRemoteHeads(stdout) {+ const heads = new Map();+ for (const line of gitLines(stdout)) {+ const [sha, ref] = line.split(/\s+/);+ if (sha && ref?.startsWith('refs/heads/')) heads.set(ref.slice('refs/heads/'.length), sha);+ }+ return heads;+}++/**+ * Ground truth for what branches exist on `origin` right now, or `null` when the+ * remote could not be read.+ *+ * `refs/remotes/origin/*` is deliberately NOT the source here: nothing in the+ * reconcile path fetches, so those refs reflect whenever someone last pulled.+ * Acting on a stale view means either deleting a ref that has since moved, or+ * missing one entirely — and one `ls-remote` per cycle buys the real answer.+ *+ * `null` (not an empty Map) on failure, for the same reason `getOpenPrsByHead`+ * distinguishes them: "we could not ask" must never read as "the remote has no+ * branches", which would make every branch look like its remote was already gone.+ *+ * @param {string} repoPath+ * @returns {Promise<Map<string,string>|null>}+ */+export async function listRemoteHeads(repoPath) {+ const res = await execGit(['ls-remote', '--heads', RECONCILED_REMOTE], repoPath, { ignoreExitCode: true })+ .catch(() => null);+ if (!res || res.exitCode !== 0) {+ console.error(`❌ branch-reconcile: git ls-remote ${RECONCILED_REMOTE} failed — remote branch state unknown this cycle`);+ return null;+ }+ return parseRemoteHeads(res.stdout);+}++/**+ * Which of `origin`'s branches nothing local points at any more. Pure.+ *+ * A remote branch is CLAIMED — and therefore never a sweep candidate — when+ * either a local branch shares its name, or a local branch tracks it. Both halves+ * are load-bearing: a local `foo` with no upstream still claims `origin/foo`+ * (that is where a plain `git push` would send it), and a local branch may track+ * a remote branch under a different name, which the name check alone would miss.+ * That second case is why `gatherBranchState` carries `tracking` and not just the+ * `hasUpstream` boolean.+ *+ * Protected branches and the default branch are dropped outright — a remote whose+ * local counterpart is `main` must never appear as an orphan even in a report.+ *+ * @param {Map<string,string>} remoteHeads - branch → SHA on origin+ * @param {object[]} localBranches - getBranches() records ({ name, tracking })+ * @param {{ defaultBranch: string }} ctx+ * @returns {{branch:string, sha:string}[]} orphans, name-sorted for stable output+ */+export function partitionRemoteOrphans(remoteHeads, localBranches, { defaultBranch }) {+ const claimed = new Set();+ for (const b of localBranches || []) {+ if (b?.name) claimed.add(b.name);+ const tracked = upstreamBranchName(b?.tracking);+ if (tracked) claimed.add(tracked);+ }+ const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);+ return [...(remoteHeads || new Map())]+ .filter(([branch]) => !claimed.has(branch) && !protectedSet.has(branch))+ .map(([branch, sha]) => ({ branch, sha }))+ .sort((a, b) => a.branch.localeCompare(b.branch));+}++/**+ * Sweep `origin` for branches nothing local points at, and reap the ones whose+ * work is already merged into the default branch.+ *+ * PEER SAFETY. This is the only part of reconcile that looks at the remote, and+ * a federated peer's in-progress branch looks exactly like an orphan from here —+ * it has no local counterpart on THIS machine because it never did. What makes+ * the sweep safe is not knowing whose branch it is but what state it is in:+ * deletion requires the branch to be already merged into the default branch, and+ * no machine can lose work that the default branch already carries. Anything+ * unmerged is reported and left alone, whoever pushed it.+ *+ * Merge-checked against the SHA `ls-remote` just reported, NOT `origin/<branch>`:+ * a stale remote-tracking ref can say "merged" about commits that origin has+ * since moved past, and reaping on that is how you delete unmerged work. An+ * unresolvable SHA (a branch this clone has never fetched) is `unknown`, which+ * fails closed to report-only.+ *+ * DEFAULTS TO REPORT-ONLY. `git push origin --delete` reaches off this machine to+ * a shared forge and cannot be undone from here, so it stays opt-in per the same+ * reasoning the superseded ledger uses for worktrees: automate the analysis, keep+ * the destructive step a decision someone made on purpose. Callers that have not+ * asked for `reap: true` get an unchanged, side-effect-free cycle.+ *+ * @param {string} repoPath+ * @param {string} defaultBranch+ * @param {{ reap?: boolean }} [opts] - `reap: true` actually deletes the merged+ * orphans; the default reports them under reason `reap-disabled`.+ * @returns {Promise<{reaped:string[], reported:{branch:string,reason:string}[], remoteUnavailable?:boolean}>}+ */+export async function reapOrphanedRemotes(repoPath, defaultBranch, { reap = false } = {}) {+ const [remoteHeads, localBranches] = await Promise.all([+ listRemoteHeads(repoPath),+ getBranches(repoPath).catch(() => null)+ ]);+ // Either read failing makes "nothing local claims this" unknowable, and an+ // unknowable claim set would make every remote branch look orphaned.+ if (!remoteHeads || !localBranches) {+ return { reaped: [], reported: [], remoteUnavailable: true };+ }++ const orphans = partitionRemoteOrphans(remoteHeads, localBranches, { defaultBranch });+ const reaped = [];+ const reported = [];+ for (const { branch, sha } of orphans) {+ const merged = await isBranchMergedInto(repoPath, sha, defaultBranch).catch(() => false);+ if (!merged) {+ reported.push({ branch, reason: 'unmerged-remote-only' });+ continue;+ }+ if (!reap) {+ reported.push({ branch, reason: 'reap-disabled' });+ continue;+ }+ const result = await deleteBranch(repoPath, branch, { remote: true }).catch((err) => ({ error: err.message }));+ const outcome = result?.results?.remote;+ if (result?.error || (outcome && outcome.startsWith('failed'))) {+ reported.push({ branch, reason: `remote-delete-failed: ${result.error || outcome}` });+ continue;+ }+ reaped.push(branch);+ console.log(`🔀 branch-reconcile: reaped merged orphan ${RECONCILED_REMOTE}/${branch}`);+ }+ // Report-only is silent work unless it says so — without this line a merged+ // orphan is detected every cycle and never surfaces anywhere a human looks.+ const reapable = reported.filter((r) => r.reason === 'reap-disabled').length;+ if (reapable) {+ console.log(`🔀 branch-reconcile: ${reapable} merged branch(es) on ${RECONCILED_REMOTE} nothing local points at — reap is opt-in, not deleted`);+ }+ return { reaped, reported };+}+/*** Age of a worktree directory (ms since its last structural mtime), or null when* it can't be stat'd. The worktree root's mtime is set when `git worktree add`@@ -368,8 +541,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, tip, hasUpstream, isMerged, hasWorktree, worktreePath, worktreeDirty, dirtyPaths,- * behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }+ * { branch, tip, hasUpstream, tracking, 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]);@@ -417,6 +590,10 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdbranch: b.name,tip,hasUpstream: Boolean(b.tracking),+ // Kept alongside the boolean because cleanup needs the NAME, not just the+ // fact: a branch may track a remote branch called something else, and the+ // remote-side delete has to name the right ref.+ tracking: b.tracking || null,isMerged,hasWorktree: Boolean(worktreePath),worktreePath,@@ -496,16 +673,19 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge* in-flight set (branches needing an agent) for the scheduler to dispatch.** @param {string} [repoPath=PATHS.root]- * @param {{ cleanup?: boolean, activeAgentIds?: Set<string> }} [opts] - when cleanup- * is false, merged branches are reported (in `skipped`, reason `cleanup-disabled`)- * but not deleted. `activeAgentIds` protects in-use CoS agent worktrees.- * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}+ * @param {{ cleanup?: boolean, reapRemotes?: boolean, activeAgentIds?: Set<string> }} [opts] - when+ * cleanup is false, merged branches are reported (in `skipped`, reason `cleanup-disabled`)+ * but not deleted. `reapRemotes` (default false) additionally deletes merged+ * branches left on `origin` that nothing local points at; off, they are only+ * reported — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS+ * agent worktrees.+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}* `forgeUnavailable: true` means the cycle was SKIPPED before it started because* the `gh` probe failed; `prStateUnavailable: true` means it ran but a gh read* failed mid-cycle. Either way an empty `inFlight` says nothing about the repo* and the caller must retry rather than park on it (#3358).*/-export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeAgentIds = new Set() } = {}) {+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRemotes = false, activeAgentIds = new Set() } = {}) {// On a GitHub repo every classification below depends on PR state, so an// unreadable forge makes the whole pass a guess — skip with one line rather// than report a quiet repo. Probed against THIS repo's API host@@ -550,7 +730,19 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeA? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds }): { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };- return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, prStateUnavailable };+ // Runs AFTER cleanupMerged on purpose: that step deletes merged local branches+ // and leaves their `origin/*` counterpart behind, which is precisely the orphan+ // this sweep exists to notice. Skipped entirely on a repo with no origin —+ // there is no remote to read, and probing one every cycle would log a failure+ // forever. Gated on `hasOrigin`, NOT on `origin` itself: getOriginInfo returns a+ // fully-populated object with `hasOrigin: false` for an origin-less repo, so a+ // truthiness check would pass and re-introduce exactly that per-cycle failure.+ // Report-only unless the caller opts into `reapRemotes`.+ const orphanRemotes = origin?.hasOrigin+ ? await reapOrphanedRemotes(repoPath, defaultBranch, { reap: reapRemotes })+ : { reaped: [], reported: [] };++ return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, orphanRemotes, prStateUnavailable };}/**diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 081134c668..59ddb8ae62 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -60,7 +60,8 @@ import {classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,isAbandonedAgentWorktree, gatherDivergence,actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,- branchPriorityRank, prioritizeBranches+ branchPriorityRank, prioritizeBranches,+ upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes} from './branchReconcile.js';import * as git from './git.js';import * as wt from './worktreeManager.js';@@ -985,3 +986,248 @@ describe('formatInFlightForPrompt', () => {expect(block).not.toContain('supersession shows up');});});++describe('orphaned remote branches', () => {+ // `git ls-remote --heads` output is tab-separated: <sha>\trefs/heads/<branch>.+ const lsRemote = (entries) =>+ entries.map(([branch, sha]) => `${sha}\trefs/heads/${branch}`).join('\n');++ /**+ * Route `execGit` by subcommand so a case can state what origin holds without+ * disturbing the rev-parse/rev-list calls the rest of the gather makes.+ */+ const mockRemote = (stdout, { exitCode = 0 } = {}) => {+ execGit.mockImplementation(async (args) =>+ args[0] === 'ls-remote' ? { stdout, exitCode } : { stdout: '', exitCode: 0 }+ );+ };++ describe('upstreamBranchName', () => {+ it('strips exactly the origin/ prefix, leaving slashes in the branch name', () => {+ expect(upstreamBranchName('origin/cos/task-x/agent-y')).toBe('cos/task-x/agent-y');+ });++ it('ignores a remote we cannot delete against', () => {+ // deleteBranch hardcodes `git push origin --delete`, so an upstream on any+ // other remote must not be treated as a claim WE could act on.+ expect(upstreamBranchName('upstream/main')).toBeNull();+ expect(upstreamBranchName('fork/feature')).toBeNull();+ });++ it('returns null for a branch with no upstream', () => {+ expect(upstreamBranchName('')).toBeNull();+ expect(upstreamBranchName(null)).toBeNull();+ expect(upstreamBranchName(undefined)).toBeNull();+ // `origin/` with nothing after it names no branch.+ expect(upstreamBranchName('origin/')).toBeNull();+ });+ });++ describe('parseRemoteHeads', () => {+ it('maps branch to SHA and ignores non-head refs', () => {+ const heads = parseRemoteHeads([+ 'aaa1\trefs/heads/main',+ 'bbb2\trefs/heads/feature/x',+ 'ccc3\trefs/tags/v1.0.0',+ 'ddd4\trefs/pull/42/head'+ ].join('\n'));+ expect([...heads.keys()].sort()).toEqual(['feature/x', 'main']);+ expect(heads.get('feature/x')).toBe('bbb2');+ });++ it('yields an empty map for empty output', () => {+ expect(parseRemoteHeads('').size).toBe(0);+ });+ });++ describe('partitionRemoteOrphans', () => {+ it('treats a same-named local branch as a claim even with no upstream', () => {+ // A local `foo` with no tracking still owns `origin/foo` — that is where a+ // plain `git push` sends it. Reaping it would delete a live branch.+ const orphans = partitionRemoteOrphans(+ new Map([['foo', 'aaa']]),+ [{ name: 'foo', tracking: '' }],+ { defaultBranch: 'main' }+ );+ expect(orphans).toEqual([]);+ });++ it('treats a differently-named tracked branch as a claim', () => {+ // The case the name check alone misses, and the reason gatherBranchState+ // carries `tracking` rather than only the hasUpstream boolean.+ const orphans = partitionRemoteOrphans(+ new Map([['remote-name', 'aaa']]),+ [{ name: 'local-name', tracking: 'origin/remote-name' }],+ { defaultBranch: 'main' }+ );+ expect(orphans).toEqual([]);+ });++ it('never reports a protected or default branch as an orphan', () => {+ const orphans = partitionRemoteOrphans(+ new Map([['main', 'aaa'], ['release', 'bbb'], ['gh-pages', 'ccc']]),+ [],+ { defaultBranch: 'main' }+ );+ expect(orphans).toEqual([]);+ });++ it('surfaces a remote branch nothing local points at, name-sorted', () => {+ const orphans = partitionRemoteOrphans(+ new Map([['zeta', 'zzz'], ['alpha', 'aaa'], ['kept', 'kkk']]),+ [{ name: 'kept', tracking: 'origin/kept' }],+ { defaultBranch: 'main' }+ );+ expect(orphans).toEqual([+ { branch: 'alpha', sha: 'aaa' },+ { branch: 'zeta', sha: 'zzz' }+ ]);+ });+ });++ describe('reapOrphanedRemotes', () => {+ it('reports a merged orphan instead of deleting it by default', async () => {+ // The destructive step is opt-in: `git push origin --delete` reaches a+ // shared forge and cannot be undone from here.+ mockRemote(lsRemote([['stale/merged', 'sha-merged']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockResolvedValue(true);++ const res = await reapOrphanedRemotes('/repo', 'main');+ expect(res.reaped).toEqual([]);+ expect(res.reported).toEqual([{ branch: 'stale/merged', reason: 'reap-disabled' }]);+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('deletes a merged orphan on the remote when reaping is enabled', async () => {+ mockRemote(lsRemote([['stale/merged', 'sha-merged']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockResolvedValue(true);+ git.deleteBranch.mockResolvedValue({ branch: 'stale/merged', results: { remote: 'deleted' } });++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.reaped).toEqual(['stale/merged']);+ expect(res.reported).toEqual([]);+ // Remote-only: the local half must not be touched, there is nothing local.+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'stale/merged', { remote: true });+ });++ it('merge-checks the SHA ls-remote reported, not the branch name', async () => {+ // A stale `origin/<branch>` ref can say "merged" about commits origin has+ // since moved past; the live SHA is the only safe thing to judge.+ mockRemote(lsRemote([['stale/merged', 'sha-from-ls-remote']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockResolvedValue(true);++ await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(git.isBranchMergedInto).toHaveBeenCalledWith('/repo', 'sha-from-ls-remote', 'main');+ });++ it('never deletes an unmerged remote-only branch — it may be a peer\'s live work', async () => {+ mockRemote(lsRemote([['peer/in-progress', 'sha-unmerged']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockResolvedValue(false);++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.reaped).toEqual([]);+ expect(res.reported).toEqual([{ branch: 'peer/in-progress', reason: 'unmerged-remote-only' }]);+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('fails closed when the merge check itself errors', async () => {+ // An unfetched SHA cannot be resolved locally — "unknown" must read as+ // "leave it alone", never as "not merged, so safe to assume".+ mockRemote(lsRemote([['never/fetched', 'sha-missing']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockRejectedValue(new Error('bad object'));++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.reaped).toEqual([]);+ expect(res.reported).toEqual([{ branch: 'never/fetched', reason: 'unmerged-remote-only' }]);+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('reports nothing when the remote cannot be read', async () => {+ // An unreadable remote must not read as "origin has no branches" — and an+ // unknowable claim set must not make every remote branch look orphaned.+ mockRemote('', { exitCode: 128 });+ git.getBranches.mockResolvedValue([]);++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res).toEqual({ reaped: [], reported: [], remoteUnavailable: true });+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('reports nothing when the local branch list cannot be read', async () => {+ mockRemote(lsRemote([['anything', 'sha']]));+ git.getBranches.mockRejectedValue(new Error('not a git repo'));++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.remoteUnavailable).toBe(true);+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('surfaces a failed remote delete rather than claiming it was reaped', async () => {+ mockRemote(lsRemote([['stale/merged', 'sha-merged']]));+ git.getBranches.mockResolvedValue([]);+ git.isBranchMergedInto.mockResolvedValue(true);+ git.deleteBranch.mockResolvedValue({ results: { remote: 'failed: protected branch' } });++ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.reaped).toEqual([]);+ expect(res.reported[0].branch).toBe('stale/merged');+ expect(res.reported[0].reason).toContain('remote-delete-failed');+ });+ });++ describe('reconcile wiring', () => {+ it('reports the merged orphan a local cleanup left behind, without deleting it', async () => {+ // The composition this sweep exists for: cleanupMerged deletes the merged+ // LOCAL branch and leaves `origin/<branch>` behind, which the sweep — running+ // after it — then notices.+ git.getBranches.mockResolvedValue([+ { name: 'next/issue-1', isDefault: false, current: false, tracking: 'origin/next/issue-1', merged: true }+ ]);+ wt.listWorktrees.mockResolvedValue([]);+ execGh.mockResolvedValue('[]');+ git.isBranchMergedInto.mockResolvedValue(true);+ mockRemote(lsRemote([['left/behind', 'sha-merged'], ['main', 'sha-main']]));++ const res = await reconcile('/repo');+ expect(res.cleaned).toEqual(['next/issue-1']);+ expect(res.orphanRemotes.reaped).toEqual([]);+ expect(res.orphanRemotes.reported).toEqual([{ branch: 'left/behind', reason: 'reap-disabled' }]);+ // Only the local half of the cleanup ran.+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'next/issue-1', { local: true });+ expect(git.deleteBranch).not.toHaveBeenCalledWith('/repo', 'left/behind', { remote: true });+ });++ // getOriginInfo returns a fully-populated object with `hasOrigin: false` for an+ // origin-less repo — it does NOT return null — so a truthiness gate would run+ // the sweep anyway and log an ls-remote failure on every single cycle.+ it('skips the sweep on a repo whose origin-info says there is no origin', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: false, originUrl: null, host: null, owner: null, repo: null,+ fullName: null, isUpstream: false, isGithub: false, isFork: false+ });+ git.getBranches.mockResolvedValue([]);+ wt.listWorktrees.mockResolvedValue([]);+ mockRemote(lsRemote([['would/be/orphan', 'sha']]));++ const res = await reconcile('/repo');+ expect(res.orphanRemotes).toEqual({ reaped: [], reported: [] });+ expect(execGit).not.toHaveBeenCalledWith(+ expect.arrayContaining(['ls-remote']), expect.anything(), expect.anything()+ );+ });++ it('skips the sweep when origin-info could not be read at all', async () => {+ getOriginInfo.mockRejectedValue(new Error('not a git repo'));+ git.getBranches.mockResolvedValue([]);+ wt.listWorktrees.mockResolvedValue([]);++ const res = await reconcile('/repo');+ expect(res.orphanRemotes).toEqual({ reaped: [], reported: [] });+ });+ });+});