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
fix(cos): finish delivery and preserve evidence during cleanup (#12557)
[._.]/14a29e9c1450
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 79b5f7bad6..89132dbaf0 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -107,10 +107,57 @@ queue. Heads whose checks were still running are watched on the apppending-merge sweep. Detection only: nothing merges, reverts or changes branchprotection.+### Completion recovery and merged cleanup++Successful worktree and claim-swarm runs persist a pending completion audit+before publishing completion. The existing 30-minute merge sweep resumes up to+ten oldest pending audits from live and archived agent records. Every recorded+claim branch has its own recovery backlink; interruption after task creation can+repair the exact existing backlink rather than minting another merge authority.+Missing tasks, unreadable state, active owners and explicit leave-open policy+never grant recovery permission. GitHub auto-merge enabled alone is unfinished.++Routine reconciliation retains superseded but unmerged branches. Their separate+backup-and-retire workflow requires explicit `reapSuperseded: true`; merged cleanup+does not enable it.++The Git page's merged badge is a display hint. Delete merged branches and+completion cleanup use the same retirement path: resolve the current checkout,+re-read ownership and policy, verify the exact commit's merge evidence, archive+and verify ignored content, private Git evidence and reflog-only commit objects.+Before local ref deletion, a separate archive preserves the shared branch+reflog verbatim and bundles every historical commit it names, including for+branches without a checkout. Missing objects or changed archive bytes hold the ref.+Local ref retirement uses Git’s checked-out-branch guard and an exact-head lease+inside the worktree creation queue. Remote deletion binds its fresh proof and+exact-head lease to one captured, matching fetch/push endpoint. Recovery refs retain original commit objects even for a squash+merge without a checkout. Cleanup reports locked, dirty, active, unmanaged,+unverified manual claim, changed-head and archive-failure holds explicitly.+An absent live registry entry alone cannot waive a manual claim hold; a+successful completion receipt bound to the current checkout path, head and+filesystem incarnation is required. Older records cannot release a reused claim. Initialized submodules currently retain+the checkout because their complete content is not supported by the archive.+A held merged receipt names a recovery task when policy and source ownership+permit it; intentional human handoffs stay with their existing owner. The recovery+task prepares preservation prerequisites; the coordinator makes one final retirement+attempt after that task completes. A further refusal remains held with its reason+and recovery task, without creating a loop.+### Pending-merge handoff (#12247)-A participant that has pushed a head and satisfied its configured reviews may-hand the CI wait to the server instead of holding its session open:+Runs default to owning delivery through CI, confirmed merge and safe cleanup.+Early finish is opt-in through the managed-app API setting+`mergeHandoffMinQueuedRuns` (positive integer; absent or null disables it).+Operators choose this threshold from their CI runner capacity; PortOS does not+invent a waiting-time or queue-size default. The server reads GitHub Actions'+current queued workflow-run count and requires that count to meet the configured+threshold, plus queued work on this exact PR head, no failed/unknown checks,+mergeability and satisfied reviews. Unknown backlog, an unavailable/paused+coordinator or failed persistence keeps responsibility with the original run.+This signal measures queued runs, not estimated completion time; repositories+using other CI providers keep in-session ownership until a supported signal exists.++An eligible participant may hand the CI wait to the server:`POST /api/cos/merge-handoff` (host-control gated) takes the registered agentID, the PR URL, the full head SHA and — for a claim run, which cuts its owncheckout — the worktree path. The server binds everything else itself: the@@ -135,15 +182,19 @@ creating nested `[Review Loop]` descendants. A live owner keeps its receiptuntil it releases the branch. Unreadable ownership defers; a changed target,manual hold or exhausted retry budget remains blocked even if CI later turnsgreen. A new verified handoff is needed to replace that binding. An unreadable binding never merges and is-handed to the operator by notification; a PR that never settles times out to a-notification as before.+retained with an explicit blocked reason and an operator notification. A+verified receipt that exceeds its polling budget or cannot read the forge+remains durable and is retried by the scheduled sweep; notification never+discards custody. A closed, unmerged PR is retained for explicit disposition,+even when its old checks failed. Failure recovery waits for an active source+task to finish before transferring ownership to a persisted recovery task.Immediately before merging under admission, the coordinator re-reads its owningtask. A new manual hold or changed completion policy blocks the old receipt;an unreadable owner or queued recovery defers without consuming a worker slot.-The merge-admission prompt section offers this handoff to every participant-before its CI wait. When a local review round returns clean, the run records+The merge-admission prompt section describes this optional handoff before the+normal in-session CI wait. When a local review round returns clean, the run records`REVIEW_HEAD=$(git rev-parse HEAD)` beside `REVIEW_STATUS` (one line, replacingany earlier one); a later commit means that head was not reviewed. On`queued: true` with a receipt for its head, the run stops: it does not wait for@@ -156,7 +207,7 @@ A receipt is a pending end state. `probePrForBranch` reportsthe published local head, so the merge-gate check finalizes without a nudge(`merge-handoff-queued`), worktree cleanup keeps the branch, and the repo-stateaudit treats the queued entry as the branch's owner. The receipt starts one-immediate sweep of the app, which merges a head whose CI already settled+immediate, daemon-gated sweep of the app, which merges a head whose CI settled after acceptancewithout waiting for the 30-minute timer and spends no tick budget. Overlappingsweeps of one app (timer, task generator, receipt) join a single pass; a receiptthat lands during a pass which already read the queue gets one follow-up pass@@ -168,7 +219,7 @@ follow-up poll for the app so a head whose CI turns green a minute later doesnot wait out the rest of the 30-minute timer. It re-runs the receipt sweepevery 60 seconds for the first five polls, then every 120 seconds(`HANDOFF_FOLLOW_UP_*` in `server/services/prWatcher.js`), and stops once-every receipt it tracks has merged, escalated, timed out to a notification or+every receipt it tracks has merged, escalated, reached its polling cap orleft the queue. An app has at most one poller: a receipt that lands while oneis active joins it with its own 45-minute cap, after which the 30-minute timersweep owns the entry exactly as before. Polls spend no tick budget, sodiff --git a/scripts/vitestTempRootSetup.js b/scripts/vitestTempRootSetup.jsindex bf137fd4c7..a1d5260020 100644--- a/scripts/vitestTempRootSetup.js+++ b/scripts/vitestTempRootSetup.js@@ -45,6 +45,25 @@ const TOOLCHAIN_CACHE_PREFIXES = new Set([// minted), plus optional bounded composition snapshots. The decoder reaches// only Node builtins and the existing owner writer, never a service graph.const OWNERS_FILE = '.leak-owners';+const DOTNET_REGISTRATION_CACHE = 'system-commandline-sentinel-files';++function isDotnetRegistrationCache(root, name) {+ // System.CommandLine (also used by Git Credential Manager) writes these+ // registration receipts under TEMP, not under a fixture's own directory:+ // https://github.com/git-ecosystem/git-credential-manager/issues/505+ if (name !== DOTNET_REGISTRATION_CACHE) return false;+ const path = join(root, name);+ try {+ if (!lstatSync(path).isDirectory()) return false;+ const entries = readdirSync(path);+ return entries.every(entry =>+ entry.startsWith('dotnet-suggest-registration-')+ && entry.length > 'dotnet-suggest-registration-'.length+ && lstatSync(join(path, entry)).isFile());+ } catch {+ return false;+ }+}export function groupLeakPrefix(name) {return name.replace(/[0-9a-zA-Z]{6,}$/, '') || name;@@ -94,7 +113,10 @@ export function cleanupRunTempRoot(root = process.env.PORTOS_TEST_TEMP_ROOT) {.filter((name) => name !== OWNER_FILE && name !== OWNERS_FILE).filter((name) => !VITEST_INTERNAL_SCRATCH_DIR.test(name)).filter((name) => !TOOLCHAIN_CACHE_PREFIXES.has(groupLeakPrefix(name)))- .filter((name) => !isEffectivelyEmpty(join(root, name)));+ .filter((name) => !isDotnetRegistrationCache(root, name))+ // A rejected registration cache stays a leak even if the generic empty+ // scan cannot read it; unknown cache contents must fail closed.+ .filter((name) => name === DOTNET_REGISTRATION_CACHE || !isEffectivelyEmpty(join(root, name)));const { owners, observations, state } = readOwnedBrowserObservations(root);const byPrefix = new Map();diff --git a/scripts/vitestTempRootSetup.test.js b/scripts/vitestTempRootSetup.test.jsindex 2c48692973..9b6a8a1c35 100644--- a/scripts/vitestTempRootSetup.test.js+++ b/scripts/vitestTempRootSetup.test.js@@ -94,6 +94,52 @@ describe('vitestTempRootSetup teardown', () => {expect(leaked.exitCode).toBe(1);});+ it('removes documented .NET registration receipts without treating them as fixture leaks', () => {+ const clean = runTeardown(root => {+ const cache = join(root, 'system-commandline-sentinel-files');+ mkdirSync(cache);+ writeFileSync(join(cache, 'dotnet-suggest-registration-git-credential-manager, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null'),+ 'Exception during registration: dotnet-suggest is unavailable');+ });+ expect(clean).toEqual({ warnings: [], exitCode: undefined, removed: true });+ });++ it.each(['unknown-file', 'empty-unknown-file', 'nested-directory', 'empty-nested-directory', 'linked-directory', 'lookalike-name', 'unreadable'])(+ 'still reports unrecognized content beside .NET receipts: %s', kind => {+ const leaked = runTeardown(root => {+ const cacheName = kind === 'lookalike-name'+ ? 'system-commandline-sentinel-files-fixture' : 'system-commandline-sentinel-files';+ const cache = join(root, cacheName);+ mkdirSync(cache);+ writeFileSync(join(cache, 'dotnet-suggest-registration-example'), kind.startsWith('empty-') ? '' : 'registration receipt');+ if (kind === 'unknown-file') writeFileSync(join(cache, 'fixture.json'), '{}');+ if (kind === 'empty-unknown-file') writeFileSync(join(cache, 'fixture.json'), '');+ if (kind === 'nested-directory' || kind === 'empty-nested-directory') {+ const nested = join(cache, 'dotnet-suggest-registration-nested');+ mkdirSync(nested);+ if (kind === 'nested-directory') writeFileSync(join(nested, 'fixture.json'), '{}');+ }+ if (kind === 'linked-directory') {+ const target = join(root, 'linked-target');+ mkdirSync(target);+ symlinkSync(target, join(cache, 'dotnet-suggest-registration-link'), 'junction');+ }+ if (kind === 'unreadable') {+ const original = lstatSync.getMockImplementation();+ lstatSync.mockImplementation(path => {+ if (path === cache) throw Object.assign(new Error('unreadable'), { code: 'EACCES' });+ return original(path);+ });+ }+ });+ expect(leaked.warnings).toEqual([+ `⚠️ test temp leak: system-commandline-sentinel-files${kind === 'lookalike-name' ? '-' : ''} ×1`,+ ]);+ expect(leaked.exitCode).toBe(1);+ expect(leaked.removed).toBe(true);+ },+ );+it('names the test file that minted a leaked root, and never reports the owner sidecar itself', () => {const leaked = runTeardown((root) => {mkdirSync(join(root, 'mv-song-browser-Abc123'));diff --git a/server/lib/README.md b/server/lib/README.mdindex eb7ffa6b46..1d4086e8a4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -25,6 +25,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `branchRetirementArchive.js` | `preserveBranchRetirement` preserves the shared branch reflog verbatim, records its filesystem metadata, and verifies a standalone bundle containing the current tip and every old/new reflog commit before local branch retirement. Its final verifier holds changed refs or reflogs; unsupported storage, missing objects and archive failures retain the branch. || `backupSharedAdmission.js` | Durable cross-process backup cuts and publication leases, with fail-closed owner recovery. || `runtimeFilePublication.js` | Admitted runtime recording updates with rollback of the prior file pair on failure. || `maintenanceAdmission.js` | Durable machine-local workflow drain, cross-process admission permits, continuation ownership and stale-resume fencing. |@@ -740,7 +741,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. || `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. || `mergeGateAudit.js` | Pure verdicts for the post-merge gate audit (#12549): `assessMergeGate({repository, headSha, mergedAt, checks, history, heldLease, receipts})` flags a merged claim PR that held no merge-admission lease at `mergedAt` (`leaseCoversMerge`) or whose head had a check not completed-green before it (`classifyHeadChecks` over `foldHeadChecks`, which dates every run attempt and status post against `mergedAt` so a later rerun or re-posted context cannot rewrite what the merge saw), and exempts a head the pending-merge coordinator marked merged (`receipts`; `awaitsCoordinatorMark` names the unmarked window). `null` checks = forge unreadable, never a verdict. The forge reads and recovery filing live in `../services/mergeGateAudit.js`. |-| `mergeGateContract.js` | `buildManagedGithubMergeScript()` emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |+| `mergeGateContract.js` | `buildManagedGithubMergeScript()` emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` requires delivery ownership until confirmed merge or an exact-head server receipt accepted for measured CI backlog. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. || `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. || `prDisposition.js` | `resolveAppPrCompletion(app, metadata)` supplies the reviewed automatic merge default for new tasks while preserving explicit managed-app choices and legacy review toggles. `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open; `prStaysOpen(task)` is the combined policy-or-human verdict. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `recoveryMergeTarget.js` | `repositoryCleanupMergeTarget(task)` → the `{ url, branch }` parent PR a repository-cleanup recovery was filed to land, or null (#12251). A claimed target only: merge admission also requires the completed parent's server-written backlink to that exact task, branch and PR. |diff --git a/server/lib/branchRetirementArchive.js b/server/lib/branchRetirementArchive.jsnew file mode 100644index 0000000000..1a711964d4--- /dev/null+++ b/server/lib/branchRetirementArchive.js@@ -0,0 +1,94 @@+/** Preserve shared branch reflogs and their objects before branch retirement.+ * Worktree-private archives do not cover logs/refs/heads, which Git removes+ * with the branch. This leaf also covers branches that have no checkout.+ */+import { lstat, readFile, chmod } from 'node:fs/promises';+import { createHash, randomUUID } from 'node:crypto';+import { join } from 'node:path';+import { execGit } from './execGit.js';+import { PATHS } from './paths.js';+import { ensureDir, sha256File, writeFileGuarded } from './fileCore.js';++const MAX_REFLOG_BYTES = 25 * 1024 * 1024;+const MAX_RECOVERY_HEADS = 1024;+const git = (repoPath, args) => execGit(args, repoPath).then(result => result.stdout.trim());+const digest = bytes => createHash('sha256').update(bytes).digest('hex');++async function readReflog(path) {+ const info = await lstat(path).catch(error => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (!info) return { bytes: null, identity: null };+ if (!info.isFile() || info.size > MAX_REFLOG_BYTES) throw new Error('branch reflog cannot be archived');+ const bytes = await readFile(path);+ const identity = {+ dev: info.dev, ino: info.ino, mode: info.mode, size: info.size,+ mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs, sha256: digest(bytes),+ };+ return { bytes, identity };+}++export async function preserveBranchRetirement(repoPath, commonGitDir, branch, expectedHead, { cosDir = PATHS.cos } = {}) {+ const storage = await execGit(['config', '--get', 'extensions.refStorage'], repoPath, { ignoreExitCode: true });+ if ((storage.exitCode !== 0 && storage.exitCode !== 1) || (storage.stdout.trim() && storage.stdout.trim() !== 'files')) {+ throw new Error('branch reflog storage is unsupported');+ }+ const ref = `refs/heads/${branch}`;+ if (await git(repoPath, ['rev-parse', '--verify', ref]) !== expectedHead) throw new Error('branch head changed');+ const source = join(commonGitDir, 'logs', 'refs', 'heads', ...branch.split('/'));+ const before = await readReflog(source);+ const recoveryHeads = new Set([expectedHead]);+ for (const line of (before.bytes?.toString('utf8') || '').split('\n').filter(Boolean)) {+ const match = /^([a-f0-9]{40}(?:[a-f0-9]{24})?) ([a-f0-9]{40}(?:[a-f0-9]{24})?) /.exec(line);+ if (!match) throw new Error('branch reflog entry cannot be preserved');+ for (const head of match.slice(1)) if (!/^0+$/.test(head)) recoveryHeads.add(head);+ }+ if (recoveryHeads.size > MAX_RECOVERY_HEADS) throw new Error('too many branch recovery objects');+ const id = randomUUID();+ const archiveDir = join(cosDir, 'branch-retirement-archives', id);+ await ensureDir(archiveDir);+ await chmod(archiveDir, 0o700);+ if (before.bytes) {+ const copy = join(archiveDir, 'reflog');+ await writeFileGuarded(copy, before.bytes, { flag: 'wx', mode: 0o600 });+ if (digest(await readFile(copy)) !== before.identity.sha256) throw new Error('branch reflog archive mismatch');+ }+ const bundle = join(archiveDir, 'commits.bundle');+ const recoveryRefs = [];+ try {+ for (const head of recoveryHeads) {+ if (await git(repoPath, ['cat-file', '-t', head]) !== 'commit') throw new Error('branch recovery object is not a commit');+ const recoveryRef = `refs/portos/branch-archive/${id}/${head}`;+ await git(repoPath, ['update-ref', recoveryRef, head, '']);+ recoveryRefs.push({ ref: recoveryRef, head });+ }+ await git(repoPath, ['bundle', 'create', bundle, ...recoveryRefs.map(entry => entry.ref)]);+ await git(repoPath, ['bundle', 'verify', bundle]);+ const heads = await git(repoPath, ['bundle', 'list-heads', bundle]);+ const bundled = new Set(heads.split('\n').map(line => line.split(' ')[0]));+ if ([...recoveryHeads].some(head => !bundled.has(head))) throw new Error('branch bundle recovery head mismatch');+ } finally {+ for (const entry of recoveryRefs) await git(repoPath, ['update-ref', '-d', entry.ref, entry.head]);+ }+ await chmod(bundle, 0o600);+ const bundleSha256 = await sha256File(bundle);+ const manifestPath = join(archiveDir, 'manifest.json');+ const manifest = `${JSON.stringify({+ version: 1, repoPath, commonGitDir, branch, expectedHead, archivedAt: new Date().toISOString(),+ reflog: { present: before.bytes !== null, source, identity: before.identity },+ recoveryHeads: [...recoveryHeads], bundleSha256,+ restore: 'git -C <repo> fetch <archive>/commits.bundle refs/portos/branch-archive/<archive-id>/<head>:refs/heads/<restored-branch>',+ }, null, 2)}\n`;+ await writeFileGuarded(manifestPath, manifest, { flag: 'wx', mode: 0o600 });+ const verify = () => Promise.all([+ git(repoPath, ['rev-parse', '--verify', ref]), readReflog(source),+ sha256File(bundle), readFile(manifestPath, 'utf8'),+ before.bytes ? sha256File(join(archiveDir, 'reflog')) : null,+ ]).then(([head, current, bundleHash, currentManifest, reflogHash]) =>+ head === expectedHead && JSON.stringify(current.identity) === JSON.stringify(before.identity)+ && bundleHash === bundleSha256 && currentManifest === manifest+ && (!before.bytes || reflogHash === before.identity.sha256)).catch(() => false);+ if (!await verify()) throw new Error('branch reflog or archive changed during archival');+ return { archiveDir, verify };+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 5a18684eb2..24a7312d9b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -917,3 +917,5 @@ export * from './persistentMindAttachmentOwnership.js';export * from './credentialEnvVars.js';export * from './brainLinkLocalFields.js';++export * from './branchRetirementArchive.js';diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.jsindex f88bd3a185..853185831a 100644--- a/server/lib/mergeGateContract.js+++ b/server/lib/mergeGateContract.js@@ -77,8 +77,6 @@ export function summaryStatesLeaveOpen(summary) {* one that's CLOSED rather than merged). Either way there is nothing here* to act on: finalize normally and let the post-teardown audit* (`agentRepoStateVerification.js`) be the backstop, as today.- * - `auto-merge-enabled` — GitHub confirms a pending handoff; finalize without- * claiming it has merged.* - `merge-handoff-queued` — the server's pending-merge coordinator holds a* verified receipt for the published head (#12247); finalize without claiming* it has merged. The branch is the coordinator's until it merges or recovers.@@ -90,13 +88,12 @@ export function summaryStatesLeaveOpen(summary) {* @param {object} params* @param {{prState: string|null, readable: boolean, autoMergeEnabled?: boolean, mergeHandoffQueued?: boolean}|null} params.prProbe* @param {string|null|undefined} params.summary- * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'auto-merge-enabled'|'merge-handoff-queued'|'needs-reprompt'}+ * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'merge-handoff-queued'|'needs-reprompt'}*/export function resolveMergeGateVerdict({ prProbe, summary }) {if (!prProbe || prProbe.readable === false) return 'no-pr-action';if (prProbe.prState === 'MERGED') return 'merged';if (prProbe.prState !== 'OPEN') return 'no-pr-action';- if (prProbe.autoMergeEnabled === true) return 'auto-merge-enabled';if (prProbe.mergeHandoffQueued === true) return 'merge-handoff-queued';if (summaryStatesLeaveOpen(summary)) return 'leave-open-stated';return 'needs-reprompt';@@ -113,7 +110,7 @@ export function resolveMergeGateVerdict({ prProbe, summary }) {export function buildMergeGateReprompt(prUrl) {return [`Your Merge Gate is not finished: ${prUrl} is still OPEN and your last summary did not say you were leaving it open.`,- 'Work through the Merge Gate steps from your original instructions now: use the verified PortOS pending-merge handoff (or, outside merge admission, the GitHub auto-merge handoff) when eligible, otherwise watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.',+ 'Work through the Merge Gate steps from your original instructions now: use a persisted PortOS pending-merge receipt only when the server accepts measured CI backlog under the configured policy; otherwise watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.','If it truly cannot merge (a required check is red after a genuine fix attempt, or there is a conflict only a human can resolve), say so explicitly and leave it open.',].join('\n');}@@ -136,7 +133,7 @@ export function hasHealthyAutoMergeRequest(pr, now = Date.now()) {/** Shared GitHub handoff contract for inline, review-follow-up and recovery prompts. */export function buildAutoMergeHandoffInstructions(prRef) {- return `**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect \`gh pr view ${prRef} --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision\` and \`gh api repos/{owner}/{repo}\` (the PR's BASE repository). Require \`allow_auto_merge: true\`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read \`gh pr checks ${prRef} --required --json name,state\` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable \`gh pr merge ${prRef} --auto --merge --match-head-commit <published-head>\`. Use \`--squash\` or \`--rebase\` only if merge commits are disallowed. Never use \`--admin\`, change branch protection, or enable repository auto-merge settings. Read back \`gh pr view ${prRef} --json state,headRefOid,autoMergeRequest\`: require the same published head and OPEN with a non-null \`autoMergeRequest.enabledAt\`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.`;+ return `**Own delivery through completion:** By default stay responsible for ${prRef} through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting \`mergeHandoffMinQueuedRuns\` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.`;}/** Shared preservation ordering for every managed checkout delivery prompt. */diff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.jsindex d09a904c6d..dc2ab6164c 100644--- a/server/lib/mergeGateContract.test.js+++ b/server/lib/mergeGateContract.test.js@@ -82,8 +82,8 @@ describe('resolveMergeGateVerdict', () => {})).toBe('leave-open-stated');});- it('accepts live auto-merge evidence even without a handoff summary', () => {- expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true, autoMergeEnabled: true }, summary })).toBe('auto-merge-enabled');+ it('requires continued ownership when only GitHub auto-merge is enabled', () => {+ expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true, autoMergeEnabled: true }, summary })).toBe('needs-reprompt');expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true }, summary: 'Auto-merge enabled.' })).toBe('needs-reprompt');});diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.jsindex 66d72375ac..a181c6d306 100644--- a/server/lib/repoStateExpectations.js+++ b/server/lib/repoStateExpectations.js@@ -150,8 +150,8 @@ export function resolveRepoStateExpectation({export function classifyRepoStateIssues(expectation, observed = {}) {if (!expectation?.verify) return [];const branch = observed.branchName || 'the agent branch';- // GitHub owns a verified pending merge; retaining its branch is intentional.- if (observed.prState === 'OPEN' && observed.autoMergeEnabled === true) return [];+ // Enabling forge auto-merge does not own failure recovery or local cleanup.+ // Explicit server receipts are checked by the caller's pending-owner gate.const branchShouldBeGone = !expectation.staysOpen;const issues = [];diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 0f72a7c34b..fa8b3efb1f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -341,6 +341,7 @@ export const appSchema = z.object({// task when it diverges. See lib/repoStateExpectations.js. Unset = ON: an install// that never hears about a leaked branch just accumulates them.verifyRepoStateOnCompletion: z.boolean().optional(),+ mergeHandoffMinQueuedRuns: z.number().int().min(1).max(10000).nullable().optional(),// Unset/false = off (default); true = land a `.quality.json` quality snapshot through an immediately-merged PR after each audit.publishQualitySnapshot: z.boolean().optional(),featureOverrides: appFeatureOverridesSchema.optional(),diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex b77acb2510..a209025e5b 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1077,9 +1077,9 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/AMBIGUOUS/);expect(prompt).toMatch(/gh workflow list/);expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);- expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);- expect(prompt).toContain('autoMergeRequest.enabledAt');- expect(prompt).toContain('allow_auto_merge: true');+ expect(prompt).not.toMatch(/gh pr merge[^`\n]*--auto --merge/);+ expect(prompt).toContain('mergeHandoffMinQueuedRuns');+ expect(prompt).toContain('explicit persisted PortOS pending-merge receipt');expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);expect(prompt).toContain('If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup');expect(prompt).toContain('Continue to the completion sentinel when this workflow requires one');@@ -1951,9 +1951,9 @@ describe('buildLightContextPrompt', () => {// merge and verify — without these steps the PR sits open after the// agent exits (the original "agent abandoned the PR" bug).expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);- expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);- expect(prompt).toContain('autoMergeRequest.enabledAt');- expect(prompt).toContain('allow_auto_merge: true');+ expect(prompt).not.toMatch(/gh pr merge[^`\n]*--auto --merge/);+ expect(prompt).toContain('mergeHandoffMinQueuedRuns');+ expect(prompt).toContain('explicit persisted PortOS pending-merge receipt');expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);expect(prompt).toMatch(/MERGED/);});@@ -2092,10 +2092,10 @@ describe('buildLightContextPrompt', () => {expect(prompt).toContain('/api/cos/merge-admission');expect(prompt).toMatch(/task-src-1/);expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);- // Pending CI may finish with a GitHub-confirmed auto-merge handoff.- expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);- expect(prompt).toContain('autoMergeRequest.enabledAt');- expect(prompt).toContain('allow_auto_merge: true');+ // Pending CI retains ownership unless a measured durable successor accepts the exact head.+ expect(prompt).not.toMatch(/gh pr merge[^`\n]*--auto --merge/);+ expect(prompt).toContain('mergeHandoffMinQueuedRuns');+ expect(prompt).toContain('explicit persisted PortOS pending-merge receipt');// The immediate-merge fallback still verifies MERGED.expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);expect(prompt).toMatch(/MERGED/);@@ -2133,9 +2133,9 @@ describe('buildLightContextPrompt', () => {// CI is the gate, and the merge command matches the review-loop contract.expect(prompt).toMatch(/gh pr checks "https:\/\/github\.com\/o\/r\/pull\/9" --watch --fail-fast/);expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);- expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);- expect(prompt).toContain('autoMergeRequest.enabledAt');- expect(prompt).toContain('allow_auto_merge: true');+ expect(prompt).not.toMatch(/gh pr merge[^`\n]*--auto --merge/);+ expect(prompt).toContain('mergeHandoffMinQueuedRuns');+ expect(prompt).toContain('explicit persisted PortOS pending-merge receipt');expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);expect(prompt).toMatch(/MERGED/);// No reviewer defaulting may leak back in (normalizeReviewers would say copilot).@@ -2921,7 +2921,7 @@ describe('buildAgentPrompt — provider type routing', () => {});});- it('full-context (api) review-loop follow-up offers verified auto-merge and immediate-merge fallback', async () => {+ it('full-context (api) review-loop follow-up requires ownership through merge or an accepted durable successor', async () => {// Regression for Copilot feedback on PR #260: the merge-without-auto +// MERGED-state verification instructions live in BOTH the light and full// prompt paths, and we lock them in for the full path here so the two@@ -2945,10 +2945,10 @@ describe('buildAgentPrompt — provider type routing', () => {expect(prompt).toMatch(/## Review-Loop Follow-up/);// Merge command must be present, exactly with --merge --match-head-commit <verified-head>.expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);- // Pending CI may finish with a GitHub-confirmed auto-merge handoff.- expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);- expect(prompt).toContain('autoMergeRequest.enabledAt');- expect(prompt).toContain('allow_auto_merge: true');+ // Pending CI retains ownership unless a measured durable successor accepts the exact head.+ expect(prompt).not.toMatch(/gh pr merge[^`\n]*--auto --merge/);+ expect(prompt).toContain('mergeHandoffMinQueuedRuns');+ expect(prompt).toContain('explicit persisted PortOS pending-merge receipt');// The immediate-merge fallback still verifies MERGED.expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state -q \.state/);expect(prompt).toMatch(/MERGED/);diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 3c59c1898d..34148ff8a1 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -1,3 +1,4 @@+import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';import { processAuditFingerprint } from '../lib/persistentMindProcessAudit.js';/*** Agent Repo-State Verification@@ -145,7 +146,7 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc// tree wedges the next `git worktree add` for that path. The cheap disk check// first, so the common leaked-directory case skips the `git worktree list` spawn.const probeWorktree = async () => {- if (existsSync(worktreePath)) return true;+ if (worktreePath && existsSync(worktreePath)) return true;const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);if (!worktrees) return null;return worktrees.some(wt =>@@ -243,7 +244,97 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc* @param {string[]} [params.cleanupWarnings] - warnings cleanup already raised* @returns {Promise<{verified: boolean, skipReason: string|null, issues: Array<{code: string, message: string}>, observed: object|null, recoveryTaskId: string|null}>}*/-export async function verifyAgentRepoState({ agentId, task, agentState, success, prExpected = false, cleanupWarnings = [] }) {+const verificationRuns = new Map();++export async function verifyAgentRepoState(input) {+ if (verificationRuns.has(input.agentId)) return verificationRuns.get(input.agentId);+ const run = verifyRunBranches(input).then(async result => {+ // Completion persists pending before publishing its event. A failed probe,+ // active follow-up or refused task write stays pending for the timer sweep.+ if (input.agentState?.metadata?.repoStateVerification?.status === 'pending') {+ const outcomes = result.branches || [result];+ const terminalSkips = [REPO_STATE_SKIPS.DISABLED, REPO_STATE_SKIPS.NOT_WORKTREE,+ REPO_STATE_SKIPS.PERSISTENT_WORKTREE, REPO_STATE_SKIPS.DISCARDED_WORKTREE, REPO_STATE_SKIPS.FAILED_RUN];+ const settled = outcomes.every(item => item.verified || terminalSkips.includes(item.skipReason))+ || leavesPrForHuman(input.task);+ const { recordRepoStateVerification } = await import('./cosAgentLifecycle.js');+ await recordRepoStateVerification(input.agentId, { status: settled ? 'completed' : 'pending',+ checkedAt: new Date().toISOString(), reasons: [...new Set(outcomes.map(item => item.skipReason).filter(Boolean))] });+ }+ return result;+ }).finally(() => verificationRuns.delete(input.agentId));+ verificationRuns.set(input.agentId, run);+ return run;+}++let completionSweep = null;+/** Resume interrupted completion from existing agent archives, bounded per pass. */+export function sweepRepoStateVerifications() {+ if (completionSweep) return completionSweep;+ completionSweep = resumeCompletionAudits().finally(() => { completionSweep = null; });+ return completionSweep;+}++async function resumeCompletionAudits() {+ const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');+ const { getTaskById } = await import('./cosTaskStore.js');+ const agents = await readBranchCompletionPolicies({ repairIndex: false });+ const pending = agents.filter(agent => agent.status === 'completed' && agent.metadata?.repoStateVerification?.status === 'pending')+ .sort((a, b) => (a.metadata.repoStateVerification.checkedAt || '').localeCompare(b.metadata.repoStateVerification.checkedAt || ''));+ let checked = 0;+ for (const agent of pending.slice(0, 10)) {+ const task = await getTaskById(agent.taskId).catch(() => null);+ // Move missing tasks to the back of the next pass; they cannot grant authority.+ if (!task) {+ const { recordRepoStateVerification } = await import('./cosAgentLifecycle.js');+ await recordRepoStateVerification(agent.id || agent.agentId, { status: 'pending',+ checkedAt: new Date().toISOString(), reasons: ['task-unavailable'] });+ checked++;+ continue;+ }+ await verifyAgentRepoState({ agentId: agent.id || agent.agentId, agentState: agent, task,+ success: agent.result?.success === true, prExpected: isTruthyMeta(task.metadata?.openPR) })+ .catch(error => emitLog('warn', `Completion recovery deferred for ${agent.id}: ${error.message}`, { agentId: agent.id }));+ checked++;+ }+ return { checked, pendingAtStart: pending.length };+}++async function verifyRunBranches(input) {+ const meta = input.agentState?.metadata || {};+ if (meta.isWorktree === true || !isTruthyMeta(meta.claimPicksOwnBranch)) return verifyAgentBranchState(input);+ const bindings = [meta.claimBranches, meta.claimReleasedBranches];+ if (bindings.some(value => value != null && (!Array.isArray(value) || value.some(branch => typeof branch !== 'string' || !branch)))) {+ return { verified: false, skipReason: REPO_STATE_SKIPS.GATE_UNREADABLE, issues: [], observed: null, recoveryTaskId: null };+ }+ const branches = [...new Set(bindings.flatMap(value => value || []))];+ if (!branches.length) return verifyAgentBranchState(input);+ const sourceWorkspace = meta.sourceWorkspace || meta.workspacePath;+ const trees = sourceWorkspace ? await listWorktrees(sourceWorkspace).catch(() => null) : null;+ if (!trees) return { verified: false, skipReason: REPO_STATE_SKIPS.GATE_UNREADABLE, issues: [], observed: null, recoveryTaskId: null };+ const results = [];+ for (const branch of branches) {+ const { readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');+ const { claimCheckoutOwnerReason } = await import('../lib/claimContinuation.js');+ const agents = await readClaimOwnershipAgents().catch(() => null);+ const owner = claimCheckoutOwnerReason({ branchName: branch, sourceWorkspace, agents });+ if (owner) {+ results.push({ branch, verified: false, skipReason: owner, issues: [], recoveryTaskId: null });+ continue;+ }+ // Scope only to server-recorded bindings, never branches parsed from prose.+ // Resolve the holder from Git; the claim agent's workspace is the primary.+ const holder = trees.find(tree => tree.branch === `refs/heads/${branch}`);+ results.push({ branch, ...await verifyAgentBranchState({ ...input, prExpected: true,+ agentState: { ...input.agentState, metadata: { ...meta, isWorktree: true,+ worktreeBranch: branch, sourceWorkspace, workspacePath: holder?.path || null } },+ }) });+ }+ return { verified: results.every(result => result.verified), branches: results,+ issues: results.flatMap(result => result.issues), skipReason: null };+}++async function verifyAgentBranchState({ agentId, task, agentState, success, prExpected = false, cleanupWarnings = [] }) {const metadata = agentState?.metadata || {};const branchName = metadata.worktreeBranch || null;const sourceWorkspace = metadata.sourceWorkspace || null;@@ -287,7 +378,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,const expectation = resolveRepoStateExpectation({ ...structural, enabled, followUpPending: owned });if (!expectation.verify) return skipped(expectation.skipReason);- const worktreePath = metadata.workspacePath || join(PATHS.worktrees, agentId);+ const worktreePath = isTruthyMeta(metadata.claimPicksOwnBranch) ? metadata.workspacePath : metadata.workspacePath || join(PATHS.worktrees, agentId);const observed = await probeRepoState({sourceWorkspace,branchName,@@ -311,7 +402,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,emitLog('info', `🔎 Repo state only partly readable for ${agentId} (${branchName}) — could not check: ${observed.unreadable.join(', ')}`, { agentId, branchName });return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_INCOMPLETE, issues: [], observed, recoveryTaskId: null };}- emitLog('info', `🔎 Agent branch ${branchName} ${observed.autoMergeEnabled ? 'verified pending GitHub auto-merge' : 'verified clean'} for ${agentId}`, { agentId, branchName });+ emitLog('info', `🔎 Agent branch ${branchName} verified clean for ${agentId}`, { agentId, branchName });return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };}@@ -347,7 +438,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });const recoveryTaskId = await fileRepoStateRecoveryTask({- agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId,+ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId, claimRun: isTruthyMeta(metadata.claimPicksOwnBranch),}).catch(err => {emitLog('warn', `Failed to file repo-state recovery task for ${agentId}: ${err.message}`, { agentId, branchName });return null;@@ -375,16 +466,16 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,* `PR_UNMERGED` delegates to branch-reconcile's `driveToMerge`, which carries the* caveats a hand-written line loses: preserve the linked checkout (gh can implicitly delete a* branch checked out elsewhere), retry `--squash`/`--rebase` on "not allowed",- * verify the GitHub auto-merge handoff, or remove the worktree after merging+ * verify the exact-head server handoff, or remove the worktree after merging* before deleting the branch.*/export const REPO_STATE_REMEDIATIONS = Object.freeze({[REPO_STATE_ISSUES.WORKTREE_PRESENT]: ({ worktreePath }) =>- `Remove the leftover worktree: confirm it is clean ("git -C ${worktreePath} status --porcelain"), commit or discard anything found, then "git worktree remove ${worktreePath}" and "git worktree prune".`,+ `Inspect the retained worktree ${worktreePath}. Preserve every unique tracked, untracked and ignored byte, verify its archive, and recheck live ownership before asking the shared retirement path to remove it. Never discard content or bypass a cleanup hold.`,[REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT]: ({ branchName, base }) =>- `Delete the local branch once its work is on ${base}: "git branch -d ${branchName}" (use -D only after confirming the commits landed). Remove its worktree first — the delete fails while a worktree still has it checked out.`,+ `Retire local branch ${branchName} only after fresh merge evidence against ${base}, archive verification and ownership checks. Let shared cleanup compare-and-delete its unchanged tip after the holder is safely retired.`,[REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT]: ({ branchName }) =>- `Delete the remote branch after confirming its work merged: "git push origin --delete ${branchName}".`,+ `Re-read the exact remote ref for ${branchName}, prove that head merged, then delete only with an expected-head lease. Preserve any advanced or unreadable ref.`,[REPO_STATE_ISSUES.BRANCH_UNMERGED]: ({ base }) =>`The branch has commits that are NOT on ${base}. Decide whether they are still wanted: land them (open or merge a PR, or merge locally and resolve conflicts) before deleting anything. Do NOT delete this branch until its work is on ${base}.`,// Forge-aware: `driveToMerge` emits a `gh pr merge` procedure, which a GitLab@@ -404,7 +495,7 @@ export const REPO_STATE_REMEDIATIONS = Object.freeze({** @returns {Promise<string|null>} the task id, or null when it was a duplicate*/-async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId }) {+async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId, claimRun = false }) {const appName = task?.metadata?.appName || appId || 'PortOS';const base = observed.defaultBranch || 'the default branch';const ctx = { branchName, base, prUrl: observed.prUrl, prNumber: observed.prNumber, worktreePath, forgeCli: observed.forgeCli };@@ -423,6 +514,8 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWork'What diverged:',...issues.map((i, n) => `${n + 1}. ${i.message}`),'',+ MANAGED_WORKTREE_CLEANUP_CONTRACT,+ '','Finish the work, in this order:',...issues.map((i, n) => `${n + 1}. ${REPO_STATE_REMEDIATIONS[i.code](ctx)}`),'',@@ -453,13 +546,20 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkif (created?.duplicate) {emitLog('info', `🔎 Repo-state recovery for ${branchName} already queued as ${created.id}`, { agentId, branchName });- return null;+ // Repair an interruption between task creation and backlink persistence,+ // but never bind an unrelated task returned by description deduplication.+ const { getTaskById } = await import('./cosTaskStore.js');+ const duplicate = await getTaskById(created.id).catch(() => null);+ const origin = duplicate?.metadata?.recoveryOrigin;+ const target = duplicate?.metadata?.recoveryMergeTarget;+ if (!mergeTarget || origin?.parentAgentId !== agentId || origin?.parentTaskId !== task?.id+ || origin?.subsystem !== 'repository-cleanup' || target?.url !== mergeTarget.url || target?.branch !== branchName) return null;}if (mergeTarget && created?.id) {// Admission's trust anchor: task metadata is API-writable, so only this// server-written backlink on the parent names which task may land its PR.- const { updateAgent } = await import('./cosAgentLifecycle.js');- const bound = await updateAgent(agentId, { metadata: { repoStateRecovery: { taskId: created.id, ...mergeTarget } } })+ const { recordRepoStateRecovery } = await import('./cosAgentLifecycle.js');+ const bound = await recordRepoStateRecovery(agentId, { taskId: created.id, ...mergeTarget }, { claimRun }).catch(error => { emitLog('warn', `Could not bind repo-state recovery to ${agentId}: ${error.message}`, { agentId, branchName }); return null; });if (!bound) emitLog('warn', `Repo-state recovery ${created.id} cannot merge ${branchName}: parent ${agentId} was not bound`, { agentId, branchName });}diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 011ab05913..b667529524 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -21,7 +21,9 @@ vi.mock('./branchCompletionPolicy.js', async () => ({import { describe, it, expect, beforeEach, vi } from 'vitest';-vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn().mockResolvedValue({}) }));+vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true) }));+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn().mockResolvedValue([]) }));+vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn().mockResolvedValue(null) }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));vi.mock('./cos.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-recovery-1' }),@@ -56,8 +58,10 @@ vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedvi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));-import { updateAgent } from './cosAgentLifecycle.js';-import { verifyAgentRepoState, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';+import { updateAgent, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';+import { verifyAgentRepoState, sweepRepoStateVerifications, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';+import { readBranchCompletionPolicies } from './branchCompletionPolicy.js';+import { getTaskById } from './cosTaskStore.js';import { addTask, getAllTasks } from './cos.js';import { ensureTaskThread } from './brainTaskThreads.js';import { listWorktrees } from './worktreeManager.js';@@ -108,6 +112,8 @@ const run = (overrides = {}) => verifyAgentRepoState({beforeEach(() => {vi.clearAllMocks();+ readBranchCompletionPolicies.mockResolvedValue([]);+ getTaskById.mockResolvedValue(null);listWorktrees.mockResolvedValue([]);listRemoteHeads.mockResolvedValue(new Map());cleanupMerged.mockResolvedValue({ cleaned: [] });@@ -186,8 +192,10 @@ describe('verifyAgentRepoState — divergent runs', () => {expect(payload.useWorktree).toBe(false);// Remediation must be actionable without re-diagnosing, and must forbid// deleting unmerged work or touching a sibling agent's branch.- expect(payload.context).toContain(`git worktree remove ${WORKTREE}`);- expect(payload.context).toContain(`git branch -d ${BRANCH}`);+ expect(payload.context).toContain(`Inspect the retained worktree ${WORKTREE}`);+ expect(payload.context).toContain('Preserve every unique tracked, untracked and ignored byte');+ expect(payload.context).toContain(`Retire local branch ${BRANCH} only after fresh merge evidence`);+ expect(payload.context).not.toContain('git branch -D');expect(payload.context).toContain(`touch ONLY ${BRANCH}`);expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({taskId: 'task-recovery-1', priority: 'high',@@ -200,16 +208,16 @@ describe('verifyAgentRepoState — divergent runs', () => {expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.WORKTREE_PRESENT]);});- it('does not file recovery against GitHub-confirmed auto-merge while its branch survives', async () => {+ it('files recovery when GitHub auto-merge has no durable completion owner', async () => {localBranch(true);hasBranchMergeEvidence.mockResolvedValue(false);listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));execGit.mockImplementation(async (args) => ({ exitCode: 0, stdout: args[0] === 'rev-parse' ? 'abc123\n' : '' }));findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled: true, headRefOid: 'abc123' });const result = await run();- expect(result.issues).toEqual([]);+ expect(result.issues.map(issue => issue.code)).toContain(REPO_STATE_ISSUES.PR_UNMERGED);expect(result.observed).toMatchObject({ prState: 'OPEN', autoMergeEnabled: true });- expect(addTask).not.toHaveBeenCalled();+ expect(addTask).toHaveBeenCalled();});it.each([@@ -470,3 +478,60 @@ it.each(['draft', 'leave-open'])('reports divergence without cleanup or recoveryexpect(addTask).not.toHaveBeenCalled();expect(cleanupMerged).not.toHaveBeenCalled();});++describe('claim-swarm completion', () => {+ it('recovers every recorded branch and preserves its independent merge backlink', async () => {+ const branches = ['claim/issue-11', 'claim/issue-12'];+ findPullRequestForBranch.mockImplementation(async branch => ({ status: 'found', detail: 'OPEN', number: branches.indexOf(branch) + 11,+ url: `https://github.com/example/repo/pull/${branches.indexOf(branch) + 11}` }));+ const state = agentState({ isWorktree: false, worktreeBranch: null, workspacePath: '/repo', claimPicksOwnBranch: true,+ claimBranches: [branches[0]], claimReleasedBranches: branches });+ const result = await run({ agentState: state });+ expect(result.branches.map(item => item.branch)).toEqual(branches);+ expect(addTask).toHaveBeenCalledTimes(2);+ for (const branch of branches) expect(recordRepoStateRecovery).toHaveBeenCalledWith('agent-1',+ expect.objectContaining({ branch, taskId: 'task-recovery-1' }), { claimRun: true });+ expect(cleanupMerged).not.toHaveBeenCalled();+ });+ it('does not infer branches from output or override manual handoffs and failed retries', async () => {+ const state = agentState({ isWorktree: false, worktreeBranch: null, claimPicksOwnBranch: true, claimBranches: ['claim/issue-11'] });+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', url: 'https://github.com/example/repo/pull/11' });+ await run({ agentState: state, task: task({ prCompletion: 'leave-open' }) });+ await run({ agentState: state, success: false });+ await run({ agentState: { ...state, metadata: { ...state.metadata, claimBranches: [] }, output: 'claim/issue-22' } });+ expect(addTask).not.toHaveBeenCalled();+ expect(cleanupMerged).not.toHaveBeenCalled();+ });+});+++describe('durable completion replay', () => {+ const archived = () => ({ ...agentState(), id: 'agent-1', taskId: 'task-1', status: 'completed', result: { success: true },+ metadata: { ...agentState().metadata, repoStateVerification: { status: 'pending' } } });+ it('resumes a persisted pending audit after restart and settles clean completion', async () => {+ readBranchCompletionPolicies.mockResolvedValue([archived()]);+ getTaskById.mockResolvedValue(task());+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'MERGED', url: 'https://github.com/example/repo/pull/7' });+ expect(await sweepRepoStateVerifications()).toMatchObject({ checked: 1 });+ expect(recordRepoStateVerification).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'completed' }));+ expect(addTask).not.toHaveBeenCalled();+ });+ it('keeps missing policy pending with an updated retry time rather than granting authority or starving other audits', async () => {+ readBranchCompletionPolicies.mockResolvedValue([archived()]);+ await sweepRepoStateVerifications();+ expect(recordRepoStateVerification).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'pending', reasons: ['task-unavailable'], checkedAt: expect.any(String) }));+ expect(addTask).not.toHaveBeenCalled();+ });+ it('repairs a lost backlink only for the exact duplicate task and parent', async () => {+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', url: 'https://github.com/example/repo/pull/7' });+ addTask.mockResolvedValue({ id: 'existing', duplicate: true });+ getTaskById.mockResolvedValue({ metadata: { recoveryOrigin: { parentAgentId: 'agent-1', parentTaskId: 'task-1', subsystem: 'repository-cleanup' },+ recoveryMergeTarget: { url: 'https://github.com/example/repo/pull/7', branch: BRANCH } } });+ await run();+ expect(recordRepoStateRecovery).toHaveBeenCalledWith('agent-1', { taskId: 'existing', url: 'https://github.com/example/repo/pull/7', branch: BRANCH }, { claimRun: false });+ recordRepoStateRecovery.mockClear();+ getTaskById.mockResolvedValue({ metadata: { recoveryOrigin: { parentAgentId: 'someone-else' } } });+ await run();+ expect(recordRepoStateRecovery).not.toHaveBeenCalled();+ });+});diff --git a/server/services/apps.js b/server/services/apps.jsindex 0306a4aeb7..bc277229fe 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -321,6 +321,8 @@ async function createAppUnlocked(appData) {// repoStateVerificationEnabled), so writing a default here would freeze the// app against a future change of that default — but an explicit `false` on// create MUST survive, or a new app cannot opt out through POST at all.+ ...(Number.isSafeInteger(appData.mergeHandoffMinQueuedRuns) && appData.mergeHandoffMinQueuedRuns > 0+ ? { mergeHandoffMinQueuedRuns: appData.mergeHandoffMinQueuedRuns } : {}),...(typeof appData.verifyRepoStateOnCompletion === 'boolean'? { verifyRepoStateOnCompletion: appData.verifyRepoStateOnCompletion }: {}),diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.jsindex a3ea8fa8d5..a1566b6531 100644--- a/server/services/branchCompletionPolicy.js+++ b/server/services/branchCompletionPolicy.js@@ -169,7 +169,7 @@ export async function readBranchCompletionHold(input, deps = {}) {// fetched. Only a potential explicit release needs a fresh forge read; offline// cleanup preserves the handoff when that read cannot establish the same head.if (input.retirement === true && decision.obligation?.prUrl- && await verifiedPolicyTip(input.repoPath, input.branch, decision.obligation.prUrl, { requireMerged: true }).catch(() => null) === tip) return null;+ && await verifiedPolicyTip(input.repoPath, input.branch, decision.obligation.prUrl, { requireMerged: true, expectedTip: input.tip }).catch(() => null) === tip) return null;if (decision.release && await verifiedPolicyTip(input.repoPath, input.branch, decision.release.prUrl).catch(() => null) === tip) return null;return decision.reason;}@@ -195,14 +195,14 @@ export async function recordBranchCompletionPolicy({ agentId, task, repoPath, brawait updateAgent(agentId, { metadata: { branchCompletionPolicy: { branch, prUrl, completion, tip } } });}-async function verifiedPolicyTip(repoPath, branch, prUrl, { requireMerged = false } = {}) {+async function verifiedPolicyTip(repoPath, branch, prUrl, { requireMerged = false, expectedTip = null } = {}) {const { getOriginInfo } = await import('../lib/gitRemote.js');const { parsePullRequestUrl } = await import('../lib/gitForge.js');const origin = await getOriginInfo(repoPath);const pr = parsePullRequestUrl(prUrl);if (!pr || pr.host !== origin?.host || `${pr.owner}/${pr.repo}` !== origin.fullName) return null;const { execGit } = await import('../lib/execGit.js');- const tip = (await execGit(['rev-parse', '--verify', `refs/heads/${branch}`], repoPath)).stdout?.trim();+ const tip = expectedTip || (await execGit(['rev-parse', '--verify', `refs/heads/${branch}`], repoPath)).stdout?.trim();if (!/^[a-f0-9]{40,64}$/i.test(tip || '')) return null;const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');const { execGh } = await import('./github.js');diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 79b0e53f35..992292497e 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -16,18 +16,16 @@ import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';* 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.+ * The orphan sweep (`reapOrphanedRemotes`) checks remote branches through the+ * endpoint-bound Git cleanup action. A scan alone cannot authorize deletion:+ * another install may advance a branch after the scan.*/import { buildAutoMergeHandoffInstructions } from '../lib/mergeGateContract.js';import { stat } from 'node:fs/promises';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import { isHostShuttingDown } from '../lib/hostShutdown.js';-import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';+import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteMergedRemoteBranches } from './git.js';import { execGit } from '../lib/execGit.js';import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees, readWorktreeStatus } from './worktreeManager.js';import { isAgentWorktreeId, isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';@@ -376,13 +374,12 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,* and its mtime says when it was created, not whether its owner is finished.* Reconcile once deleted a release worktree a minute after a still-running* release run created it (#10270). So such a tree holds, at any age, with its- * branch; the operator's explicit merged-branch cleanup (`deleteMergedBranches`,- * `includeUnmanagedTrees`) keeps its wider reach, and the superseded reap —- * which carries a recorded verdict and a backup, not just "merged and clean" —- * takes one after SUPERSEDED_UNMANAGED_IDLE_MS.+ * branch. The Git page shares this hold. The explicit superseded reap carries+ * a recorded verdict and backup and can admit one after+ * SUPERSEDED_UNMANAGED_IDLE_MS.** Arbitrary names are accepted INSIDE these roots on purpose: claim trees are- * `claim-*`, not `agent-*`, and still need their stale/shipped retirement.+ * `claim-*`, not `agent-*`, and can retire with exact completion evidence.** @param {string} repoPath* @returns {Array<{path:string, requireAgentId:boolean}>}@@ -795,8 +792,8 @@ export function partitionRemoteOrphans(remoteHeads, localBranches, { defaultBran}/**- * Sweep `origin` for branches nothing local points at, and reap the ones whose- * work is already merged into the default branch.+ * Report or retire `origin` branches nothing local points at. Retirement shares+ * the endpoint-bound Git cleanup action and its fresh ownership gates.** 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 —@@ -812,16 +809,13 @@ export function partitionRemoteOrphans(remoteHeads, localBranches, { defaultBran* 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.+ * `reap` opts in to endpoint-bound retirement of this scan's candidates only.+ * The shared helper refreshes the default and rechecks the remote head, local+ * holders, live owners and completion policy before an exact leased push.** @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`.+ * @param {{ reap?: boolean }} [opts] - deletes verified merged orphans when enabled* @returns {Promise<{reaped:string[], reported:{branch:string,reason:string}[], remoteUnavailable?:boolean}>}*/export async function reapOrphanedRemotes(repoPath, defaultBranch, { reap = false } = {}) {@@ -838,6 +832,7 @@ export async function reapOrphanedRemotes(repoPath, defaultBranch, { reap = falsconst orphans = partitionRemoteOrphans(remoteHeads, localBranches, { defaultBranch });const reaped = [];const reported = [];+ const candidates = [];for (const { branch, sha } of orphans) {const hasMergeEvidence = await hasBranchMergeEvidence(repoPath, sha, defaultBranch).catch(() => false);if (!hasMergeEvidence) {@@ -848,14 +843,12 @@ export async function reapOrphanedRemotes(repoPath, defaultBranch, { reap = falsreported.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}`);+ candidates.push(branch);+ }+ if (candidates.length) {+ const retired = await deleteMergedRemoteBranches(repoPath, candidates, { defaultBranch });+ reaped.push(...retired.deleted);+ reported.push(...retired.skipped);}// 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.@@ -1122,36 +1115,12 @@ async function retainedClaimMarkers(repoPath, branch, { origin } = {}) {* worktree, then delete the local branch. Safety gates (ALL must hold):* 1. `hasBranchMergeEvidence(default)` re-verified true (fail closed).* 2. the branch's worktree (if any) has no real uncommitted changes.- * 3. that worktree (if any) lives in a managed root (`reconcileWorktreeRoots`)- * and no lock, live owner, or claim window holds it.- * A failed gate skips the branch (with a reason) — never a force-delete of- * unmerged or dirty work.- *- * With a fresh owner-registry read under the claim binding lock, an owner-free- * claim can retire immediately. The age windows below are only the fallback- * for callers without that authoritative recheck; neither path bypasses dirty- * work, managed-root, lock, or active-owner guards.- *- * SHIPPED_CLAIM fallback: a `claim-*` worktree holds for STALE_CLAIM_IDLE_MS on the chance- * a claim session is still using it. Waiting out a full week is pointless once- * the claim has demonstrably SHIPPED, and doing it anyway is what left four- * finished claims parked while every run reported "cleaned 0" and parked on- * "merged branches held back" — the exact stall this reconcile exists to clear.- *- * A shipped claim is one where all three hold, established here in order:- * 1. Merge evidence — re-verified against the default branch just above.- * 2. `upstreamGone` — the branch was pushed and its remote ref is no longer on- * origin, i.e. its PR merged with `--delete-branch`.- * 3. clean worktree — the dirty gate below, which this never overrides.- * Together they say the /claim flow finished everything except its own teardown.- * `upstreamGone` is the discriminator the long window was standing in for: a- * claim still being WORKED either has no upstream yet or has one that still- * exists.- *- * What it does NOT prove is that the claim PROCESS has exited — so this- * SHORTENS the idle window to SHIPPED_CLAIM_IDLE_MS rather than removing it,- * for callers without a registry recheck. The fallback remains conservative: an- * unreadable mtime fails safe to protected, and an explicit lock still wins.+ * 3. that worktree (if any) lives in a managed root and is unlocked.+ * 4. fresh ownership and completion policy permit retirement under the claim+ * binding lock; manual claims have an exact successful checkout receipt.+ * 5. recovery archives verify before removal and exact-head ref deletion.+ * A failed gate skips the branch with a reason. Age, an absent upstream, and+ * a cached merged flag never substitute for successful completion evidence.** @param {string} repoPath* @param {string} defaultBranch@@ -1172,16 +1141,11 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgeskipped.push({ branch: b.branch, reason: 'not-merged-on-recheck' });continue;}- // A SHIPPED claim (see SHIPPED_CLAIM above) waits out the short window instead- // of the week-long one — merge evidence was established above, and retireBranch's- // dirty gate is still ahead of the removal.const retired = await retireBranch(repoPath, b, {activeAgentIds,claimOwners,mergedRetirement: true,- staleClaimIdleMs: isMalformedClaimBranch(b.branch)- ? SHIPPED_CLAIM_IDLE_MS- : b.upstreamGone ? SHIPPED_CLAIM_IDLE_MS : STALE_CLAIM_IDLE_MS,+ mergeTarget: defaultBranch,label: `🔀 branch-reconcile: remove worktree for ${b.branch}`,});if (!retired.ok) {@@ -1324,17 +1288,27 @@ export async function reapSupersededBranches(repoPath, defaultBranch, superseded* @returns {Promise<{ ok: true, prepared?: any } | { ok: false, reason: string, retryAt?: string }>}*/async function retireBranch(repoPath, b, opts) {- if (opts.claimOwners === undefined) opts = {- ...opts, claimOwners: { readAgents: readClaimOwnershipAgents },- };+ const supplied = opts.claimOwners;+ if (supplied === null || (supplied !== undefined && (typeof supplied !== 'object'+ || Array.isArray(supplied) || (supplied.readAgents !== undefined && typeof supplied.readAgents !== 'function')))) {+ return { ok: false, reason: 'claim-ownership-unreadable' };+ }+ // A caller's snapshot can add a hold, never grant retirement permission.+ if (supplied && Object.hasOwn(supplied, 'agents')) {+ const snapshotHold = claimCheckoutOwnerReason({+ branchName: b.branch, holderPath: b.worktreePath, sourceWorkspace: repoPath, agents: supplied.agents,+ });+ if (snapshotHold) return { ok: false, reason: snapshotHold };+ }+ const reader = supplied?.readAgents || readClaimOwnershipAgents;+ const readAgents = () => Promise.resolve().then(reader).catch(() => null);+ opts = { ...opts, claimOwners: { ...supplied, readAgents } };// A live claim run may still be finishing this branch (CI wait, merge handoff,// its own cleanup) — never remove its checkout or ref from under it. The scan's// answer is stale by now, so with a registry reader the owners are re-read// under the lock binding takes: a bind lands before this check or after the// removal, never between them.if (b.claimOwnerReason) return { ok: false, reason: b.claimOwnerReason };- const readAgents = opts.claimOwners?.readAgents;- if (!readAgents) return retireBranchNow(repoPath, b, opts);return withClaimOwnershipLock(async () => {const agents = await readAgents().catch(() => null);const reason = claimCheckoutOwnerReason({@@ -1352,17 +1326,34 @@ async function retireBranch(repoPath, b, opts) {});}-async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false }) {+async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false, mergeTarget }) {+ if (PROTECTED_BRANCHES.includes(b.branch)) return { ok: false, reason: 'protected-branch' };+ const defaultBranch = await getDefaultBranch(repoPath, { strict: true }).catch(() => null);+ if (!defaultBranch) return { ok: false, reason: 'default-branch-unavailable' };+ if (b.branch === defaultBranch) return { ok: false, reason: 'protected-branch' };const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');const readPolicyHold = () => readBranchCompletionHold({ repoPath, branch: b.branch, retirement: mergedRetirement });const policyHold = await readPolicyHold();if (policyHold) return { ok: false, reason: policyHold };+ let preservation = null;+ const expectedHead = (await execGit(['rev-parse', '--verify', `refs/heads/${b.branch}`], repoPath).catch(() => null))?.stdout?.trim();+ if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(expectedHead || '')) return { ok: false, reason: mergedRetirement ? 'not-merged-on-recheck' : 'branch-head-unavailable' };+ if (mergedRetirement) {+ // Completion audits may know only the branch. Resolve its actual holder,+ // and pin merge evidence to its current commit rather than the scan's flag.+ const holders = await listWorktrees(repoPath).catch(() => null);+ if (!holders) return { ok: false, reason: 'worktree-ownership-unreadable' };+ const holder = holders.find(wt => wt.branch === `refs/heads/${b.branch}`);+ if (!await hasBranchMergeEvidence(repoPath, expectedHead, mergeTarget).catch(() => false)) return { ok: false, reason: 'not-merged-on-recheck' };+ if (b.worktreePath && b.worktreePath !== holder?.path) return { ok: false, reason: 'worktree-holder-changed' };+ if (holder?.path === repoPath) return { ok: false, reason: 'currently-checked-out' };+ b = { ...b, worktreePath: holder?.path || null, worktreeLocked: holder?.locked || false };+ }if (b.worktreePath) {// Never tear down a worktree outside the managed roots (see// reconcileWorktreeRoots), one that's locked, a RECENT human /claim session,- // or an active CoS agent workspace. An abandoned claim worktree (clean and older- // than the window) falls through and IS retired; that's the "cleaned 0- // forever" leak this exists to close.+ // or an active CoS agent workspace. Passing the age/location gate is only+ // eligibility: manual claims still require exact completion evidence below.const gate = {path: b.worktreePath,locked: b.worktreeLocked,@@ -1385,11 +1376,29 @@ async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleCif (dirty === null) return { ok: false, reason: 'worktree-status-unavailable' };if (requireCleanWorktree && dirty) return { ok: false, reason: 'worktree-dirty' };}+ if (mergedRetirement && b.worktreePath) {+ if (isHumanClaimWorktree(worktreeAgentId(b.worktreePath))) {+ const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');+ const records = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);+ // Registry absence cannot prove a manual CLI or external task finished.+ // Require a recorded completed owner before waiving its claim hold.+ const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');+ const completed = records && await hasCompletedCheckoutEvidence(records, {+ repoPath, branch: b.branch, path: b.worktreePath, head: expectedHead,+ });+ if (!completed) return { ok: false, reason: records ? 'claim-completion-unverified' : 'claim-ownership-unreadable' };+ }+ const tree = (await listWorktrees(repoPath)).find(wt => wt.path === b.worktreePath);+ if (!tree || tree.head !== expectedHead) return { ok: false, reason: 'worktree-holder-changed' };+ const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');+ preservation = await preserveMergedCheckout(repoPath, tree, mergeTarget).catch(error => ({ error }));+ if (preservation.error) return { ok: false, reason: 'archive-failed', detail: preservation.error.message };+ }const prepared = prepare ? await prepare() : null;if (prepared?.error) return { ok: false, reason: prepared.error };if (b.worktreePath) {const verifyRemoval = async (holder) => {- if (!holder || holder.branch !== `refs/heads/${b.branch}`) return 'worktree-holder-changed';+ if (!holder || holder.branch !== `refs/heads/${b.branch}` || holder.head !== expectedHead) return 'worktree-holder-changed';if (claimOwners !== undefined) {const agents = claimOwners?.readAgents ? await claimOwners.readAgents().catch(() => null) : claimOwners?.agents;const reason = claimCheckoutOwnerReason({ branchName: b.branch, holderPath: b.worktreePath, sourceWorkspace: repoPath, agents });@@ -1397,10 +1406,19 @@ async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleC}const policyHold = await readPolicyHold();if (policyHold) return policyHold;+ if (mergedRetirement && isHumanClaimWorktree(worktreeAgentId(b.worktreePath))) {+ const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');+ const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');+ const records = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);+ if (!records || !await hasCompletedCheckoutEvidence(records, {+ repoPath, branch: b.branch, path: b.worktreePath, head: expectedHead,+ })) return 'claim-completion-unverified';+ }const dirty = await isWorktreeDirty(b.worktreePath);if (dirty === null) return 'worktree-status-unavailable';if (requireCleanWorktree && dirty) return 'worktree-dirty';- return null;+ if (mergedRetirement && !await hasBranchMergeEvidence(repoPath, expectedHead, mergeTarget).catch(() => false)) return 'not-merged-on-recheck';+ return preservation ? preservation.verify(holder) : null;};const removal = await forceRemoveWorktreeDir(repoPath, b.worktreePath, { label, log: 'all', verifyRemoval });// The branch is still checked out by a surviving worktree: deleting it would@@ -1409,11 +1427,25 @@ async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleC}const latestPolicyHold = await readPolicyHold();if (latestPolicyHold) return { ok: false, reason: latestPolicyHold };- const result = await deleteBranch(repoPath, b.branch, { local: true }).catch((err) => ({ error: err.message }));- if (result?.error || result?.results?.local?.startsWith?.('failed')) {- return { ok: false, reason: `delete-failed: ${result.error || result.results.local}` };+ if (claimOwners !== undefined) {+ const agents = claimOwners?.readAgents ? await claimOwners.readAgents().catch(() => null) : claimOwners?.agents;+ const reason = claimCheckoutOwnerReason({ branchName: b.branch, holderPath: b.worktreePath, sourceWorkspace: repoPath, agents });+ if (reason) return { ok: false, reason };+ }+ const holders = await listWorktrees(repoPath).catch(() => null);+ if (!holders || holders.some(wt => wt.branch === `refs/heads/${b.branch}`)) return { ok: false, reason: 'branch-has-new-holder' };+ if (mergedRetirement) {+ if (!await hasBranchMergeEvidence(repoPath, expectedHead, mergeTarget).catch(() => false)) return { ok: false, reason: 'not-merged-on-recheck' };+ // A squash/rebase-equivalent branch can contain unique commit objects even+ // without a checkout. Keep an immutable recovery ref before retiring it.+ const backupRef = `refs/portos/completed/${expectedHead}`;+ const backup = await execGit(['update-ref', backupRef, expectedHead], repoPath, { ignoreExitCode: true }).catch(() => null);+ if (backup?.exitCode !== 0) return { ok: false, reason: 'recovery-ref-failed' };}- return { ok: true, prepared };+ const { deleteCompletedLocalBranch } = await import('./worktreeManager.js');+ const deleted = await deleteCompletedLocalBranch(repoPath, b.branch, expectedHead);+ return deleted ? { ok: true, prepared, ...(preservation && { archiveDir: preservation.archiveDir }) }+ : { ok: false, reason: 'branch-ref-changed-or-delete-failed' };}/**@@ -1548,8 +1580,16 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { activeif (dirty) return 'worktree-dirty';return await isStillDetachedOnMerged(repoPath, tree.path, defaultBranch) ? null : 'worktree-head-changed';};+ const current = (await listWorktrees(repoPath).catch(() => null))?.find(holder => holder.path === tree.path);+ if (!current || current.head !== tree.head || current.branch) return { removed: false, reason: 'worktree-holder-changed' };+ const initialHold = await verifyRemoval(current);+ if (initialHold) return { removed: false, reason: initialHold };+ const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');+ const preservation = await preserveMergedCheckout(repoPath, current, defaultBranch).catch(error => ({ error }));+ if (preservation.error) return { removed: false, reason: 'archive-failed' };return forceRemoveWorktreeDir(repoPath, tree.path, {- label: '🔀 branch-reconcile: remove detached worktree', log: 'all', verifyRemoval,+ label: '🔀 branch-reconcile: remove detached worktree', log: 'all',+ verifyRemoval: async holder => await verifyRemoval(holder) || await preservation.verify(holder),});});if (!removal.removed) {@@ -1562,19 +1602,17 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { active}/**- * Full Tier-1 reconcile: gather → classify → clean up merged + verified-superseded.+ * Full Tier-1 reconcile: gather → classify → clean up merged work.+ * Superseded work is retained unless its separate backup-and-retire path is opted into.* Returns the in-flight set (branches needing an agent) for the scheduler to dispatch.** @param {string} [repoPath=PATHS.root]* @param {{ cleanup?: boolean, reapSuperseded?: boolean, reapRemotes?: boolean, activeAgentIds?: Set<string> }} [opts] - when* cleanup is false, merged branches are reported (in `skipped`, reason- * `cleanup-disabled`) but not deleted. `reapSuperseded` (defaults to `cleanup`)- * governs the separate destructive step for verified-superseded branches, whose- * work is NOT on the default branch and survives only as a backup — a caller- * whose "clean up merged branches" toggle never meant that turns it off- * explicitly. `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+ * `cleanup-disabled`) but not deleted. `reapSuperseded` (default false)+ * explicitly opts into the separate destructive step for verified-superseded+ * branches, whose work is NOT on the default branch and survives only as a backup. `reapRemotes` (default false) reports merged remote orphans+ * using endpoint-bound retirement — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS* agent worktrees and any live worktree basename tokens supplied by the caller.* `claimOwners` (`{ agents, readAgents? }`, the agent registry) adds the* registered claim owners — see `resolveClaimOwnerReason`; a dispatching@@ -1597,7 +1635,7 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { active* 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, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), claimOwners = undefined, forgeAccount = null, pendingMergeBranches = undefined } = {}) {+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = false, reapRemotes = false, activeAgentIds = new Set(), claimOwners = undefined, forgeAccount = null, pendingMergeBranches = undefined } = {}) {if (claimOwners === undefined) claimOwners = { agents: await readClaimOwnershipAgents(), readAgents: readClaimOwnershipAgents };// Worktree cleanup is the first reconcile step, before any forge probe. It// only removes a tree after proving both that it is completely clean and@@ -1607,7 +1645,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSupconst worktreeCleanup = cleanup? await reapMergedWorktrees(repoPath, { activeAgentIds, claimOwners, includeClaudeTrees: true }).catch(() => ({ reaped: [] })): { reaped: [] };- const cleanedWorktrees = (worktreeCleanup.reaped || [])+ const cleanedWorktrees = (worktreeCleanup.reaped || []).filter(entry => typeof entry === 'string' || entry?.branchDeleted).map((entry) => typeof entry === 'string' ? entry : entry?.branch).filter(Boolean);@@ -1680,10 +1718,9 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup// 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);- // A verified-superseded branch is TERMINAL, so it is reaped here rather than- // reported: nothing else can ever retire it, and a report that survives every- // pass is how nine of them accumulated in this install. Backed up first, and- // held by the same protection gate as cleanupMerged — see reapSupersededBranches.+ // A cached superseded verdict avoids repeated analysis but does not prove+ // the branch merged. Retain it by default; an explicit caller opt-in uses the+ // backup-first retirement path and the same owner/holder gates as merged work.const supersededReap = reapSuperseded? await reapSupersededBranches(repoPath, defaultBranch, superseded, { activeAgentIds, claimOwners }): { reaped: [], held: superseded, skipped: superseded.map((b) => ({ branch: b.branch, reason: 'reap-superseded-disabled' })) };@@ -1851,7 +1888,7 @@ const supersessionGate = ({ collisionPaths = [], behind } = {}) => {// recovery followed by fresh validation on the resulting head.const verifyGate = 'Fetch the default branch for comparison before opening or updating a PR; inspect semantic overlap and supersession. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk. Base movement alone does not require a rebase or another CI run; this overrides mandatory base-sync instructions in delegated slashdo workflows. Run the test suites for the workspaces the diff touches (`cd server && npm test`, `cd client && npm test`) plus lint, and read the result. After changing the head, rerun affected validation and required reviews/checks. 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.';-// A verified GitHub auto-merge handoff can finish the run before CI drains.+// A measured backlog and durable server receipt can transfer pending CI.// Immediate merges still require the current-head CI and ownership gates.// `pr` is the PR's number when the branch already has one, else the `<num>`// placeholder the agent fills in after opening it.@@ -1862,7 +1899,7 @@ export const driveToMerge = (pr) => [buildAutoMergeHandoffInstructions(pr),'Opening (or approving) the PR is NOT the end state — a green PR left open is still an unfinished branch that this task will simply re-drive on its next run.','A conflict-free branch with passing current-head required checks and satisfied configured reviews may merge behind the default branch. Base movement alone does not require rebasing or restarting CI.',- `Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s so the run stays observable while CI is pending. Budget 15 minutes for the run; past that, leave the PR open and report that CI was still pending.`,+ `Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s so the run stays observable while CI is pending. Retain ownership while CI is pending unless the server accepts an exact-head backlog handoff; elapsed waiting time alone is not completion.`,'If a required check FAILS, fix it on the branch, push, and re-poll (max 3 rounds); if it is still red after that, leave the PR open and report exactly which check failed.','Record the exact local branch head whose checks and configured reviews passed as <verified-head>; immediately before merging, repeat the ownership/policy Recheck and require the forge PR head to equal that same head. If either changed, stop and revalidate. Every merge attempt, including a method retry, must retain --match-head-commit <verified-head>.',`Once every required check is green AND the PR is MERGEABLE, merge without implicit local teardown: \`gh pr merge ${pr} --merge --match-head-commit <verified-head>\`. On a disallowed method retry with \`gh pr merge ${pr} --squash --match-head-commit <verified-head>\`, then \`gh pr merge ${pr} --rebase --match-head-commit <verified-head>\`. Never \`--auto\`: a queued merge outlives this run.`,diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.jsindex 8059b008a1..157a1aa69e 100644--- a/server/services/branchReconcile.ownership.test.js+++ b/server/services/branchReconcile.ownership.test.js@@ -4,17 +4,26 @@* A checkout freshly cut from the default branch is clean and an ancestor of* it, so the merged-branch cleanup used to retire it — and its branch — while* the process that created it was still running. These tests drive `reconcile`- * against a real throwaway repository (no origin, so no forge is consulted) to- * pin that only PortOS-managed roots are retired unattended, while the- * operator's explicit merged-branch cleanup keeps its wider reach.+ * against a real throwaway repository (no forge is consulted) to pin that only+ * PortOS-managed roots are retired unattended. The Git page's merged-branch+ * action shares those ownership gates; external checkouts need scoped release.*/-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';import { mkdtemp, mkdir, rm, utimes, writeFile, appendFile, unlink } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { execGit } from '../lib/execGit.js';import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { captureCompletedCheckouts } from './completedCheckoutEvidence.js';++// Retirement now preserves private Git and ignored evidence. Exercise the+// real archive against a test-owned data root, never the install's data tree.+vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-reconcile-own-archives-'),+}));+afterAll(cleanupTempDataRoots);const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [] }));vi.mock('../lib/execGit.js', async (importOriginal) => {@@ -94,6 +103,16 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re// inventory promises Git's checkout path, not Node's fixture-input spelling.const gitCheckoutPath = async (path) => (await execGit(['rev-parse', '--show-toplevel'], path)).stdout.trim();+ // Operator cleanup independently verifies the remote's advertised default.+ // A bare fixture's default HEAD otherwise points at an unborn master branch.+ async function addOrigin() {+ const remote = join(scratch, 'origin.git');+ await execGit(['init', '--bare', remote], scratch);+ await execGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], remote);+ await execGit(['remote', 'add', 'origin', remote], repo);+ await execGit(['push', 'origin', 'main'], repo);+ }+it('reports an unmerged detached checkout without discarding its tracked, untracked or ignored content', async () => {const path = await addTree(join(external, 'detached-work'), 'temporary-work');await writeFile(join(path, 'tracked.txt'), 'unique committed work\n');@@ -118,7 +137,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect((await execGit(['rev-parse', 'HEAD'], path)).stdout.trim()).toBe(head);});- it('retires inactive managed trees but never a fresh or old unmanaged one', async () => {+ it('preserves unmanaged and unverified manual checkouts regardless of age', async () => {const claudeRoot = join(repo, '.claude', 'worktrees');await mkdir(claudeRoot, { recursive: true });const fresh = await addTree(join(external, 'release-preparation'), 'release-prep/v9.9.9');@@ -141,9 +160,10 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(existsSync(fresh)).toBe(true);expect(existsSync(old)).toBe(true);- // Managed: an abandoned claim is still retired; a lock or real work holds.- expect(result.cleaned, context).toContain('claim/issue-5');- expect(existsSync(staleClaim)).toBe(false);+ // Age and registry absence do not prove a manual claim finished.+ expect(result.cleaned, context).not.toContain('claim/issue-5');+ expect(reasonFor('claim/issue-5'), context).toBe('claim-completion-unverified');+ expect(existsSync(staleClaim)).toBe(true);expect(reasonFor('claim/issue-6'), context).toBe('worktree-locked');expect(existsSync(lockedClaim)).toBe(true);const report = describeIdleReconcilePark(result.skipped, [], {@@ -156,16 +176,18 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(report.remaining).toContainEqual(expect.objectContaining({branch: 'old-workspace', path: await gitCheckoutPath(old), reason: 'worktree-unmanaged-location', managed: false,}));- expect(report.remaining.some(entry => entry.path === staleClaimPath)).toBe(false);+ expect(report.remaining).toContainEqual(expect.objectContaining({+ path: staleClaimPath, branch: 'claim/issue-5', reason: 'claim-completion-unverified',+ }));expect(result.cleaned, context).not.toContain('claim/issue-7');expect(existsSync(dirtyClaim)).toBe(true);const left = await branches();expect(left).toEqual(expect.arrayContaining(['release-prep/v9.9.9', 'old-workspace', 'claim/issue-6', 'claim/issue-7']));- expect(left).not.toContain('claim/issue-5');+ expect(left).toContain('claim/issue-5');});- it('retires fresh owner-free claims while preserving locked and unfinished work', async () => {+ it('retires a fresh claim with exact completion evidence while preserving locked and unfinished work', async () => {const root = join(repo, '.claude', 'worktrees');await mkdir(root, { recursive: true });const clean = await addTree(join(root, 'claim-issue-11'), 'claim/issue-11');@@ -178,6 +200,13 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reawait execGit(['add', 'committed.txt'], unmerged);await execGit(['commit', '-m', 'feat: unfinished work'], unmerged);+ const owner = { id: 'completed-claim', status: 'running', startedAt: new Date(Date.now() - 1000).toISOString(),+ metadata: { sourceWorkspace: repo, claimPicksOwnBranch: true, claimBranches: ['claim/issue-11'] } };+ const completedCheckouts = await captureCompletedCheckouts(owner, { success: true });+ expect(completedCheckouts).toHaveLength(1);+ injected.policies = [{ ...owner, status: 'completed', result: { success: true }, completedAt: new Date().toISOString(),+ metadata: { ...owner.metadata, completedCheckouts } }];+const result = await reconcile(repo, {activeAgentIds: new Set(), claimOwners: { agents: [], readAgents: async () => [] },});@@ -213,16 +242,18 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(existsSync(tree)).toBe(false);});- it('leaves the operator-initiated merged-branch cleanup able to remove an unmanaged tree', async () => {+ it('keeps an unmanaged checkout held at the operator merged-branch cleanup boundary', async () => {const loose = await addTree(join(external, 'loose'), 'loose-br', { ageMs: 30 * DAY });const held = await reconcile(repo, { activeAgentIds: new Set() });expect(held.skipped.find((s) => s.branch === 'loose-br')?.reason).toBe('worktree-unmanaged-location');+ await addOrigin();const operator = await deleteMergedBranches(repo, { activeAgentIds: new Set() });- expect(operator.deleted.map((d) => d.name), JSON.stringify(operator)).toContain('loose-br');- expect(existsSync(loose)).toBe(false);- expect(await branches()).not.toContain('loose-br');+ expect(operator.deleted).toEqual([]);+ expect(operator.skipped).toContain('loose-br (local: worktree-unmanaged-location)');+ expect(existsSync(loose)).toBe(true);+ expect(await branches()).toContain('loose-br');});it.each([false, true])('preserves authored files when status is unreadable (throws=%s)', async (throws) => {@@ -268,6 +299,36 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(await branches()).toContain(branch);});+ it('refreshes a stale empty ownership snapshot before retiring a newly claimed branch', async () => {+ const branch = 'fix/stale-owner-snapshot';+ const path = await addTree(join(repo, '.claude', 'worktrees', 'snapshot'), branch);+ injected.owners = [{ id: 'new-owner', status: 'running', metadata: {+ sourceWorkspace: repo, claimBranches: [branch],+ } }];+ const result = await cleanupMerged(repo, 'main', [{ branch, upstreamGone: true }], { claimOwners: { agents: [] } });+ expect(result.cleaned).toEqual([]);+ expect(result.skipped).toEqual([{ branch, reason: 'claim-owner-active' }]);+ expect(existsSync(path)).toBe(true);+ expect(await branches()).toContain(branch);+ });++ it('never uses an old manual claim age or empty snapshot as completion proof', async () => {+ const branch = 'claim/issue-55';+ const path = await addTree(join(repo, '.claude', 'worktrees', 'claim-issue-55'), branch, { ageMs: 30 * DAY });+ // Match gatherBranchState's Git-reported spelling, including Windows+ // separators and expanded short paths, so this reaches the policy gate.+ const worktreePath = (await execGit(['rev-parse', '--show-toplevel'], path)).stdout.trim();+ const entry = { branch, worktreePath, worktreeAgeMs: 30 * DAY, upstreamGone: true };+ for (const claimOwners of [{ agents: [] }, { agents: null }, null]) {+ const result = await cleanupMerged(repo, 'main', [entry], { claimOwners });+ expect(result.cleaned).toEqual([]);+ expect(result.skipped).toContainEqual(expect.objectContaining({ branch,+ reason: claimOwners?.agents ? 'claim-completion-unverified' : 'claim-ownership-unreadable' }));+ expect(existsSync(path)).toBe(true);+ expect(await branches()).toContain(branch);+ }+ });+it('holds a branch queued for the pending-merge coordinator instead of dispatching its open PR, and fails closed when the queue is unreadable', async () => {const branch = 'claim/issue-1';await execGit(['checkout', '-q', '-b', branch], repo);@@ -344,10 +405,12 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reit('fails closed on an unreadable registry or unknown owner status at the operator cleanup boundary', async () => {const path = await addTree(join(external, 'unknown-owner'), 'fix/unknown-owner');+ await addOrigin();for (const owners of [null, [{ id: 'agent-unknown', status: 'unknown', workspacePath: path }]]) {injected.owners = owners;const result = await deleteMergedBranches(repo, { activeAgentIds: new Set() });expect(result.deleted).toEqual([]);+ expect(result.skipped.some(reason => reason.includes('claim-ownership-unreadable'))).toBe(true);expect(existsSync(path)).toBe(true);expect(await branches()).toContain('fix/unknown-owner');}diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 97e48c9232..71528dadfc 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -1,6 +1,7 @@+vi.mock('./completedCheckoutEvidence.js', () => ({ hasCompletedCheckoutEvidence: vi.fn(async records => records.some(agent => agent.result?.success === true)) }));vi.mock('./branchCompletionPolicy.js', async () => ({...await vi.importActual('./branchCompletionPolicy.js'),- readBranchCompletionPolicies: vi.fn(async () => []),+ readBranchCompletionPolicies: vi.fn(async () => (await wt.listWorktrees()).map(tree => ({ id: 'completed-owner', status: 'completed', result: { success: true }, metadata: { sourceWorkspace: '/repo', worktreeBranch: tree.branch?.replace('refs/heads/', '') } }))),readBranchCompletionHold: vi.fn(async () => null),}));/**@@ -13,11 +14,13 @@ vi.mock('./branchCompletionPolicy.js', async () => ({* inFlight / wip correctly).*/+vi.mock('./heldCheckoutRecovery.js', () => ({ preserveMergedCheckout: vi.fn(async () => ({ archiveDir: '/archive', verify: async () => null })) }));import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { join } from 'node:path';vi.mock('./git.js', () => ({getBranches: vi.fn(),+ deleteMergedRemoteBranches: vi.fn(async (_repo, names) => ({ deleted: names, skipped: [] })),getDefaultBranch: vi.fn(async () => 'main'),hasBranchMergeEvidence: vi.fn(),deleteBranch: vi.fn(async () => ({ branch: 'x', results: { local: 'deleted' } }))@@ -32,6 +35,7 @@ vi.mock('./worktreeManager.js', async () => {const { AGENT_SCRATCH_PATHS, matchesScratchRoot } = await import('../lib/agentScratchPaths.js');return {listWorktrees: vi.fn(async () => []),+ deleteCompletedLocalBranch: vi.fn(async () => true),forceRemoveWorktreeDir: vi.fn(async () => ({ removed: true, warning: null })),reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),readWorktreeStatus: async (path) => {@@ -117,7 +121,7 @@ vi.mock('./supersededBackup.js', () => ({}));import {- classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,+ classifyBranch, classifyBranches, cleanupMerged as retireMerged, reconcile, gatherBranchState, worktreeProtectionReason,isAbandonedAgentWorktree, isAbandonedClaimWorktree, resolveLiveOwnerReason, gatherDivergence,actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,limitBranchesForAgent,@@ -129,14 +133,30 @@ import {} from './branchReconcile.js';import * as git from './git.js';import * as wt from './worktreeManager.js';+import { preserveMergedCheckout } from './heldCheckoutRecovery.js';+import { hasCompletedCheckoutEvidence } from './completedCheckoutEvidence.js';import { execGit } from '../lib/execGit.js';import { execGh } from './github.js';import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';import { getOriginInfo } from '../lib/gitRemote.js';import { __resetForgeNoAccessLog } from '../lib/forgeAccessErrors.js';+const RETIRE_HEAD = 'a'.repeat(40);+const pinnedRef = args => args[0] === 'rev-parse' && args[1] === '--verify' && /^refs\/heads\/[^{}]+$/.test(args[2]);+const gitFixtureResult = (stdout = '', exitCode = 0) => async args => ({ stdout: pinnedRef(args) ? RETIRE_HEAD : stdout, exitCode });+let retirementTrees = [];+async function cleanupMerged(repo, target, branches, options) {+ retirementTrees = branches.filter(branch => branch.worktreePath).map(branch => ({+ path: branch.worktreePath, branch: `refs/heads/${branch.branch}`, head: RETIRE_HEAD, locked: branch.worktreeLocked,+ }));+ wt.listWorktrees.mockImplementation(async () => retirementTrees);+ return retireMerged(repo, target, branches, options);+}+beforeEach(() => {vi.clearAllMocks();+ hasCompletedCheckoutEvidence.mockReset().mockImplementation(async records => records.some(agent => agent.result?.success === true));+ preserveMergedCheckout.mockImplementation(async () => ({ archiveDir: '/archive', verify: async () => null }));// Ancient by default, so age-indifferent tests keep their pre-window behavior;// a test that pins a specific age must not leak it into the next one.worktreeMtimeMs = 0;@@ -151,10 +171,12 @@ beforeEach(() => {hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'});git.getDefaultBranch.mockResolvedValue('main');+ git.deleteMergedRemoteBranches.mockImplementation(async (_repo, names) => ({ deleted: names, skipped: [] }));git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });- wt.forceRemoveWorktreeDir.mockResolvedValue({ removed: true, warning: null });+ wt.forceRemoveWorktreeDir.mockImplementation(async (_repo, path) => { retirementTrees = (await wt.listWorktrees()).filter(tree => tree.path !== path); wt.listWorktrees.mockResolvedValue(retirementTrees); return { removed: true, warning: null }; });wt.reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [] });- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ wt.deleteCompletedLocalBranch.mockResolvedValue(true);+ execGit.mockImplementation(gitFixtureResult('', 0));tryReadFileMock.mockResolvedValue(null);backupSupersededBranchMock.mockImplementation(async (_repoPath, branch) => ({dir: `/repo/data/cos/abandoned-worktree-backups/${branch.branch.replace(/\//g, '-')}`,@@ -350,17 +372,30 @@ describe('unverified issue reservations in reconcile', () => {});describe('cleanupMerged', () => {+ it('retains human claims without successful exact checkout completion evidence', async () => {+ const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');+ hasCompletedCheckoutEvidence.mockResolvedValueOnce(false);+ git.hasBranchMergeEvidence.mockResolvedValue(true);+ const branch = 'claim/issue-42';+ const worktreePath = '/repo/.claude/worktrees/claim-issue-42';+ retirementTrees = [{ path: worktreePath, branch: `refs/heads/${branch}`, head: RETIRE_HEAD }];+ const result = await cleanupMerged('/repo', 'main', [{ branch, worktreePath }]);+ expect(result.skipped).toEqual([expect.objectContaining({ branch, reason: 'claim-completion-unverified' })]);+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();+ expect(wt.deleteCompletedLocalBranch).not.toHaveBeenCalled();+ });+it.each([['forward-slash fixture', '/repo/.claude/worktrees/next-2190'],['native-joined fixture', join('/repo', '.claude', 'worktrees', 'next-2190')]])('removes worktree + deletes branch when merged and clean (%s)', async (_label, worktreePath) => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktree+ execGit.mockImplementation(gitFixtureResult('', 0)); // clean worktreeconst res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath }]);expect(res.cleaned).toEqual(['next/issue-2190']);expect(res.skipped).toEqual([]);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', worktreePath, expect.any(Object));- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'next/issue-2190', { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', 'next/issue-2190', RETIRE_HEAD);});it.each([@@ -368,7 +403,7 @@ describe('cleanupMerged', () => {'/repo/.claude/worktrees/../outside/next-2190'])('holds a merged clean worktree outside the managed root (%s)', async (worktreePath) => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath }]);expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'next/issue-2190', path: worktreePath, reason: 'worktree-unmanaged-location' }]);@@ -378,7 +413,7 @@ describe('cleanupMerged', () => {it('does not delete the branch or report it cleaned when the worktree survives removal', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktree+ execGit.mockImplementation(gitFixtureResult('', 0)); // clean worktreewt.forceRemoveWorktreeDir.mockResolvedValue({ removed: false, warning: 'Worktree cleanup incomplete — retryable' });const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/repo/.claude/worktrees/next-2190' }]);expect(res.cleaned).toEqual([]);@@ -395,7 +430,7 @@ describe('cleanupMerged', () => {it('skips when the worktree has real uncommitted changes', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: ' M server/index.js', exitCode: 0 }); // dirty+ execGit.mockImplementation(gitFixtureResult(' M server/index.js', 0)); // dirtyconst res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2196', worktreePath: '/repo/.claude/worktrees/next-2196' }]);expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'next/issue-2196', path: '/repo/.claude/worktrees/next-2196', reason: 'worktree-dirty' }]);@@ -410,7 +445,8 @@ describe('cleanupMerged', () => {expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();});- it('keeps legacy snapshot-only callers behind locked / human-claim / active-agent gates', async () => {+ it('keeps snapshot-only callers behind locked / completion-proof / active-agent gates', async () => {+ hasCompletedCheckoutEvidence.mockResolvedValue(false);git.hasBranchMergeEvidence.mockResolvedValue(true);const activeAgentIds = new Set(['agent-abc12345']);const res = await cleanupMerged('/repo', 'main', [@@ -421,23 +457,23 @@ describe('cleanupMerged', () => {expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'locked-b', path: '/repo/data/cos/worktrees/locked', reason: 'worktree-locked' },- { branch: 'claim-b', path: '/repo/data/cos/worktrees/claim-foo', reason: 'worktree-human-claim' },+ { branch: 'claim-b', path: '/repo/data/cos/worktrees/claim-foo', reason: 'claim-completion-unverified' },{ branch: 'active-b', path: '/repo/data/cos/worktrees/agent-abc12345', reason: 'worktree-active-agent' }]);expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();expect(git.deleteBranch).not.toHaveBeenCalled();});- it('reaps an ABANDONED claim worktree (merged + clean + stale age)', async () => {+ it('reaps an old claim worktree with verified completion evidence', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean+ execGit.mockImplementation(gitFixtureResult('', 0)); // cleanconst res = await cleanupMerged('/repo', 'main', [// 10 days old — comfortably past the 7-day STALE_CLAIM_IDLE_MS default{ branch: 'claim/issue-1933', worktreePath: '/repo/data/cos/worktrees/claim-issue-1933', worktreeAgeMs: 10 * 24 * 60 * 60 * 1000 }]);expect(res.cleaned).toEqual(['claim/issue-1933']);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-1933', expect.any(Object));- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'claim/issue-1933', { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', 'claim/issue-1933', RETIRE_HEAD);});it('leaves global issue markers untouched after successful local deletion without asserting they exist', async () => {@@ -446,7 +482,7 @@ describe('cleanupMerged', () => {const result = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-42', worktreePath: '/repo/.claude/worktrees/retired' }]);expect(result.cleaned).toEqual(['claim/issue-42']);expect(result.claimMarkersHeld).toEqual([{ branch: 'claim/issue-42', issue: 42, reason: 'claim-reservation-owner-unverified', markerState: 'unknown', ownerState: 'unknown' }]);- expect(git.deleteBranch).toHaveBeenCalled();+ expect(execGit.mock.calls.some(([args]) => args[0] === 'update-ref')).toBe(true);expect(execGh).not.toHaveBeenCalled();});@@ -470,17 +506,17 @@ describe('cleanupMerged', () => {const held = await cleanupMerged('/repo', 'main', [branch], { activeAgentIds: new Set(['claim-issue-42']) });expect(held.skipped[0].reason).toBe('worktree-active-agent');expect(execGh).not.toHaveBeenCalled();- git.deleteBranch.mockResolvedValue({ error: 'delete refused' });+ execGit.mockImplementation(async args => args[0] === 'update-ref' ? { exitCode: 1, stdout: '' } : gitFixtureResult()(args));const failed = await cleanupMerged('/repo', 'main', [branch]);expect(failed.cleaned).toEqual([]);expect(execGh).not.toHaveBeenCalled();});- it('reaps the invalid empty-issue claim immediately when merged and clean', async () => {+ it('reaps the invalid empty-issue claim when merged, clean, and completion is verified', async () => {expect(isMalformedClaimBranch('claim/issue-')).toBe(true);expect(isMalformedClaimBranch('claim/issue-42')).toBe(false);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-', worktreePath: '/repo/data/cos/worktrees/claim-issue-', worktreeAgeMs: 2 * 60 * 60 * 1000 }@@ -488,63 +524,66 @@ describe('cleanupMerged', () => {expect(res.cleaned).toEqual(['claim/issue-']);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-', expect.any(Object));- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'claim/issue-', { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', 'claim/issue-', RETIRE_HEAD);});- it('still protects a RECENT claim worktree for snapshot-only callers even when merged + clean, and says when the hold lifts', async () => {+ it('retains a recent unverified claim for snapshot-only callers without a time-based expiry', async () => {+ hasCompletedCheckoutEvidence.mockResolvedValue(false);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean- const before = Date.now();+ execGit.mockImplementation(gitFixtureResult('', 0)); // cleanconst res = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-9999', worktreePath: '/repo/data/cos/worktrees/claim-issue-9999', worktreeAgeMs: 60 * 1000 } // 1 min old], { claimOwners: { agents: [] } });expect(res.cleaned).toEqual([]);expect(res.skipped).toHaveLength(1);- expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-9999', reason: 'worktree-human-claim' });- // The whole point of retryAt: the caller can park until the grace window- // lapses instead of sleeping to the next recheck. ~7 days minus 1 minute out.- const retryMs = Date.parse(res.skipped[0].retryAt);- expect(retryMs).toBeGreaterThan(before + 6.9 * 24 * 60 * 60 * 1000);- expect(retryMs).toBeLessThanOrEqual(Date.now() + 7 * 24 * 60 * 60 * 1000);+ expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-9999', reason: 'claim-completion-unverified' });+ expect(res.skipped[0]).not.toHaveProperty('retryAt');expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();expect(git.deleteBranch).not.toHaveBeenCalled();});- it('reaps a SHIPPED claim once idle, but not while dirty, un-shipped, or still busy', async () => {+ it('requires completion proof for shipped claims and preserves dirty or actively owned checkouts', async () => {const HOUR = 60 * 60 * 1000;const shipped = (over) => ({worktreePath: '/repo/data/cos/worktrees/claim-x', worktreeAgeMs: 2 * HOUR, upstreamGone: true, ...over});git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean+ execGit.mockImplementation(gitFixtureResult('', 0)); // cleanconst reaped = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-0', ...shipped() }], { claimOwners: { agents: [] } });expect(reaped.cleaned).toEqual(['claim/issue-0']);// The dirty gate is independent — a shorter window never overrides it.- execGit.mockResolvedValue({ stdout: ' M server/index.js', exitCode: 0 }); // dirty+ execGit.mockImplementation(gitFixtureResult(' M server/index.js', 0)); // dirtyconst dirty = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-1', ...shipped() }], { claimOwners: { agents: [] } });expect(dirty.cleaned).toEqual([]);expect(dirty.skipped).toEqual([{ branch: 'claim/issue-1', path: '/repo/data/cos/worktrees/claim-x', reason: 'worktree-dirty' }]);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean- // No completion proof — never pushed, remote ref still on origin, or the- // remote could not be read. The week-long window still applies.+ execGit.mockImplementation(gitFixtureResult('', 0)); // clean+ // Neither age nor upstream disappearance substitutes for a receipt bound+ // to this checkout's exact head and incarnation.+ hasCompletedCheckoutEvidence.mockResolvedValue(false);const unshipped = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-2', ...shipped({ upstreamGone: false }) }], { claimOwners: { agents: [] } });expect(unshipped.cleaned).toEqual([]);- expect(unshipped.skipped[0]).toMatchObject({ branch: 'claim/issue-2', reason: 'worktree-human-claim' });+ expect(unshipped.skipped[0]).toMatchObject({ branch: 'claim/issue-2', reason: 'claim-completion-unverified' });- // Shipped but touched a minute ago — a claim process mid-teardown, or a peer- // machine merged the PR while this session is still running. Held, and the- // caller is told when the short window lapses.+ // A remote branch deleted by a peer still leaves this local unverified+ // checkout held, even if it is clean and recently touched.const busy = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-3', ...shipped({ worktreeAgeMs: 60 * 1000 }) }], { claimOwners: { agents: [] } });expect(busy.cleaned).toEqual([]);- expect(busy.skipped[0]).toMatchObject({ branch: 'claim/issue-3', reason: 'worktree-human-claim' });- expect(Date.parse(busy.skipped[0].retryAt)).toBeLessThanOrEqual(Date.now() + SHIPPED_CLAIM_IDLE_MS);+ expect(busy.skipped[0]).toMatchObject({ branch: 'claim/issue-3', reason: 'claim-completion-unverified' });+ expect(busy.skipped[0]).not.toHaveProperty('retryAt');++ hasCompletedCheckoutEvidence.mockResolvedValue(true);+ const active = await cleanupMerged('/repo', 'main', [+ { branch: 'claim/issue-4', ...shipped() }+ ], { claimOwners: { agents: [] }, activeAgentIds: new Set(['claim-x']) });+ expect(active.cleaned).toEqual([]);+ expect(active.skipped[0]).toMatchObject({ branch: 'claim/issue-4', reason: 'worktree-active-agent' });});it('omits retryAt for holds that do NOT lift on a clock', async () => {@@ -564,22 +603,22 @@ describe('cleanupMerged', () => {describe('worktreeProtectionReason', () => {it('flags locked, human-claim, and active-agent worktrees; passes ordinary ones', () => {- expect(worktreeProtectionReason({ path: '/wt/x', locked: true })).toBe('worktree-locked');- expect(worktreeProtectionReason({ path: '/x/claim-foo' })).toBe('worktree-human-claim');- expect(worktreeProtectionReason({ path: '/x/agent-1', activeAgentIds: new Set(['agent-1']) })).toBe('worktree-active-agent');- expect(worktreeProtectionReason({ path: '/repo/next-issue-2199', activeAgentIds: new Set(['agent-1']) })).toBeNull();+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/wt/x', locked: true })).toBe('worktree-locked');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo' })).toBe('worktree-human-claim');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/agent-1', activeAgentIds: new Set(['agent-1']) })).toBe('worktree-active-agent');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/repo/next-issue-2199', activeAgentIds: new Set(['agent-1']) })).toBeNull();});it('reaps an abandoned claim (stale age) but protects a recent one and unknown age', () => {const staleClaimIdleMs = 24 * 60 * 60 * 1000;// recent human /claim session (2h old) — still protected- expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: 2 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-human-claim');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', ageMs: 2 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-human-claim');// abandoned claim (3d old, merged+clean) — reaped- expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBeNull();+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBeNull();// unknown age → fail safe toward protecting- expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: null, staleClaimIdleMs })).toBe('worktree-human-claim');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', ageMs: null, staleClaimIdleMs })).toBe('worktree-human-claim');// locked always wins even when stale- expect(worktreeProtectionReason({ path: '/x/claim-foo', locked: true, ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-locked');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', locked: true, ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-locked');});// A shipped claim gets a SHORTER window, not a bypass — so a worktree a live@@ -588,7 +627,7 @@ describe('worktreeProtectionReason', () => {// fails safe. Both properties come free from reusing the window; a bypass had// neither.it('honors the short shipped-claim window without abandoning the window itself', () => {- const at = (ageMs, staleClaimIdleMs) => worktreeProtectionReason({ path: '/x/claim-foo', ageMs, staleClaimIdleMs });+ const at = (ageMs, staleClaimIdleMs) => worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', ageMs, staleClaimIdleMs });// Just-merged and still busy: inside the short window, still protected.expect(at(60 * 1000, SHIPPED_CLAIM_IDLE_MS)).toBe('worktree-human-claim');// Idle past it: reaped, without waiting out the week-long window.@@ -600,9 +639,9 @@ describe('worktreeProtectionReason', () => {});it('allows live claims through when allowLiveClaim is true, but locked and active-agent still hold', () => {- expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true })).toBeNull();- expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true, locked: true })).toBe('worktree-locked');- expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true, activeAgentIds: new Set(['claim-foo']) })).toBe('worktree-active-agent');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', allowLiveClaim: true })).toBeNull();+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', allowLiveClaim: true, locked: true })).toBe('worktree-locked');+ expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', allowLiveClaim: true, activeAgentIds: new Set(['claim-foo']) })).toBe('worktree-active-agent');});});@@ -618,7 +657,7 @@ describe('gatherBranchState', () => {{ name: 'next/issue-2190', isDefault: false, current: false, tracking: 'origin/next/issue-2190', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/wt/2199', branch: 'refs/heads/next/issue-2199' }+ { head: RETIRE_HEAD, path: '/wt/2199', branch: 'refs/heads/next/issue-2199' }]);execGh.mockResolvedValue(JSON.stringify([{ number: 2206, headRefName: 'next/issue-2199', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }@@ -708,30 +747,30 @@ describe('isAbandonedAgentWorktree', () => {const live = new Set(['agent-aaaaaaaa']);it('is true only for an unlocked agent worktree whose agent is not running', () => {- expect(isAbandonedAgentWorktree({ path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBe(true);- expect(isAbandonedAgentWorktree({ path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe(false);- expect(isAbandonedAgentWorktree({ path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBe(true);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe(false);});it('never claims a human /claim worktree, a non-agent sibling, or a missing path', () => {- expect(isAbandonedAgentWorktree({ path: '/wt/claim-fix-thing', activeAgentIds: live })).toBe(false);- expect(isAbandonedAgentWorktree({ path: '/wt/next-issue-42', activeAgentIds: live })).toBe(false);- expect(isAbandonedAgentWorktree({ path: '', activeAgentIds: live })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/claim-fix-thing', activeAgentIds: live })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/next-issue-42', activeAgentIds: live })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '', activeAgentIds: live })).toBe(false);});// Sentinel, not a plain collection: an empty Set is an authoritative "nothing is// running" (the common case), while an omitted/non-Set value means liveness is// unknown and must fail safe toward protecting the worktree.it('treats an empty Set as authoritative but an absent one as unknown', () => {- expect(isAbandonedAgentWorktree({ path: '/wt/agent-bbbbbbbb', activeAgentIds: new Set() })).toBe(true);- expect(isAbandonedAgentWorktree({ path: '/wt/agent-bbbbbbbb' })).toBe(false);- expect(isAbandonedAgentWorktree({ path: '/wt/agent-bbbbbbbb', activeAgentIds: ['agent-cccccccc'] })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: new Set() })).toBe(true);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb' })).toBe(false);+ expect(isAbandonedAgentWorktree({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: ['agent-cccccccc'] })).toBe(false);});});describe('isAbandonedClaimWorktree', () => {it('recognizes an unlocked claim tree only with authoritative liveness', () => {- const dirty = { path: '/wt/claim-issue-42', worktreeDirty: true };+ const dirty = { head: RETIRE_HEAD, path: '/wt/claim-issue-42', worktreeDirty: true };expect(isAbandonedClaimWorktree({ ...dirty, activeAgentIds: new Set() })).toBe(true);expect(isAbandonedClaimWorktree({ ...dirty, activeAgentIds: new Set(['claim-issue-42']) })).toBe(false);expect(isAbandonedClaimWorktree({ ...dirty, locked: true, activeAgentIds: new Set() })).toBe(false);@@ -741,9 +780,9 @@ describe('isAbandonedClaimWorktree', () => {it('never treats an agent or ordinary sibling tree as a claim', () => {const activeAgentIds = new Set();- expect(isAbandonedClaimWorktree({ path: '/wt/agent-deadbeef', worktreeDirty: true, activeAgentIds })).toBe(false);- expect(isAbandonedClaimWorktree({ path: '/wt/next-issue-42', worktreeDirty: true, activeAgentIds })).toBe(false);- expect(isAbandonedClaimWorktree({ path: '', worktreeDirty: true, activeAgentIds })).toBe(false);+ expect(isAbandonedClaimWorktree({ head: RETIRE_HEAD, path: '/wt/agent-deadbeef', worktreeDirty: true, activeAgentIds })).toBe(false);+ expect(isAbandonedClaimWorktree({ head: RETIRE_HEAD, path: '/wt/next-issue-42', worktreeDirty: true, activeAgentIds })).toBe(false);+ expect(isAbandonedClaimWorktree({ head: RETIRE_HEAD, path: '', worktreeDirty: true, activeAgentIds })).toBe(false);});});@@ -751,28 +790,28 @@ describe('resolveLiveOwnerReason', () => {const live = new Set(['agent-aaaaaaaa']);it('reports dispatch-side ownership while cleanup keeps claim worktrees protected', () => {- expect(resolveLiveOwnerReason({ path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe('worktree-active-agent');- expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe('worktree-locked');+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe('worktree-active-agent');+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe('worktree-locked');// A claim directory identifies the claim, but not a live process — this side// passes allowLiveClaim. The cleanup-side protection remains covered by// worktreeProtectionReason. A lock still wins, structurally: the gate tests// it before the claim, so no slug rewriting happens here.- expect(resolveLiveOwnerReason({ path: '/wt/claim-fix-thing', activeAgentIds: live })).toBeNull();- expect(resolveLiveOwnerReason({ path: '/wt/claim-fix-thing', locked: true, activeAgentIds: live })).toBe('worktree-locked');+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/claim-fix-thing', activeAgentIds: live })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/claim-fix-thing', locked: true, activeAgentIds: live })).toBe('worktree-locked');});it('lets a LIVE owner outrank the claim exception, not the other way round', () => {// The scheduler adds live claim-worktree basenames to activeAgentIds, and// the gate tests liveness BEFORE the claim exception. Never hand a branch// to an agent while something says a process still owns it.- expect(resolveLiveOwnerReason({ path: '/wt/claim-fix-thing', activeAgentIds: new Set(['claim-fix-thing']) }))+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/claim-fix-thing', activeAgentIds: new Set(['claim-fix-thing']) })).toBe('worktree-active-agent');});it('is null for a free worktree, a dead agent, and no worktree at all', () => {- expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBeNull();- expect(resolveLiveOwnerReason({ path: '/wt/next-issue-42', activeAgentIds: live })).toBeNull();- expect(resolveLiveOwnerReason({ path: null, activeAgentIds: live })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/next-issue-42', activeAgentIds: live })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: null, activeAgentIds: live })).toBeNull();});// The one case worktreeProtectionReason can't answer: it is only ever called with@@ -780,12 +819,12 @@ describe('resolveLiveOwnerReason', () => {// DISPATCH decision that default is backwards — presume live, like// isAbandonedAgentWorktree does.it('presumes an agent worktree is live when liveness is UNKNOWN', () => {- expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb' })).toBe('worktree-agent-liveness-unknown');- expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: ['agent-cccccccc'] })).toBe('worktree-agent-liveness-unknown');+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb' })).toBe('worktree-agent-liveness-unknown');+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: ['agent-cccccccc'] })).toBe('worktree-agent-liveness-unknown');// …but an authoritative empty Set really does mean nothing is running.- expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: new Set() })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/agent-bbbbbbbb', activeAgentIds: new Set() })).toBeNull();// and a non-agent worktree is nobody's live session either way.- expect(resolveLiveOwnerReason({ path: '/wt/next-issue-42' })).toBeNull();+ expect(resolveLiveOwnerReason({ head: RETIRE_HEAD, path: '/wt/next-issue-42' })).toBeNull();});// Ownership lives in the branch NAME (`cos/<taskId>/<agentId>`), so it outlives the@@ -810,6 +849,7 @@ 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 (pinnedRef(args)) return { stdout: RETIRE_HEAD, exitCode: 0 };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 };@@ -987,7 +1027,7 @@ describe('unreachable forge (#3358)', () => {]);wt.listWorktrees.mockResolvedValue([]);git.hasBranchMergeEvidence.mockResolvedValue(false);- execGit.mockImplementation(async (args) => args[0] === 'ls-remote'+ execGit.mockImplementation(async (args) => pinnedRef(args) ? { stdout: RETIRE_HEAD, exitCode: 0 } : args[0] === 'ls-remote'? { stdout: 'sha\trefs/heads/claim/issue-1\n', exitCode: 0 }: { stdout: '', exitCode: 0 });execGh.mockResolvedValue(JSON.stringify([@@ -1088,7 +1128,7 @@ describe('unreachable forge (#3358)', () => {});it('runs clean-and-merged worktree cleanup before a forge probe', async () => {- wt.reapMergedWorktrees.mockResolvedValueOnce({ reaped: [{ branch: 'feature/done' }], skipped: [] });+ wt.reapMergedWorktrees.mockResolvedValueOnce({ reaped: [{ branch: 'feature/done', branchDeleted: true }], skipped: [] });ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });const res = await reconcile('/repo');@@ -1139,17 +1179,17 @@ describe('reconcile', () => {// PRs had merged (deleting their remote branches) sat with their worktrees// intact, and every run reported "cleaned 0 / merged branches held back" for a// week because the claim grace window outranked the fact that they were done.- it('cleans a SHIPPED claim end to end instead of parking on the grace window', async () => {+ it('cleans a shipped claim with verified completion evidence end to end', async () => {git.getBranches.mockResolvedValue([{ name: 'claim/issue-4348', isDefault: false, current: false, tracking: 'origin/claim/issue-4348', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }]);execGh.mockResolvedValue('[]');// ls-remote reports origin has only main — the claim's remote branch was// deleted when its PR merged. Everything else (status, etc.) reads clean.- execGit.mockImplementation(async (args) => args[0] === 'ls-remote'+ execGit.mockImplementation(async (args) => pinnedRef(args) ? { stdout: RETIRE_HEAD, exitCode: 0 } : args[0] === 'ls-remote'? { stdout: 'abc123\trefs/heads/main\n', exitCode: 0 }: { stdout: '', exitCode: 0 });// Idle for hours — past SHIPPED_CLAIM_IDLE_MS, so no live session is implied.@@ -1168,27 +1208,27 @@ describe('reconcile', () => {// The fail-safe half of the same signal: "we could not read origin" must never// read as "the remote branch is gone", or an unreachable network would start// reaping claim worktrees that were never shipped.- it('does NOT treat an unreadable remote as proof a claim shipped', async () => {+ it('does NOT treat an unreadable remote as proof a claim completed', async () => {+ hasCompletedCheckoutEvidence.mockResolvedValue(false);git.getBranches.mockResolvedValue([{ name: 'claim/issue-4348', isDefault: false, current: false, tracking: 'origin/claim/issue-4348', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }]);execGh.mockResolvedValue('[]');- execGit.mockImplementation(async (args) => args[0] === 'ls-remote'+ execGit.mockImplementation(async (args) => pinnedRef(args) ? { stdout: RETIRE_HEAD, exitCode: 0 } : args[0] === 'ls-remote'? { stdout: '', exitCode: 1 } // ls-remote failed → listRemoteHeads returns null: { stdout: '', exitCode: 0 });- // Idle long enough that the SHORT window would have released it — so the only- // thing holding it back is the unreadable remote, which is what this pins.+ // Idle beyond the old short window, but with no exact completion receipt.worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;git.hasBranchMergeEvidence.mockResolvedValue(true);- // A snapshot-only caller cannot replace the human-claim age protection- // with a fresh registry proof under the binding lock.+ // A snapshot-only caller cannot substitute missing remote or ownership+ // data for exact successful completion evidence.const res = await reconcile('/repo', { claimOwners: { agents: [] } });expect(res.cleaned).toEqual([]);- expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-4348', reason: 'worktree-human-claim' });+ expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-4348', reason: 'claim-completion-unverified' });expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();});@@ -1205,7 +1245,7 @@ describe('reconcile', () => {// Branch-aware: only 2190 is merged (gather short-circuits it via merged:true;// this also satisfies the cleanup re-check). 2199 must stay un-merged so it// classifies IN_REVIEW rather than being swept into cleanup.- git.hasBranchMergeEvidence.mockImplementation(async (_dir, branch) => branch === 'next/issue-2190');+ git.hasBranchMergeEvidence.mockImplementation(async (_dir, branch) => branch === 'next/issue-2190' || branch === RETIRE_HEAD);const res = await reconcile('/repo');expect(res.cleaned).toEqual(['next/issue-2190']);@@ -1223,14 +1263,14 @@ describe('reconcile', () => {{ name: 'cos/task-y/agent-live1234', isDefault: false, current: false, tracking: 'origin/cos/task-y/agent-live1234', merged: false }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/agent-live1234', branch: 'refs/heads/cos/task-y/agent-live1234' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/agent-live1234', branch: 'refs/heads/cos/task-y/agent-live1234' }]);git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue(JSON.stringify([{ number: 4001, headRefName: 'cos/task-y/agent-live1234', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));// Clean worktree — the agent has committed and pushed but is still running.- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-live1234']) });expect(res.inFlight).toEqual([]);@@ -1254,7 +1294,7 @@ describe('reconcile', () => {execGh.mockResolvedValue(JSON.stringify([{ number: 4002, headRefName: 'cos/task-z/agent-live5678', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-live5678']) });expect(res.inFlight).toEqual([]);@@ -1266,7 +1306,7 @@ describe('reconcile', () => {{ name: 'claim/issue-42', isDefault: false, current: false, tracking: 'origin/claim/issue-42', merged: false }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-42', branch: 'refs/heads/claim/issue-42' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-42', branch: 'refs/heads/claim/issue-42' }]);git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue(JSON.stringify([@@ -1275,7 +1315,7 @@ describe('reconcile', () => {// The claim has committed its work and is no longer running. A clean claim// tree must be eligible for the same PR reconciliation as any other branch;// the cleanup-side claim guard is tested separately above.- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await reconcile('/repo', { activeAgentIds: new Set() });expect(res.inFlight.map((b) => [b.branch, b.state])).toEqual([['claim/issue-42', 'IN_REVIEW']]);@@ -1291,11 +1331,11 @@ describe('reconcile', () => {{ name: 'cos/task-x/agent-deadbeef', isDefault: false, current: false, tracking: 'origin/main', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);// Uncommitted work in the worktree.- execGit.mockResolvedValue({ stdout: ' M server/services/thing.js\n?? server/services/newThing.js\n', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult(' M server/services/thing.js\n?? server/services/newThing.js\n', 0));const res = await reconcile('/repo', { activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.state)).toEqual(['ABANDONED_WIP']);@@ -1309,10 +1349,10 @@ describe('reconcile', () => {{ name: 'claim/issue-42', isDefault: false, current: false, tracking: null, merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-42', branch: 'refs/heads/claim/issue-42' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-42', branch: 'refs/heads/claim/issue-42' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: ' M server/services/thing.js\n', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult(' M server/services/thing.js\n', 0));const res = await reconcile('/repo', { activeAgentIds: new Set() });@@ -1338,10 +1378,10 @@ describe('reconcile', () => {{ name: 'claim/issue-101', isDefault: false, current: false, tracking: null, merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '?? server/services/newThing.test.js\n', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('?? server/services/newThing.test.js\n', 0));};// Pinned to epic 100, then bound child 101 before cutting it.const owner = (status, metadata = {}) => ({@@ -1390,10 +1430,10 @@ describe('reconcile', () => {{ name: 'claim/issue-101', isDefault: false, current: false, tracking: 'origin/claim/issue-101', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));// The scan saw nobody; the run bound the branch before cleanup reached it.const late = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents: [], readAgents: async () => [owner('running')] } });expect(late.skipped).toEqual([expect.objectContaining({ branch: 'claim/issue-101', reason: 'claim-owner-active' })]);@@ -1405,7 +1445,7 @@ describe('reconcile', () => {it('preserves work written after the scan even when the claim has no owner', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '?? unfinished.js\n', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('?? unfinished.js\n', 0));const result = await cleanupMerged('/repo', 'main', [{branch: 'claim/issue-101', worktreePath: '/repo/data/cos/worktrees/claim-issue-101', worktreeAgeMs: 0,}], { activeAgentIds: new Set(), claimOwners: { agents: [], readAgents: async () => [] } });@@ -1417,7 +1457,7 @@ describe('reconcile', () => {it('preserves a recent claim when a workspace owner appears after the scan', async () => {dirtyClaim();worktreeMtimeMs = Date.now();- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const result = await reconcile('/repo', {activeAgentIds: new Set(),claimOwners: { agents: [], readAgents: async () => [{@@ -1435,10 +1475,10 @@ describe('reconcile', () => {{ name: 'claim/issue-101', isDefault: false, current: false, tracking: 'origin/claim/issue-101', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-101', branch: 'refs/heads/claim/issue-101' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await reconcile('/repo', { activeAgentIds: new Set(), claimOwners: { agents: [owner('running')] } });expect(res.skipped).toEqual([expect.objectContaining({ branch: 'claim/issue-101', reason: 'claim-owner-active' })]);expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();@@ -1451,10 +1491,10 @@ describe('reconcile', () => {{ name: 'cos/task-x/agent-deadbeef', isDefault: false, current: false, tracking: 'origin/main', merged: true }]);wt.listWorktrees.mockResolvedValue([- { path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }]);git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: ' M server/services/thing.js\n', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult(' M server/services/thing.js\n', 0));const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-deadbeef']) });expect(res.inFlight).toEqual([]);@@ -1478,9 +1518,10 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {git.getBranches.mockResolvedValue([{ name: BRANCH, isDefault: false, current: false, tracking: 'origin/main', merged: false }]);- wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);+ wt.listWorktrees.mockResolvedValue([{ head: RETIRE_HEAD, path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => {+ if (pinnedRef(args)) return { stdout: RETIRE_HEAD, exitCode: 0 };const [cmd] = args;if (cmd === 'rev-parse') return { stdout: `${tip}\n`, exitCode: 0 };if (cmd === 'merge-base' && args[1] === '--is-ancestor') {@@ -1510,11 +1551,52 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {}]});+ it('retains superseded unmerged work by default even with cleanup enabled', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger());+ const res = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(res.reapedSuperseded).toEqual([]);+ expect(res.superseded.map(entry => entry.branch)).toEqual([BRANCH]);+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'reap-superseded-disabled' });+ expect(backupSupersededBranchMock).not.toHaveBeenCalled();+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();+ expect(wt.deleteCompletedLocalBranch).not.toHaveBeenCalled();+ });++ it('retains an explicitly opted-in superseded checkout whose head changes during backup', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger());+ const changed = { head: 'b'.repeat(40), path: WORKTREE, branch: `refs/heads/${BRANCH}` };+ backupSupersededBranchMock.mockImplementation(async () => {+ wt.listWorktrees.mockResolvedValue([changed]);+ return { dir: '/backups/x', manifest: 'manifest.json', untracked: [] };+ });+ wt.forceRemoveWorktreeDir.mockImplementation(async (_repo, _path, options) => {+ const reason = await options.verifyRemoval(changed);+ return { removed: !reason, reason };+ });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });+ expect(res.reapedSuperseded).toEqual([]);+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'worktree-holder-changed' });+ expect(wt.deleteCompletedLocalBranch).not.toHaveBeenCalled();+ });++ it('retains an explicitly opted-in superseded ref when its deletion lease fails', async () => {+ setupAbandoned();+ tryReadFileMock.mockResolvedValue(ledger());+ wt.deleteCompletedLocalBranch.mockResolvedValue(false);+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });+ expect(res.reapedSuperseded).toEqual([]);+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'branch-ref-changed-or-delete-failed' });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', BRANCH, RETIRE_HEAD);+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });+it('reaps a branch with a fresh cached verdict, after backing it up', async () => {setupAbandoned();tryReadFileMock.mockResolvedValue(ledger());- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight).toEqual([]);// Reported under its own key, NOT `cleaned` — a superseded branch's work is// not on the default branch — and gone from the prompt's superseded block.@@ -1523,7 +1605,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {expect(res.superseded).toEqual([]);expect(backupSupersededBranchMock).toHaveBeenCalledTimes(1);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', WORKTREE, expect.anything());- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', BRANCH, { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', BRANCH, RETIRE_HEAD);});it('backs up before it deletes anything', async () => {@@ -1534,11 +1616,11 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {order.push('backup');return { dir: '/backups/x', manifest: 'manifest.json', untracked: [] };});- wt.forceRemoveWorktreeDir.mockImplementation(async () => { order.push('remove'); return { removed: true, warning: null }; });- git.deleteBranch.mockImplementation(async () => { order.push('delete'); return { results: { local: 'deleted' } }; });+ wt.forceRemoveWorktreeDir.mockImplementation(async () => { order.push('remove'); wt.listWorktrees.mockResolvedValue([]); return { removed: true, warning: null }; });+ wt.deleteCompletedLocalBranch.mockImplementation(async () => { order.push('delete'); return true; });- await reconcile('/repo', { activeAgentIds: new Set() });- expect(order[0]).toBe('backup');+ await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });+ expect(order).toEqual(['backup', 'remove', 'delete']);});// No recoverable copy, no delete. The verdict is not what makes this safe.@@ -1547,7 +1629,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {tryReadFileMock.mockResolvedValue(ledger());backupSupersededBranchMock.mockRejectedValue(new Error('disk full'));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();expect(git.deleteBranch).not.toHaveBeenCalled();expect(res.superseded.map((b) => b.branch)).toEqual([BRANCH]);@@ -1563,9 +1645,10 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {git.getBranches.mockResolvedValue([{ name: CLAIM, isDefault: false, current: false, tracking: null, merged: false }]);- wt.listWorktrees.mockResolvedValue([{ path: CLAIM_TREE, branch: `refs/heads/${CLAIM}` }]);+ wt.listWorktrees.mockResolvedValue([{ head: RETIRE_HEAD, path: CLAIM_TREE, branch: `refs/heads/${CLAIM}` }]);git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => {+ if (pinnedRef(args)) return { stdout: RETIRE_HEAD, exitCode: 0 };const [cmd] = args;if (cmd === 'rev-parse') return { stdout: 'aaaaaaa\n', exitCode: 0 };if (cmd === 'merge-base' && args[1] === '--is-ancestor') return { stdout: '', exitCode: 0 };@@ -1583,10 +1666,10 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {}]}));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(backupSupersededBranchMock).toHaveBeenCalledTimes(1);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', CLAIM_TREE, expect.anything());- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', CLAIM, { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', CLAIM, RETIRE_HEAD);expect(res.reapedSuperseded).toEqual([CLAIM]);expect(res.superseded).toEqual([]);});@@ -1643,14 +1726,14 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {const idle = await reapSupersededBranches('/repo', 'main', [entry(SUPERSEDED_UNMANAGED_IDLE_MS)], { activeAgentIds: new Set() });expect(backupSupersededBranchMock).toHaveBeenCalledTimes(1);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', TMP_TREE, expect.anything());- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', BRANCH, { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', BRANCH, RETIRE_HEAD);expect(idle.reaped).toEqual([BRANCH]);expect(idle.held).toEqual([]);});it('keeps the unmanaged-location hold for merged cleanup, which has no verdict to lean on', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ execGit.mockImplementation(gitFixtureResult('', 0));const res = await cleanupMerged('/repo', 'main', [{branch: 'next/issue-2190', worktreePath: '/private/tmp/portos-next-2190', worktreeAgeMs: 30 * 24 * 60 * 60 * 1000}]);@@ -1715,7 +1798,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {dirtyPaths: ['server/services/thing.js', 'PORTOS_PUBLIC_REVIEW_INPUT.json']}));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.reapedSuperseded).toEqual([BRANCH]);expect(res.skipped).not.toContainEqual(expect.objectContaining({ branch: BRANCH, reason: 'verdict-does-not-match-branch' })@@ -1741,7 +1824,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned({ tip: 'bbbbbbb' });tryReadFileMock.mockResolvedValue(ledger());- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);expect(res.superseded).toEqual([]);});@@ -1752,7 +1835,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned();tryReadFileMock.mockResolvedValue(ledger({ dirtyPaths: ['server/services/other.js'] }));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);expect(res.superseded).toEqual([]);});@@ -1761,7 +1844,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned();tryReadFileMock.mockResolvedValue(ledger({ collisionPaths: [] }));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);});@@ -1769,7 +1852,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned({ replacedByReachable: false });tryReadFileMock.mockResolvedValue(ledger());- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);expect(res.superseded).toEqual([]);});@@ -1778,7 +1861,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned();tryReadFileMock.mockResolvedValue('{ not json');- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);});@@ -1787,7 +1870,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {setupAbandoned();tryReadFileMock.mockResolvedValue(ledger({ repoPath: '/some/other-app' }));- const res = await reconcile('/repo', { activeAgentIds: new Set() });+ const res = await reconcile('/repo', { reapSuperseded: true, activeAgentIds: new Set() });expect(res.inFlight.map((i) => i.branch)).toEqual([BRANCH]);expect(res.superseded).toEqual([]);});@@ -1799,10 +1882,11 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {// refused to delete a dirty tree, and every pass instead spent a coordinator run// that came back "no real work product, a human should discard it".describe('reconcile — detached-HEAD worktrees (#10825)', () => {- const MAIN = { path: '/repo', head: 'aaa111', branch: 'refs/heads/main' };+ const MAIN = { head: RETIRE_HEAD, path: '/repo', head: 'aaa111', branch: 'refs/heads/main' };const detachedTree = (path, extra = {}) => ({ path, head: 'bbb222', detached: true, ...extra });// Only the ancestry probe cares about argv; status reads clean unless a test says otherwise.const stubGit = ({ merged = true, dirty = false } = {}) => execGit.mockImplementation(async (args) => {+ if (pinnedRef(args)) return { stdout: RETIRE_HEAD, exitCode: 0 };if (args[0] === 'merge-base') return { stdout: '', exitCode: merged ? 0 : 1 };if (args[0] === 'symbolic-ref') return { stdout: '', exitCode: 1 };if (args[0] === 'rev-parse') return { stdout: 'bbb222\n', exitCode: 0 };@@ -1823,6 +1907,24 @@ describe('reconcile — detached-HEAD worktrees (#10825)', () => {expect(res.cleaned).toContain(path);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', path, expect.any(Object));expect(res.detachedWorktrees).toEqual([]);+ expect(preserveMergedCheckout).toHaveBeenCalledWith('/repo', detachedTree(path), 'main');+ });++ it.each(['archive-failed', 'checkout-content-changed'])('preserves detached recovery evidence on %s', async reason => {+ const path = '/repo/data/cos/worktrees/agent-1234abcd';+ wt.listWorktrees.mockResolvedValue([MAIN, detachedTree(path)]);+ stubGit();+ if (reason === 'archive-failed') preserveMergedCheckout.mockRejectedValue(new Error('archive unavailable'));+ else {+ preserveMergedCheckout.mockResolvedValue({ archiveDir: '/archive', verify: async () => reason });+ wt.forceRemoveWorktreeDir.mockImplementation(async (_repo, _path, options) => ({+ removed: false, reason: await options.verifyRemoval(detachedTree(path)),+ }));+ }+ const result = await reconcile('/repo');+ expect(result.cleaned).toEqual([]);+ expect(result.detachedWorktrees).toContainEqual(expect.objectContaining({ path, reason }));+ if (reason === 'archive-failed') expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();});it.each([@@ -1877,7 +1979,7 @@ describe('reconcile — detached-HEAD worktrees (#10825)', () => {it('never gathers the main checkout or a detached tree at unmerged commits', async () => {wt.listWorktrees.mockResolvedValue([- { path: '/repo', head: 'aaa111', detached: true },+ { head: RETIRE_HEAD, path: '/repo', head: 'aaa111', detached: true },detachedTree('/repo/data/cos/worktrees/unmerged-work'),]);stubGit({ merged: false });@@ -1896,9 +1998,10 @@ describe('reconcile — a worktree holding only PortOS runtime scratch', () => {git.getBranches.mockResolvedValue([{ name: BRANCH, isDefault: false, current: false, tracking: null, merged: true }]);- wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);+ wt.listWorktrees.mockResolvedValue([{ head: RETIRE_HEAD, path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockImplementation(async (args) => {+ if (pinnedRef(args)) return { stdout: RETIRE_HEAD, exitCode: 0 };if (args[0] === 'rev-list') return { stdout: '114\t0\n', exitCode: 0 };if (args[0] === 'status') return { stdout: porcelain, exitCode: 0 };return { stdout: '', exitCode: 0 };@@ -1912,7 +2015,7 @@ describe('reconcile — a worktree holding only PortOS runtime scratch', () => {expect(res.inFlight).toEqual([]);expect(res.cleaned).toContain(BRANCH);expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', WORKTREE, expect.anything());- expect(git.deleteBranch).toHaveBeenCalledWith('/repo', BRANCH, { local: true });+ expect(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', BRANCH, RETIRE_HEAD);});it('still holds a worktree carrying one real change alongside the scratch', async () => {@@ -2104,12 +2207,13 @@ describe('desiredEndState', () => {}});- it('offers verified auto-merge before the fallback CI wait in both merge-bound states', () => {+ it('keeps delivery in-session unless a measured backlog has a durable successor', () => {for (const state of ['NEEDS_PR', 'IN_REVIEW']) {const instruction = desiredEndState(state, {});expect(instruction).toContain('gh pr checks <num> --required');- expect(instruction).toContain('--auto --merge --match-head-commit <published-head>');- expect(instruction).toContain('autoMergeRequest.enabledAt');+ expect(instruction).not.toContain('--auto --merge');+ expect(instruction).toContain('mergeHandoffMinQueuedRuns');+ expect(instruction).toContain('Unknown backlog, refused handoff');}});@@ -2340,7 +2444,7 @@ describe('orphaned remote branches', () => {*/const mockRemote = (stdout, { exitCode = 0 } = {}) => {execGit.mockImplementation(async (args) =>- args[0] === 'ls-remote' ? { stdout, exitCode } : { stdout: '', exitCode: 0 }+ pinnedRef(args) ? { stdout: RETIRE_HEAD, exitCode: 0 } : args[0] === 'ls-remote' ? { stdout, exitCode } : { stdout: '', exitCode: 0 });};@@ -2438,10 +2542,11 @@ describe('orphaned remote branches', () => {const res = await reapOrphanedRemotes('/repo', 'main');expect(res.reaped).toEqual([]);expect(res.reported).toEqual([{ branch: 'stale/merged', reason: 'reap-disabled' }]);+ expect(git.deleteMergedRemoteBranches).not.toHaveBeenCalled();expect(git.deleteBranch).not.toHaveBeenCalled();});- it('deletes a merged orphan on the remote when reaping is enabled', async () => {+ it('retires only scanned merged orphans through the fresh remote safety gate', async () => {mockRemote(lsRemote([['stale/merged', 'sha-merged']]));git.getBranches.mockResolvedValue([]);git.hasBranchMergeEvidence.mockResolvedValue(true);@@ -2450,8 +2555,19 @@ describe('orphaned remote branches', () => {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 });+ expect(git.deleteMergedRemoteBranches).toHaveBeenCalledWith('/repo', ['stale/merged'], { defaultBranch: 'main' });+ expect(git.deleteBranch).not.toHaveBeenCalled();+ });++ it('reports the fresh safety gate reason and does not fall back to unleased deletion', async () => {+ mockRemote(lsRemote([['stale/merged', 'sha-merged']]));+ git.getBranches.mockResolvedValue([]);+ git.hasBranchMergeEvidence.mockResolvedValue(true);+ git.deleteMergedRemoteBranches.mockResolvedValue({ deleted: [], skipped: [{ branch: 'stale/merged', reason: 'head changed or deletion failed' }] });+ const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });+ expect(res.reaped).toEqual([]);+ expect(res.reported).toEqual([{ branch: 'stale/merged', reason: 'head changed or deletion failed' }]);+ expect(git.deleteBranch).not.toHaveBeenCalled();});it('names the repo and git\'s own reason when the remote cannot be read', async () => {@@ -2527,17 +2643,6 @@ describe('orphaned remote branches', () => {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.hasBranchMergeEvidence.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', () => {@@ -2558,7 +2663,7 @@ describe('orphaned remote branches', () => {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(wt.deleteCompletedLocalBranch).toHaveBeenCalledWith('/repo', 'next/issue-1', RETIRE_HEAD);expect(git.deleteBranch).not.toHaveBeenCalledWith('/repo', 'left/behind', { remote: true });});@@ -2595,7 +2700,7 @@ describe('orphaned remote branches', () => {describe('worktreeProtectionExpiresAt', () => {const DAY = 24 * 60 * 60 * 1000;const CLAIM = '/repo/data/cos/worktrees/claim-issue-42';- const at = (over = {}) => worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, ...over });+ const at = (over = {}) => worktreeProtectionExpiresAt({ head: RETIRE_HEAD, path: CLAIM, ageMs: 2 * DAY, ...over });it('dates a claim hold to the end of its grace window', () => {const before = Date.now();@@ -2612,7 +2717,7 @@ describe('worktreeProtectionExpiresAt', () => {expect(worktreeProtectionExpiresAt({path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set(['agent-abc12345'])})).toBeNull();- expect(worktreeProtectionExpiresAt({ path: null, ageMs: 2 * DAY })).toBeNull();+ expect(worktreeProtectionExpiresAt({ head: RETIRE_HEAD, path: null, ageMs: 2 * DAY })).toBeNull();});it('returns null when the age is unknown rather than guessing one', () => {@@ -2629,15 +2734,15 @@ describe('worktreeProtectionExpiresAt', () => {// The lock outlives the grace window, and the gate reports it as such: it// tests the lock BEFORE the claim, so a locked claim tree reads// 'worktree-locked' and there is no window here to date.- expect(worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, locked: true })).toBeNull();+ expect(worktreeProtectionExpiresAt({ head: RETIRE_HEAD, path: CLAIM, ageMs: 2 * DAY, locked: true })).toBeNull();});it('gives no expiry to a non-claim worktree that is not held at all', () => {- expect(worktreeProtectionExpiresAt({ path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set() })).toBeNull();+ expect(worktreeProtectionExpiresAt({ head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set() })).toBeNull();});it('returns null when allowLiveClaim is true', () => {- expect(worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, allowLiveClaim: true })).toBeNull();+ expect(worktreeProtectionExpiresAt({ head: RETIRE_HEAD, path: CLAIM, ageMs: 2 * DAY, allowLiveClaim: true })).toBeNull();});});diff --git a/server/services/completedCheckoutEvidence.js b/server/services/completedCheckoutEvidence.jsnew file mode 100644index 0000000000..d28508b5af--- /dev/null+++ b/server/services/completedCheckoutEvidence.js@@ -0,0 +1,96 @@+/** Server-observed checkout identity captured before a claim run completes.+ * A branch name/path/head can all be reused; private Git filesystem identity+ * distinguishes the completed checkout from a later manual checkout.+ */+import { lstat, realpath } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { execGit } from '../lib/execGit.js';+import { isTruthyMeta } from '../lib/metadataFlags.js';++const shortBranch = branch => branch?.replace(/^refs\/heads\//, '');+const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);++async function filesystemIdentity(path, type) {+ const stat = await lstat(path, { bigint: true });+ if (!(type === 'file' ? stat.isFile() : stat.isDirectory()) || typeof stat.dev !== 'bigint'+ || typeof stat.ino !== 'bigint' || stat.ino <= 0n || typeof stat.birthtimeNs !== 'bigint' || stat.birthtimeNs <= 0n) {+ throw new Error('checkout-incarnation-unavailable');+ }+ return { dev: String(stat.dev), ino: String(stat.ino), birthtimeNs: String(stat.birthtimeNs) };+}++async function readCheckoutIdentity({ repoPath, branch, path, head }) {+ const { listWorktrees } = await import('./worktreeManager.js');+ const repository = await realpath(repoPath);+ const checkout = await realpath(path);+ if (checkout === repository || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(head || '')) return null;+ const holders = (await listWorktrees(repository)).filter(tree => shortBranch(tree.branch) === branch);+ if (holders.length !== 1 || await realpath(holders[0].path) !== checkout || holders[0].head !== head) return null;+ const pointer = await filesystemIdentity(join(checkout, '.git'), 'file');+ const gitdir = await realpath((await execGit(['rev-parse', '--absolute-git-dir'], checkout)).stdout.trim());+ const administration = await filesystemIdentity(gitdir, 'directory');+ const [currentHead, currentBranch, common] = await Promise.all([+ execGit(['rev-parse', '--verify', 'HEAD^{commit}'], checkout),+ execGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], checkout),+ execGit(['rev-parse', '--git-common-dir'], checkout),+ ]);+ const repoCommon = await execGit(['rev-parse', '--git-common-dir'], repository);+ if (currentHead.stdout.trim() !== head || currentBranch.stdout.trim() !== branch+ || await realpath(resolve(checkout, common.stdout.trim())) !== await realpath(resolve(repository, repoCommon.stdout.trim()))) return null;+ if (!same(pointer, await filesystemIdentity(join(checkout, '.git'), 'file'))+ || !same(administration, await filesystemIdentity(gitdir, 'directory'))) return null;+ return { repoPath: repository, branch, path: checkout, head, incarnation: { pointer, gitdir: { path: gitdir, ...administration } } };+}++/** Called under the agent-state lock while the successful run still owns its+ * current claim bindings. Never manufacture evidence for historical releases.+ * Capture errors withhold cleanup authority without breaking completion.+ */+export async function captureCompletedCheckouts(agent, { success } = {}) {+ const meta = agent?.metadata;+ if (success !== true || !['running', 'paused'].includes(agent?.status) || !agent.id+ || !Number.isFinite(Date.parse(agent.startedAt)) || !isTruthyMeta(meta?.claimPicksOwnBranch)+ || typeof meta.sourceWorkspace !== 'string' || !Array.isArray(meta.claimBranches)) return [];+ const { listWorktrees } = await import('./worktreeManager.js');+ const trees = await listWorktrees(meta.sourceWorkspace).catch(() => null);+ if (!trees) return [];+ const receipts = [];+ for (const branch of new Set(meta.claimBranches)) {+ if (typeof branch !== 'string' || !branch) continue;+ const holders = trees.filter(tree => shortBranch(tree.branch) === branch);+ if (holders.length !== 1) continue;+ const target = { repoPath: meta.sourceWorkspace, branch, path: holders[0].path, head: holders[0].head };+ const first = await readCheckoutIdentity(target).catch(() => null);+ if (!first || !same(first, await readCheckoutIdentity(target).catch(() => null))) continue;+ receipts.push({ version: 1, agentId: agent.id, startedAt: agent.startedAt, capturedAt: new Date().toISOString(), ...first });+ }+ return receipts;+}++/** Revalidate immediately before retirement as well as before archival. Older+ * completed records, failures and reused checkout incarnations grant nothing.+ */+export async function hasCompletedCheckoutEvidence(records, target) {+ if (!Array.isArray(records)) return false;+ const current = await readCheckoutIdentity(target).catch(() => null);+ if (!current) return false;+ const scoped = (await Promise.all(records.map(async agent => {+ const meta = agent?.metadata;+ const branches = [meta?.worktreeBranch,+ ...(Array.isArray(meta?.claimBranches) ? meta.claimBranches : []),+ ...(Array.isArray(meta?.claimReleasedBranches) ? meta.claimReleasedBranches : [])];+ if (!branches.includes(current.branch) || typeof meta?.sourceWorkspace !== 'string') return null;+ return await realpath(meta.sourceWorkspace).catch(() => null) === current.repoPath ? agent : null;+ }))).filter(Boolean);+ return scoped.some(agent => agent?.status === 'completed' && agent.result?.success === true+ // A later run can reuse an existing checkout without changing its inode or+ // head. Its failure/missing receipt supersedes the older success. Unknown+ // ordering is also a hold; only an unambiguous newest owner can grant this.+ && scoped.every(other => other === agent || Date.parse(other.startedAt) < Date.parse(agent.startedAt))+ && isTruthyMeta(agent.metadata?.claimPicksOwnBranch) && Array.isArray(agent.metadata?.completedCheckouts)+ && agent.metadata.completedCheckouts.some(receipt => receipt?.version === 1+ && receipt.agentId === (agent.id || agent.agentId) && receipt.startedAt === agent.startedAt+ && Number.isFinite(Date.parse(receipt.capturedAt)) && Date.parse(receipt.capturedAt) >= Date.parse(agent.startedAt)+ && Date.parse(receipt.capturedAt) <= Date.parse(agent.completedAt)+ && same(current, { repoPath: receipt.repoPath, branch: receipt.branch, path: receipt.path, head: receipt.head, incarnation: receipt.incarnation })));+}diff --git a/server/services/completedCheckoutEvidence.test.js b/server/services/completedCheckoutEvidence.test.jsnew file mode 100644index 0000000000..8609fb43f4--- /dev/null+++ b/server/services/completedCheckoutEvidence.test.js@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdir, mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execGit } from '../lib/execGit.js';+import { materializeGitRepo } from '../lib/gitTestRepo.js';+import { captureCompletedCheckouts, hasCompletedCheckoutEvidence } from './completedCheckoutEvidence.js';++describe('completed claim checkout evidence', () => {+ let scratch, repoPath, path, head, agent;+ const branch = 'claim/issue-1';+ const target = () => ({ repoPath, path, branch, head });+ const completed = receipts => ({ ...agent, status: 'completed', completedAt: new Date().toISOString(),+ result: { success: true }, metadata: { ...agent.metadata, completedCheckouts: receipts } });++ beforeEach(async () => {+ // Preserve tmpdir's spelling for the destructive fixture guard: Windows+ // may expose TEMP as an 8.3 alias while async realpath returns its long name.+ scratch = await mkdtemp(join(tmpdir(), 'completed-checkout-'));+ repoPath = join(scratch, 'repo');+ path = join(scratch, 'claim');+ await mkdir(repoPath);+ await materializeGitRepo(repoPath, { identity: { name: 'Test', email: '[email protected]' } });+ await execGit(['worktree', 'add', '-b', branch, path, 'main'], repoPath);+ head = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();+ agent = { id: 'agent-1', status: 'running', startedAt: new Date(Date.now() - 1000).toISOString(),+ metadata: { claimPicksOwnBranch: true, sourceWorkspace: repoPath, claimBranches: [branch] } };+ });+ afterEach(async () => { await rm(scratch, { recursive: true, force: true, maxRetries: 3 }); });++ it('rejects a new checkout reusing the completed branch, path and exact head', async () => {+ const receipts = await captureCompletedCheckouts(agent, { success: true });+ expect(receipts).toHaveLength(1);+ const record = completed(receipts);+ expect(await hasCompletedCheckoutEvidence([record], target())).toBe(true);+ await execGit(['worktree', 'remove', path], repoPath);+ await execGit(['worktree', 'add', path, branch], repoPath);+ expect((await execGit(['rev-parse', 'HEAD'], path)).stdout.trim()).toBe(head);+ expect(await hasCompletedCheckoutEvidence([record], target())).toBe(false);+ });++ it('withholds proof for failed, historical, released, unreadable or changed checkouts', async () => {+ expect(await captureCompletedCheckouts(agent, { success: false })).toEqual([]);+ expect(await captureCompletedCheckouts({ ...agent, status: 'completed' }, { success: true })).toEqual([]);+ expect(await captureCompletedCheckouts({ ...agent, metadata: { ...agent.metadata, claimBranches: [], claimReleasedBranches: [branch] } }, { success: true })).toEqual([]);+ expect(await hasCompletedCheckoutEvidence([completed([])], target())).toBe(false);++ const receipts = await captureCompletedCheckouts(agent, { success: true });+ const record = completed(receipts);+ expect(await hasCompletedCheckoutEvidence([{ ...record, result: { success: false } }], target())).toBe(false);+ expect(await hasCompletedCheckoutEvidence([{ ...record, startedAt: '2025-01-01T00:00:00Z' }], target())).toBe(false);+ await execGit(['commit', '--allow-empty', '-m', 'later work'], path);+ head = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();+ expect(await hasCompletedCheckoutEvidence([record], target())).toBe(false);+ await execGit(['worktree', 'remove', path], repoPath);+ expect(await captureCompletedCheckouts(agent, { success: true })).toEqual([]);+ expect(await hasCompletedCheckoutEvidence([record], target())).toBe(false);+ });++ it('does not let an older success authorize the unchanged checkout after a newer claim fails', async () => {+ const record = completed(await captureCompletedCheckouts(agent, { success: true }));+ expect(await hasCompletedCheckoutEvidence([record], target())).toBe(true);+ for (const binding of [{ claimBranches: [branch] }, { claimReleasedBranches: [branch] }, { worktreeBranch: branch }]) {+ const newer = { id: 'agent-2', status: 'completed', startedAt: new Date().toISOString(),+ result: { success: false }, metadata: { sourceWorkspace: repoPath, ...binding } };+ expect(await hasCompletedCheckoutEvidence([record, newer], target())).toBe(false);+ // A reported success with no server receipt and unreadable ordering also+ // cannot revive the older run's authority over this same checkout.+ expect(await hasCompletedCheckoutEvidence([record, { ...newer, result: { success: true } }], target())).toBe(false);+ expect(await hasCompletedCheckoutEvidence([record, { ...newer, startedAt: null }], target())).toBe(false);+ }+ });+});diff --git a/server/services/cos.js b/server/services/cos.jsindex 944ac778fd..8bd371c9b9 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -570,6 +570,8 @@ async function bootDaemon(state) {intervalMs: PENDING_MERGE_SWEEP_INTERVAL_MS,handler: async () => {if (await pendingMergeSweepBlocked()) return;+ const { sweepRepoStateVerifications } = await import('./agentRepoStateVerification.js');+ await sweepRepoStateVerifications().catch(err => console.warn(`⚠️ Completion recovery sweep deferred: ${err.message}`));const prWatcher = await import('./prWatcher.js');const sweep = await prWatcher.sweepPendingMergePrs().catch((err) => {console.warn(`⚠️ sweepPendingMergePrs failed: ${err?.message || err}`);diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex d99e2db0c7..03a76904f8 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -62,6 +62,13 @@ export async function updateAgent(agentId, updates) {updates = { ...updates, metadata: { ...updates.metadata, securityScan: previousScan } };}+ // Each claim-swarm branch has its own recovery. Merge these server-written+ // backlinks under the state lock so sibling audits cannot revoke one another.+ if (updates.metadata?.repoStateRecoveries) {+ updates = { ...updates, metadata: { ...updates.metadata, repoStateRecoveries: {+ ...state.agents[agentId].metadata?.repoStateRecoveries, ...updates.metadata.repoStateRecoveries,+ } } };+ }// Merge metadata if present in updatesif (updates.metadata) {state.agents[agentId] = {@@ -135,6 +142,43 @@ async function archiveCompletedAgent(agentId, agent) {await saveAgentIndex();}+/** Persist completion work after live-state retention expires. The same state+ * lock serializes live updates and archive rewrites; no transcript is loaded.+ */+export function recordRepoStateVerification(agentId, verification) {+ return updateCompletionReceipt(agentId, metadata => ({ ...metadata, repoStateVerification: verification }));+}++/** Server-only recovery backlink; works after the parent leaves live retention. */+export function recordRepoStateRecovery(agentId, link, { claimRun = false } = {}) {+ return updateCompletionReceipt(agentId, metadata => ({ ...metadata, repoStateRecovery: link,+ ...(claimRun ? { repoStateRecoveries: { ...metadata?.repoStateRecoveries, [link.branch]: link } } : {}),+ }));+}++async function updateCompletionReceipt(agentId, update) {+ return withBackupAssetPublication(() => withStateLock(async () => {+ const state = await loadState();+ let agent = state.agents[agentId];+ const date = agent?.completedAt?.slice(0, 10) || (await loadAgentIndex()).get(agentId);+ if (!agent && date) {+ const content = await tryReadFile(join(getAgentDir(agentId, date), 'metadata.json'));+ if (!content) return false;+ agent = JSON.parse(content);+ }+ if (!agent || (agent.id || agent.agentId) !== agentId || agent.status !== 'completed') return false;+ const updated = { ...agent, metadata: update(agent.metadata || {}) };+ // Never synthesize a bucket before archiveCompletedAgent moved the flat+ // directory: its retry treats an existing bucket as the completed move.+ if (date && (!state.agents[agentId] || await tryReadFile(join(getAgentDir(agentId, date), 'metadata.json')))) {+ const { output: _output, ...record } = updated;+ await atomicWrite(join(getAgentDir(agentId, date), 'metadata.json'), record);+ }+ if (state.agents[agentId]) { state.agents[agentId] = updated; await saveState(state); }+ return true;+ }));+}+export async function completeAgent(agentId, result = {}) {const existing = await getAgentRecord(agentId);if (existing?.metadata?.taskAnalysisType === 'security' && existing.metadata.useRunner) {@@ -174,6 +218,18 @@ export async function completeAgent(agentId, result = {}) {return state.agents[agentId];}+ // Capture while the state lock still protects this run's active bindings.+ // A later audit must never turn an old branch name into checkout authority.+ const agent = state.agents[agentId];+ let completedCheckouts;+ if (agent.metadata?.claimPicksOwnBranch) {+ completedCheckouts = [];+ if (result.success === true) {+ const { captureCompletedCheckouts } = await import('./completedCheckoutEvidence.js');+ completedCheckouts = await captureCompletedCheckouts(agent, { success: true }).catch(() => []);+ }+ }+state.agents[agentId] = {...state.agents[agentId],status: 'completed',@@ -184,7 +240,10 @@ export async function completeAgent(agentId, result = {}) {// "not declared" with "declared and failed" (false). Distinct from// result.success (the runner's exit-code verdict).result: { validationPassed: null, ...result },+ ...(result.success && (state.agents[agentId].metadata?.isWorktree || state.agents[agentId].metadata?.claimPicksOwnBranch)+ ? { metadata: { ...state.agents[agentId].metadata, repoStateVerification: { status: 'pending' } } } : {}),};+ if (completedCheckouts) state.agents[agentId].metadata = { ...state.agents[agentId].metadata, completedCheckouts };if (result.success) {state.stats.tasksCompleted++;diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex 5bdf335c4d..458b6e5db5 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -29,6 +29,8 @@ vi.mock('./domainUsage.js', () => ({recordDomainUsage: vi.fn(async () => {})}));+vi.mock('./completedCheckoutEvidence.js', () => ({ captureCompletedCheckouts: vi.fn(async () => []) }));+// Pass-through fs shim with opt-in failure injection, so one test can force the// archive's cross-filesystem fallback AND a failure partway through its copy.// Scoped to paths inside a `YYYY-MM-DD` bucket so the flat-dir writes that@@ -88,13 +90,14 @@ vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importdataRoot: () => lazyTempDataRoot('portos-cos-lifecycle-'),}));-import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, deleteAgent, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';+import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, recordRepoStateVerification, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, deleteAgent, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.js';import { recordDomainUsage } from './domainUsage.js';import { cosEvents } from './cosEvents.js';import { loadAgentIndex } from './cosAgentIndex.js';import { getActiveAgentsFromRunner, requestSecurityScanViaRunner } from './cosRunnerClient.js';import { persistAgentSecurityScan } from './agentSecurityScan.js';+import { captureCompletedCheckouts } from './completedCheckoutEvidence.js';import { activeAgents, runnerAgents, completingAgents, spawningTasks } from './agentState.js';afterAll(cleanupTempDataRoots);@@ -447,6 +450,7 @@ describe('completeAgent idempotence (#3384)', () => {emittedCompletions.length = 0;recordDomainUsage.mockClear();recordDomainUsage.mockImplementation(async () => {});+ captureCompletedCheckouts.mockReset().mockResolvedValue([]);cosEvents.on('agent:completed', (agent) => emittedCompletions.push(agent));});@@ -456,6 +460,37 @@ describe('completeAgent idempotence (#3384)', () => {cosEvents.removeAllListeners('agent:completed');});+ it('archives checkout evidence captured while the successful claim still owns its bindings', async () => {+ const agentId = 'claim-completion';+ const receipt = { version: 1, agentId, branch: 'claim/issue-1' };+ mockCosState.state.agents[agentId] = { id: agentId, status: 'running', startedAt: '2026-01-01T00:00:00Z',+ metadata: { claimPicksOwnBranch: true, claimBranches: [receipt.branch] }, output: [] };+ captureCompletedCheckouts.mockImplementationOnce(async agent => {+ expect(agent.status).toBe('running');+ expect(mockCosState.state.agents[agentId].status).toBe('running');+ return [receipt];+ });+ const result = await completeAgent(agentId, { success: true });+ expect(result.metadata.completedCheckouts).toEqual([receipt]);+ const archived = JSON.parse(await readFile(join(mockCosState.agentsDir, result.completedAt.slice(0, 10), agentId, 'metadata.json'), 'utf8'));+ expect(archived.metadata.completedCheckouts).toEqual([receipt]);+ await completeAgent(agentId, { success: true });+ expect(captureCompletedCheckouts).toHaveBeenCalledTimes(1);+ });++ it('completes without checkout authority when capture fails or the claim fails', async () => {+ const agentId = 'claim-capture-failed';+ mockCosState.state.agents[agentId] = { id: agentId, status: 'running', metadata: { claimPicksOwnBranch: true }, output: [] };+ captureCompletedCheckouts.mockRejectedValueOnce(new Error('checkout unreadable'));+ const result = await completeAgent(agentId, { success: true });+ expect(result).toMatchObject({ status: 'completed', result: { success: true }, metadata: { completedCheckouts: [] } });+ mockCosState.state.agents['claim-failed'] = { id: 'claim-failed', status: 'running',+ metadata: { claimPicksOwnBranch: true, completedCheckouts: [{ stale: true }] }, output: [] };+ const failed = await completeAgent('claim-failed', { success: false });+ expect(failed.metadata.completedCheckouts).toEqual([]);+ expect(captureCompletedCheckouts).toHaveBeenCalledTimes(1);+ });+it('keeps the first verdict when a duplicate completion arrives', async () => {// Regression: a stray runner `agent:completed` for an agent that had already// finalized on its own sentinel replaced a recorded success with@@ -589,6 +624,12 @@ describe('completeAgent idempotence (#3384)', () => {);expect(existsSync(archiveDir)).toBe(false);+ // A completion sweep between failure and retry must not create a bucket+ // that makes archiveCompletedAgent skip the original transcript move.+ await recordRepoStateVerification(agentId, { status: 'pending', reasons: ['retry'] });+ expect(existsSync(archiveDir)).toBe(false);+ expect(await readFile(join(flatDir, 'output.txt'), 'utf8')).toBe('the run that finished\n');+fsFailures.dateBucketWritesFail = false;recordDomainUsage.mockClear();emittedCompletions.length = 0;diff --git a/server/services/cosMergeAdmission.cleanupRecovery.test.js b/server/services/cosMergeAdmission.cleanupRecovery.test.jsindex ca29b09dfb..f43d17e72b 100644--- a/server/services/cosMergeAdmission.cleanupRecovery.test.js+++ b/server/services/cosMergeAdmission.cleanupRecovery.test.js@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { join } from 'node:path';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';@@ -6,6 +7,7 @@ import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js'// recovery for a parent whose PR is still open; that recovery lands the PR// inside repository merge admission. Authority comes from the audit's own// forge observation and its backlink on the parent, never a caller claim.+vi.mock('../lib/backupSnapshotBoundary.js', () => ({ withBackupAssetPublication: work => work() }));const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, archive: {} }));vi.mock('./cosState.js', () => ({AGENTS_DIR: '/synthetic/agents',@@ -23,6 +25,7 @@ vi.mock('./cosAgentIndex.js', async () => ({...await vi.importActual('./cosAgentIndex.js'),loadAgentIndex: async () => new Map([['parent-1', '2026-01-01']]),}));+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: async () => Object.values(f.state.agents) }));vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] ?? null }));vi.mock('./cos.js', () => ({@@ -57,7 +60,7 @@ import { addTask } from './cos.js';import { findPullRequestForBranch } from './github.js';import { buildTaskMetadata } from './cosTaskIntake.js';import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';-import { registerAgent } from './cosAgentLifecycle.js';+import { registerAgent, recordRepoStateRecovery } from './cosAgentLifecycle.js';import { verifyAgentRepoState } from './agentRepoStateVerification.js';import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';@@ -92,6 +95,7 @@ beforeEach(() => {f.state = { agents: { 'parent-1': { id: 'parent-1', taskId: 'task-parent', status: 'completed', startedAt: '2026-01-01T00:00:00Z',completedAt: '2026-01-01T01:00:00Z', metadata: { isWorktree: true, sourceWorkspace: '/repos/source', worktreeBranch: BRANCH,workspacePath: '/repos/source/data/cos/worktrees/parent-1', prOpenedBy: 'agent-slashdo' } } }, mergeAdmissions: {}, stats: { agentsSpawned: 0 } };+ f.archive[join('/synthetic/agents', '2026-01-01', 'parent-1', 'metadata.json')] = JSON.stringify(f.state.agents['parent-1']);persist();});@@ -110,6 +114,24 @@ describe('repository-cleanup recovery merge admission', () => {expect(f.state.agents['recovery-1'].metadata.claimPicksOwnBranch).toBeUndefined();});+ it('keeps admission for both claim-swarm recoveries after the second backlink is written', async () => {+ const parent = f.state.agents['parent-1'];+ parent.metadata = { ...parent.metadata, isWorktree: false, worktreeBranch: null,+ claimPicksOwnBranch: true, claimBranches: ['claim/issue-11', 'claim/issue-12'] };+ findPullRequestForBranch.mockImplementation(async branch => ({ status: 'found', detail: 'OPEN',+ url: `https://github.com/example/repo/pull/${branch.endsWith('11') ? 11 : 12}` }));+ addTask.mockResolvedValueOnce({ id: 'task-first' }).mockResolvedValueOnce({ id: 'task-second' });+ await verifyAgentRepoState({ agentId: 'parent-1', task: parentTask, agentState: parent, success: true });+ expect(Object.keys(f.state.agents['parent-1'].metadata.repoStateRecoveries)).toEqual(['claim/issue-11', 'claim/issue-12']);+ for (const [index, id] of ['task-first', 'task-second'].entries()) {+ await register('recovery-1', queue(id, addTask.mock.calls[index][0]));+ const lease = await admission('acquire');+ expect(lease.admitted).toBe(true);+ await admission('release', lease.token, { outcome: 'merged' });+ delete f.state.agents['recovery-1']; persist();+ }+ });+it('verifies a parent already archived out of live state through its persisted backlink', async () => {await fileAndLaunch();delete f.state.agents['parent-1']; persist();@@ -118,6 +140,22 @@ describe('repository-cleanup recovery merge admission', () => {expect(await admission('release', lease.token, { outcome: 'merged' })).toMatchObject({ released: true });});+ it('binds a recovery after the parent has already left live retention', async () => {+ const parent = f.state.agents['parent-1'];+ delete f.state.agents['parent-1']; persist();+ const audit = await verifyAgentRepoState({ agentId: 'parent-1', task: parentTask, agentState: parent, success: true, prExpected: true });+ expect(audit.recoveryTaskId).toBe('task-recovery-1');+ await register('recovery-1', queue('task-recovery-1', addTask.mock.calls.at(-1)[0]));+ expect(await admission('acquire')).toMatchObject({ admitted: true });+ });++ it('does not synthesize a date bucket while a failed archive move still owns the flat directory', async () => {+ f.archive = {};+ await recordRepoStateRecovery('parent-1', { taskId: 'recovery', url: PR_URL, branch: BRANCH });+ expect(f.archive).toEqual({});+ expect(f.disk.agents['parent-1'].metadata.repoStateRecovery.taskId).toBe('recovery');+ });+it('keeps the repository-wide lease exclusive against claim runs and the sweep', async () => {await fileAndLaunch();f.state.agents.claim = { id: 'claim', taskId: 'claim-task', status: 'running', startedAt: new Date().toISOString(),diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex 0ed83fee63..f6e89a6344 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -263,9 +263,12 @@ async function verifiedCleanupRecovery(agent, repository, agents) {const { readAgentRecordOrUnreadable } = await import('./cosAgentLifecycle.js');parent = await readAgentRecordOrUnreadable(parentAgentId);}- const link = parent?.metadata?.repoStateRecovery;+ const link = parent?.metadata?.repoStateRecoveries?.[target.branch] || parent?.metadata?.repoStateRecovery;+ const parentBranches = [parent?.metadata?.worktreeBranch,+ ...(Array.isArray(parent?.metadata?.claimBranches) ? parent.metadata.claimBranches : []),+ ...(Array.isArray(parent?.metadata?.claimReleasedBranches) ? parent.metadata.claimReleasedBranches : [])];if (!isPlainObject(parent) || parent.id !== parentAgentId || parent.taskId !== parentTaskId || parent.status !== 'completed'- || parent.metadata.worktreeBranch !== target.branch || parent.metadata.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN+ || !parentBranches.includes(target.branch) || parent.metadata.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN|| !isPlainObject(link) || link.taskId !== agent.taskId || link.url !== target.url || link.branch !== target.branch|| !parent.metadata.sourceWorkspace) return false;return repositoryKey(await getOriginInfo(parent.metadata.sourceWorkspace).catch(() => null)) === repository;diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.jsindex 8b7b1f0140..056b9d8956 100644--- a/server/services/cosMergeHandoff.js+++ b/server/services/cosMergeHandoff.js@@ -16,7 +16,7 @@ import { execGh } from './github.js';import { resolveForgeExecOptions } from './forgeExecOptions.js';import { getOriginInfo } from '../lib/gitRemote.js';import { parsePullRequestUrl } from '../lib/gitForge.js';-import { githubRepoSpec } from '../lib/workTracker.js';+import { githubApiHost, githubRepoSpec } from '../lib/workTracker.js';import { execGit } from '../lib/execGit.js';import { safeJSONParse } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';@@ -123,10 +123,15 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePatconst app = await resolveHandoffApp(task, agent, repository, repositoryKey);if (!app) return refuse('pending-merge-app-unresolved');+ // Default ownership stays with the run. Operators opt in only after choosing+ // a queued-run threshold appropriate for their CI runner capacity.+ const threshold = app.mergeHandoffMinQueuedRuns;+ if (!Number.isSafeInteger(threshold) || threshold < 1) return refuse('ci-backlog-policy-disabled');+const forgeExec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });const raw = await execGh(['pr', 'view', String(pr.number), '--repo', repoSpec,- '--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid',+ '--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid,mergeable,reviewDecision,statusCheckRollup',], undefined, { cwd: forgeExec.cwd, env: forgeExec.env, backoffKey: repoSpec }).catch(() => null);const view = raw === null ? null : safeJSONParse(raw, null);if (!isPlainObject(view) || view.number !== pr.number) return refuse('pr-unreadable');@@ -146,6 +151,28 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePatconst roster = await followUpRoster(task, policy);if (!reviewEvidenceAccepted(review, head, policy, roster)) return refuse('review-evidence-incomplete');+ const checks = view.statusCheckRollup;+ const pending = new Set(['QUEUED', 'WAITING', 'REQUESTED', 'PENDING', 'EXPECTED']);+ const green = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);+ const healthy = check => (!check?.conclusion || green.has(check.conclusion))+ && (pending.has(check?.status || check?.state) || check?.status === 'IN_PROGRESS' || green.has(check?.conclusion || check?.state));+ if (view.mergeable !== 'MERGEABLE' || !['', 'APPROVED'].includes(view.reviewDecision ?? '')+ || !Array.isArray(checks) || !checks.length || !checks.every(healthy)+ || !checks.some(check => pending.has(check?.status || check?.state))) return refuse('pr-not-waiting-on-healthy-ci');+ const { mergeHandoffSuccessorBlocked } = await import('./prWatcher.js');+ if (await mergeHandoffSuccessorBlocked()) return refuse('merge-successor-unavailable');++ // Read server-side evidence, never a caller's assertion that CI is busy.+ // Unknown/unsupported backlog keeps the original owner waiting.+ const backlogRaw = await execGh(['api', '--hostname', githubApiHost(pr.host),+ `repos/${pr.owner}/${pr.repo}/actions/runs?status=queued&per_page=1`], undefined,+ { cwd: forgeExec.cwd, env: forgeExec.env, backoffKey: repoSpec }).catch(() => null);+ const backlog = backlogRaw === null ? null : safeJSONParse(backlogRaw, null);+ if (!Number.isSafeInteger(backlog?.total_count) || backlog.total_count < 0+ || !Array.isArray(backlog.workflow_runs)) return refuse('ci-backlog-unreadable');+ if (backlog.total_count < threshold) return refuse('ci-backlog-below-threshold');+ const backlogEvidence = { queuedRuns: backlog.total_count, minimumQueuedRuns: threshold, observedAt: new Date().toISOString() };+const receipt = {id: randomUUID(), appId: app.id, prUrl, prNumber: pr.number, headSha: head, repository,queuedAt: new Date().toISOString(),@@ -171,7 +198,7 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat},handoff: {receiptId: receipt.id, agentId, startedAt: agent.startedAt, taskId: agent.taskId, repository,- headSha: head, worktreePath: workspace, prCompletion: policy, reviewStatus: review.status ?? 'not-configured', acceptedAt: receipt.queuedAt,+ headSha: head, worktreePath: workspace, backlog: backlogEvidence, prCompletion: policy, reviewStatus: review.status ?? 'not-configured', acceptedAt: receipt.queuedAt,},followUp: roster,}).catch((err) => {diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.jsindex 8c7c8c5458..28acab44f5 100644--- a/server/services/cosMergeHandoff.test.js+++ b/server/services/cosMergeHandoff.test.js@@ -6,7 +6,7 @@ import { join } from 'node:path';// Agent → server pending-merge handoff (#12247), end to end through the real// admission service and the real pr-watcher coordinator over synthetic stores.const f = vi.hoisted(() => ({- state: null, tasks: {}, apps: new Map(), checkouts: {}, pr: null, foreign: new Set(), optionalReviewers: [],+ state: null, tasks: {}, apps: new Map(), checkouts: {}, pr: null, foreign: new Set(), optionalReviewers: [], queueWriteFailure: false,}));vi.mock('./cosState.js', async () => {const { createFileWriteQueue } = await import('../lib/fileWriteQueue.js');@@ -17,6 +17,7 @@ vi.mock('./cosState.js', async () => {readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.state) }),};});+vi.mock('./cos.js', () => ({ addTask: vi.fn(async () => ({ id: 'cleanup-recovery' })) }));vi.mock('./cosTaskStore.js', () => ({ getTaskById: async (id) => f.tasks[id] ?? null }));vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: async (path) => ({ host: 'github.com', fullName: f.foreign.has(path) ? 'example/other' : 'example/repo' }),@@ -40,7 +41,7 @@ vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async (cwd) =vi.mock('./apps.js', () => ({getAppById: async (id) => f.apps.get(id) ?? null,getActiveApps: async () => [...f.apps.values()],- updateApp: async (id, patch) => { const next = { ...f.apps.get(id), ...patch }; f.apps.set(id, next); return next; },+ updateApp: async (id, patch) => { if (f.queueWriteFailure) throw new Error('disk unavailable'); const next = { ...f.apps.get(id), ...patch }; f.apps.set(id, next); return next; },}));vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent: async () => ({ ok: true, screening: { safe: true } }) }));vi.mock('./codeReview.js', () => ({@@ -62,6 +63,7 @@ vi.mock('./heldCheckoutRecovery.js', () => ({ retirePendingMergeCheckout: (...arimport { handoffPendingMerge, hasQueuedMergeHandoff } from './cosMergeHandoff.js';import { processPendingMergePrs, readPendingMergePrs } from './prWatcher.js';import { claimMergeAdmission } from './cosMergeAdmission.js';+import { addTask } from './cos.js';const HEAD = 'a'.repeat(40);const PR_URL = 'https://github.com/example/repo/pull/7';@@ -86,35 +88,178 @@ beforeAll(async () => { workspace = await mkdtemp(join(tmpdir(), 'merge-handoff-afterAll(async () => { await rm(workspace, { recursive: true, force: true }); });beforeEach(async () => {+ (await import('./prWatcher.js')).cancelHandoffFollowUps();+ (await import('./prWatcher.js')).setHandoffFollowUpGate(async () => null);cleanupMock.mockReset().mockResolvedValue({ ok: true, branchDeleted: true, archiveDir: '/archives/example' });f.state = { agents: { 'agent-1': claimAgent('agent-1', 'claim/issue-1'), 'agent-2': claimAgent('agent-2', 'claim/issue-2') }, mergeAdmissions: {} };f.tasks = Object.fromEntries(['agent-1', 'agent-2'].map((id) => [`task-${id}`, {id: `task-${id}`, status: 'in_progress', taskType: 'user', priority: 'MEDIUM', description: 'Example change',metadata: { app: 'app1', prCompletion: 'review-then-merge' },}]));- f.apps = new Map([['app1', { id: 'app1', repoPath: '/repos/source', forgeAccount: null }]]);+ f.apps = new Map([['app1', { id: 'app1', repoPath: '/repos/source', forgeAccount: null, mergeHandoffMinQueuedRuns: 3 }]]);f.checkouts = { [workspace]: { branch: 'claim/issue-1', head: HEAD } };f.foreign = new Set();f.optionalReviewers = [];+ f.queueWriteFailure = false;f.pr = {number: 7, title: 'Example change', body: 'Closes #101', author: { login: 'example-user' },commits: [{ messageHeadline: 'fix: example', messageBody: '' }], state: 'OPEN', isDraft: false,isCrossRepository: false, headRefName: 'claim/issue-1', headRefOid: HEAD,- mergeStateStatus: 'CLEAN', statusCheckRollup: [{ status: 'IN_PROGRESS' }],+ mergeStateStatus: 'CLEAN', mergeable: 'MERGEABLE', reviewDecision: 'APPROVED', statusCheckRollup: [{ status: 'QUEUED' }],};await writeFile(join(workspace, 'portos-review-status'), `REVIEW_STATUS=clean\nREVIEW_HEAD=${HEAD}\n`);execGhMock.mockReset().mockImplementation(async (args) => {if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify(f.pr);if (args[0] === 'pr' && args[1] === 'diff') return 'diff --git a/example.js b/example.js\n+const ok = true;';+ if (args[0] === 'api' && args.some(arg => arg.includes('/actions/runs?'))) return JSON.stringify({ total_count: 3, workflow_runs: [{ status: 'queued' }] });if (args[0] === 'api') return JSON.stringify({ number: 101, state: 'open', title: 'Example', body: 'Example need', assignees: [] });throw new Error('unexpected forge read');});mergePrMock.mockReset().mockResolvedValue({ success: true });notifyMock.mockClear();followUpMock.mockClear();+ addTask.mockClear();});describe('pending-merge handoff', () => {+ it('keeps original ownership by default and when backlog is unknown or below the configured threshold', async () => {+ delete f.apps.get('app1').mergeHandoffMinQueuedRuns;+ expect(await handoff()).toMatchObject({ queued: false, reason: 'ci-backlog-policy-disabled' });+ f.apps.get('app1').mergeHandoffMinQueuedRuns = 3;+ const forge = execGhMock.getMockImplementation();+ for (const [backlog, reason] of [[{}, 'ci-backlog-unreadable'], [{ total_count: 2, workflow_runs: [] }, 'ci-backlog-below-threshold']]) {+ execGhMock.mockImplementation(async args => args.some(arg => arg.includes('/actions/runs?')) ? JSON.stringify(backlog) : forge(args));+ expect(await handoff()).toMatchObject({ queued: false, reason });+ }+ expect(pending()).toEqual([]);+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it.each([+ { statusCheckRollup: [{ status: 'COMPLETED', conclusion: 'FAILURE' }] },+ { statusCheckRollup: [] }, { mergeable: 'CONFLICTING' }, { reviewDecision: 'REVIEW_REQUIRED' },+ ])('refuses an unhealthy or unverified current PR despite a repository backlog: %j', async change => {+ Object.assign(f.pr, change);+ expect(await handoff()).toMatchObject({ queued: false, reason: 'pr-not-waiting-on-healthy-ci' });+ expect(pending()).toEqual([]);+ });++ it('requires an available successor and a successfully persisted receipt', async () => {+ const watcher = await import('./prWatcher.js');+ watcher.cancelHandoffFollowUps();+ expect(await handoff()).toMatchObject({ queued: false, reason: 'merge-successor-unavailable' });+ watcher.setHandoffFollowUpGate(async () => null);+ f.queueWriteFailure = true;+ expect(await handoff()).toMatchObject({ queued: false, reason: 'queue-write-failed' });+ expect(pending()).toEqual([]);+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('does not run the immediate receipt pass while paused', async () => {+ const result = await handedOff();+ greenChecks();+ const watcher = await import('./prWatcher.js');+ watcher.setHandoffFollowUpGate(async () => 'paused');+ await watcher.followUpHandoffReceipt('app1', result.receipt.id);+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(pending()).toHaveLength(1);+ });++ it('waits for an active original claim before dispatching CI failure recovery and transfers custody once', async () => {+ await handedOff();+ f.pr.statusCheckRollup = [{ conclusion: 'FAILURE' }];+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ waiting: 1, escalated: 0 });+ expect(followUpMock).not.toHaveBeenCalled();+ f.tasks['task-agent-1'].status = 'completed';+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ escalated: 1 });+ await processPendingMergePrs(f.apps.get('app1'));+ expect(followUpMock).toHaveBeenCalledTimes(1);+ expect(pending()).toEqual([]);+ });++ it('retains a closed unmerged PR instead of dispatching recovery from its stale failed CI', async () => {+ await handedOff();+ f.tasks['task-agent-1'].status = 'completed';+ f.pr.state = 'CLOSED';+ f.pr.statusCheckRollup = [{ conclusion: 'CANCELLED' }];+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()[0].recoveryBlocked).toBe('pr-closed-unmerged');+ expect(followUpMock).not.toHaveBeenCalled();+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('preserves custody through forge outages past the polling budget and recovers when it returns', async () => {+ await handedOff();+ const forge = execGhMock.getMockImplementation();+ execGhMock.mockImplementation(async args => args[0] === 'pr' && args[1] === 'view' ? null : forge(args));+ pending()[0].ticks = 11;+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()[0].attention).toBe('forge-unreadable');+ expect(notifyMock).toHaveBeenCalledWith(expect.objectContaining({+ description: expect.stringContaining('retains its pending-merge receipt and continues checking'),+ }));+ await processPendingMergePrs(f.apps.get('app1'));+ expect(notifyMock).toHaveBeenCalledTimes(1);+ execGhMock.mockImplementation(forge);+ greenChecks();+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 1 });+ expect(pending()).toEqual([]);+ });++ it('names a cleanup recovery owner for a retained merged checkout and confirms cleanup after it finishes', async () => {+ await handedOff();+ f.tasks['task-agent-1'].status = 'completed';+ cleanupMock.mockResolvedValue({ ok: false, reason: 'retirement-submodule-not-uninitialized' });+ greenChecks();+ await processPendingMergePrs(f.apps.get('app1'));+ f.pr.state = 'MERGED';+ pending()[0].cleanup.retryAt = 0;+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()[0].cleanup.recoveryTaskId).toBe('cleanup-recovery');+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({+ description: expect.stringContaining('Prepare retained checkout'),+ context: expect.stringContaining('Do not delete the checkout or refs yourself.'),+ }), 'user');+ f.tasks['cleanup-recovery'] = { id: 'cleanup-recovery', status: 'completed' };+ await processPendingMergePrs(f.apps.get('app1'));+ cleanupMock.mockResolvedValue({ ok: true, branchDeleted: true });+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()).toEqual([]);+ });++ it.each(['retirement-submodule-not-uninitialized', 'active-owner'])(+ 'holds an unresolved completed recovery after one final retirement attempt: %s', async reason => {+ await handedOff();+ f.tasks['task-agent-1'].status = 'completed';+ f.pr.state = 'MERGED';+ cleanupMock.mockResolvedValue({ ok: false, reason: 'retirement-submodule-not-uninitialized' });+ await processPendingMergePrs(f.apps.get('app1'));+ pending()[0].cleanup.retryAt = 0;+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()[0].cleanup.recoveryTaskId).toBe('cleanup-recovery');++ f.tasks['cleanup-recovery'] = { id: 'cleanup-recovery', status: 'completed' };+ await processPendingMergePrs(f.apps.get('app1'));+ cleanupMock.mockResolvedValue({ ok: false, reason });+ await processPendingMergePrs(f.apps.get('app1'));+ expect(pending()[0].cleanup).toMatchObject({+ status: 'held', reason, recoveryTaskId: 'cleanup-recovery', recoveryCompleted: true,+ });++ // Completion is not proof of preservation. Later sweeps keep the same+ // owner and refusal, even when the final attempt found a transient reason.+ for (let sweep = 0; sweep < 2; sweep += 1) {+ pending()[0].cleanup.retryAt = 0;+ await processPendingMergePrs(f.apps.get('app1'));+ }+ expect(pending()).toHaveLength(1);+ expect(pending()[0].cleanup.status).toBe('held');+ expect(cleanupMock).toHaveBeenCalledTimes(2);+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(mergePrMock).not.toHaveBeenCalled();+ },+ );+it('persists the verified binding and merges only that head once a concurrent lease releases, across a restart', async () => {const result = await handedOff();expect(result).toMatchObject({ queued: true, receipt: { appId: 'app1', prNumber: 7, headSha: HEAD, repository: 'github.com/example/repo' } });@@ -188,11 +333,11 @@ describe('pending-merge handoff', () => {expect(await handoff()).toMatchObject({ queued: false, reason: 'review-evidence-incomplete' });});- it('merges at once when CI already settled before the receipt, without waiting for the timer', async () => {+ it('keeps an already-green PR with its original owner for immediate merge', async () => {greenChecks();- expect(await handoff()).toMatchObject({ queued: true });- await vi.waitFor(() => expect(pending()).toEqual([]));- expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD });+ expect(await handoff()).toMatchObject({ queued: false, reason: 'pr-not-waiting-on-healthy-ci' });+ expect(pending()).toEqual([]);+ expect(mergePrMock).not.toHaveBeenCalled();});it.each(['leave-open', 'draft', 'readOnly', 'blocked'])('honors a live coordinator %s hold after CI turns green', async hold => {@@ -249,8 +394,9 @@ describe('pending-merge handoff', () => {expect(Object.keys(f.state.mergeAdmissions)).toHaveLength(0);return { ok: false, reason: 'retirement-forge-unreadable' };});- greenChecks();await handedOff();+ greenChecks();+ await processPendingMergePrs(f.apps.get('app1'));expect(pending()[0]).toMatchObject({ cleanup: { status: 'pending', attempts: 1, reason: 'retirement-forge-unreadable' } });f.pr.state = 'MERGED';await processPendingMergePrs(f.apps.get('app1'));@@ -268,8 +414,9 @@ describe('pending-merge handoff', () => {it.each(['pr-completion-human-handoff', 'retirement-submodule-not-uninitialized'])('holds merged cleanup requiring explicit recovery: %s', async reason => {cleanupMock.mockResolvedValue({ ok: false, reason });- greenChecks();await handedOff();+ greenChecks();+ await processPendingMergePrs(f.apps.get('app1'));expect(pending()[0].cleanup).toMatchObject({ status: 'held', reason });f.pr.state = 'MERGED';pending()[0].cleanup.retryAt = 0;@@ -279,7 +426,6 @@ describe('pending-merge handoff', () => {});it('rechecks the queue after an overlapping sweep that read it before the receipt', async () => {- greenChecks();let releaseRead;const blocked = new Promise((resolve) => { releaseRead = resolve; });const other = { ...f.pr, number: 8, headRefName: 'cos/other', headRefOid: 'b'.repeat(40), statusCheckRollup: [{ status: 'IN_PROGRESS' }] };@@ -294,6 +440,7 @@ describe('pending-merge handoff', () => {// The live module instance, the one the handoff's receipt sweep joins.const timer = (await import('./prWatcher.js')).processPendingMergePrs(f.apps.get('app1'));expect(await handoff()).toMatchObject({ queued: true });+ greenChecks();releaseRead();await timer;await vi.waitFor(() => expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD }));@@ -318,6 +465,7 @@ describe('pending-merge handoff', () => {it('invalidates a binding whose head moved and dispatches the recorded review policy instead of merging', async () => {await handedOff();+ f.tasks['task-agent-1'].status = 'completed';f.pr.headRefOid = 'd'.repeat(40);expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0, escalated: 1, invalidated: 1 });expect(mergePrMock).not.toHaveBeenCalled();@@ -353,7 +501,7 @@ describe('pending-merge handoff', () => {expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0, invalidated: 1 });expect(mergePrMock).not.toHaveBeenCalled();expect(notifyMock).toHaveBeenCalledWith(expect.objectContaining({ link: PR_URL, priority: 'high' }));- expect(pending()).toEqual([]);+ expect(pending()[0].recoveryBlocked).toBe('handoff-binding-unreadable');});});@@ -414,7 +562,7 @@ describe('handoff follow-up poll', () => {it('never arms when the immediate pass already merged', async () => {greenChecks();await handOffPending();- expect(mergePrMock).toHaveBeenCalled();+ expect(mergePrMock).not.toHaveBeenCalled();expect(vi.getTimerCount()).toBe(0);});diff --git a/server/services/git.deleteMergedBranches.test.js b/server/services/git.deleteMergedBranches.test.jsindex a49ff230a1..6f27ea2c2e 100644--- a/server/services/git.deleteMergedBranches.test.js+++ b/server/services/git.deleteMergedBranches.test.js@@ -1,159 +1,171 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-+import { beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('../lib/execGit.js', () => {const execGit = vi.fn();- return {- execGit,- execGitSafe: (...args) => execGit(...args).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message }))- };+ return { execGit, execGitSafe: (...args) => execGit(...args).catch(error => ({ exitCode: 1, stdout: '', stderr: error.message })) };});--vi.mock('./worktreeManager.js', () => ({- isGitLockError: vi.fn(),- listWorktrees: vi.fn().mockResolvedValue([]),- reapMergedWorktrees: vi.fn()-}));-+vi.mock('./worktreeManager.js', () => ({ isGitLockError: vi.fn(), listWorktrees: vi.fn(async () => []) }));+vi.mock('./branchReconcile.js', () => ({ cleanupMerged: vi.fn() }));+vi.mock('./cosClaimOwnershipState.js', () => ({ withClaimOwnershipLock: work => work(), readClaimOwnershipAgents: vi.fn(async () => []) }));+vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: vi.fn(async () => null) }));import { execGit } from '../lib/execGit.js';-import { listWorktrees, reapMergedWorktrees } from './worktreeManager.js';-import { deleteMergedBranches } from './git.js';--const result = (stdout = '', exitCode = 0, stderr = '') => ({ stdout, stderr, exitCode });-+import { cleanupMerged } from './branchReconcile.js';+import { readClaimOwnershipAgents } from './cosClaimOwnershipState.js';+import { readBranchCompletionHold } from './branchCompletionPolicy.js';+import { listWorktrees } from './worktreeManager.js';+import { deleteMergedBranches, deleteMergedRemoteBranches } from './git.js';+const HEAD = 'a'.repeat(40);+const REMOTE = 'https://example.com/team/repo.git';+const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });+let local, remote, fetchFailed, moved, held, fetchEndpoints, pushEndpoints;beforeEach(() => {- listWorktrees.mockResolvedValue([{ branch: 'refs/heads/feature/locked' }]);- reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [], defaultBranch: 'main' });- execGit.mockImplementation((args) => {- if (args[0] === 'symbolic-ref') return Promise.resolve(result('origin/main\n'));- if (args[0] === 'rev-parse' && args.includes('--verify')) return Promise.resolve(result('abc123\n'));- if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return Promise.resolve(result('main\n'));- if (args[0] === 'branch' && args.includes('--list')) return Promise.resolve(result(' main\n feature/locked\n feature/free\n'));- if (args[0] === 'branch' && args.includes('-r') && args.includes('--merged')) return Promise.resolve(result(''));- if (args[0] === 'branch' && args.includes('--merged')) {- return Promise.resolve(result('main\nfeature/locked\nfeature/free\n'));- }- if (args[0] === 'fetch') return Promise.resolve(result());- if (args[0] === 'branch' && args[1] === '-d') return Promise.resolve(result());- return Promise.resolve(result());- });-});--afterEach(() => {vi.clearAllMocks();+ local = ['main', 'release', 'feature/done']; remote = ['origin/feature/done']; fetchFailed = moved = false; held = null;+ fetchEndpoints = pushEndpoints = [REMOTE];+ listWorktrees.mockResolvedValue([]);+ readClaimOwnershipAgents.mockResolvedValue([]);+ readBranchCompletionHold.mockResolvedValue(null);+ cleanupMerged.mockImplementation(async (_dir, _target, [{ branch }]) => held+ ? { cleaned: [], skipped: [{ branch, reason: held }] } : { cleaned: [branch], skipped: [] });+ execGit.mockImplementation(async args => {+ if (args[0] === 'remote') return ok((args.includes('--push') ? pushEndpoints : fetchEndpoints).join('\n'));+ if (args[0] === 'symbolic-ref') return ok('origin/main\n');+ if (args[0] === 'rev-parse') return ok(HEAD);+ if (args[0] === 'branch' && args.includes('--list')) return ok(local.join('\n'));+ if (args[0] === 'branch') return ok((args.includes('-r') ? remote : local).join('\n'));+ if (args[0] === 'fetch') return { ...ok(), exitCode: fetchFailed ? 1 : 0 };+ if (args[0] === 'ls-remote' && args.includes('--symref')) return ok(`ref: refs/heads/main\tHEAD\n${HEAD}\tHEAD\n`);+ if (args[0] === 'ls-remote') return ok(`${HEAD}\t${args.at(-1)}\n`);+ if (args[0] === 'push') return { ...ok(), exitCode: moved ? 1 : 0 };+ return ok();+ });});--describe('deleteMergedBranches', () => {- it('reports merged branches the reaper refused, while deleting eligible locals', async () => {- reapMergedWorktrees.mockResolvedValue({- reaped: [],- skipped: [{ path: '/wt/locked', branch: 'feature/locked', reason: 'uncommitted' }]- });-- const cleanup = await deleteMergedBranches('/repo');-- expect(cleanup.deleted).toEqual([{ name: 'feature/free', local: 'deleted', remote: null }]);- // The reaper's reason is what tells the user why the branch survived — the- // generic "it's in a worktree" wording is now only the unknown-reason fallback.- expect(cleanup.skipped).toEqual(['feature/locked (local: worktree has uncommitted changes)']);- expect(execGit).toHaveBeenCalledWith(['branch', '-D', 'feature/free'], '/repo', { ignoreExitCode: true });- expect(execGit).not.toHaveBeenCalledWith(['branch', '-D', 'feature/locked'], '/repo', { ignoreExitCode: true });+describe('delete merged branches', () => {+ it('shares local retirement and leases the merged remote head', async () => {+ const result = await deleteMergedBranches('/repo');+ expect(result.deleted).toEqual([{ name: 'feature/done', local: 'deleted', remote: 'deleted' }]);+ expect(cleanupMerged).toHaveBeenCalledWith('/repo', HEAD, [{ branch: 'feature/done' }], { activeAgentIds: null });+ expect(execGit).toHaveBeenCalledWith(['push', `--force-with-lease=refs/heads/feature/done:${HEAD}`, '--', REMOTE, ':refs/heads/feature/done'], '/repo', { ignoreExitCode: true });+ expect(readBranchCompletionHold).toHaveBeenCalledWith({ repoPath: '/repo', branch: 'feature/done', tip: HEAD, retirement: true });});-- it('deletes branches proven merged into the default when the app checkout is elsewhere', async () => {- execGit.mockImplementation((args) => {- if (args[0] === 'symbolic-ref') return Promise.resolve(result('origin/main\n'));- if (args[0] === 'rev-parse' && args.includes('--verify')) return Promise.resolve(result('abc123\n'));- if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return Promise.resolve(result('develop\n'));- if (args[0] === 'branch' && args.includes('--list')) return Promise.resolve(result(' develop\n main\n feature/merged\n'));- if (args[0] === 'branch' && args.includes('-r') && args.includes('--merged')) return Promise.resolve(result(''));- if (args[0] === 'branch' && args.includes('--merged')) {- return Promise.resolve(result('main\nfeature/merged\n'));- }- if (args[0] === 'branch' && args[1] === '-d') {- return Promise.resolve(result('', 1, 'error: branch is not fully merged into the current checkout'));- }- return Promise.resolve(result());- });-- const cleanup = await deleteMergedBranches('/repo');-- expect(cleanup.deleted).toEqual([{ name: 'feature/merged', local: 'deleted', remote: null }]);- expect(execGit).toHaveBeenCalledWith(['branch', '-D', 'feature/merged'], '/repo', { ignoreExitCode: true });- expect(execGit).not.toHaveBeenCalledWith(['branch', '-d', 'feature/merged'], '/repo', { ignoreExitCode: true });+ it.each(['archive-failed', 'worktree-locked', 'worktree-dirty', 'claim-owner-active'])('retains both refs on %s', async reason => {+ held = reason;+ const result = await deleteMergedBranches('/repo');+ expect(result.deleted).toEqual([]);+ expect(result.skipped.join(' ')).toMatch(/archive|locked|dirty|active/);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);});-- it('reports a worktree-held branch generically when the reaper named no reason', async () => {- const cleanup = await deleteMergedBranches('/repo');-- expect(cleanup.skipped).toEqual(['feature/locked (local: checked out in a worktree)']);+ it('does not use stale merge flags when refresh fails', async () => {+ fetchFailed = true;+ expect((await deleteMergedBranches('/repo')).skipped).toEqual(['cleanup (remote default could not be refreshed)']);+ expect(cleanupMerged).not.toHaveBeenCalled();});-- it('counts a reaped worktree branch as deleted and folds its remote half into one row', async () => {- reapMergedWorktrees.mockResolvedValue({- reaped: [{ path: '/wt/reaped', branch: 'feature/reaped', locked: false, branchDeleted: true }],- skipped: []- });- execGit.mockImplementation((args) => {- if (args[0] === 'symbolic-ref') return Promise.resolve(result('origin/main\n'));- if (args[0] === 'rev-parse' && args.includes('--verify')) return Promise.resolve(result('abc123\n'));- if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return Promise.resolve(result('main\n'));- if (args[0] === 'branch' && args.includes('--list')) return Promise.resolve(result(' main\n'));- if (args[0] === 'branch' && args.includes('-r') && args.includes('--merged')) {- return Promise.resolve(result('origin/main\norigin/feature/reaped\n'));- }- if (args[0] === 'branch' && args.includes('--merged')) return Promise.resolve(result('main\n'));- return Promise.resolve(result());- });-- const cleanup = await deleteMergedBranches('/repo');-- expect(cleanup.deleted).toEqual([- { name: 'feature/reaped', local: 'deleted', remote: 'deleted', worktree: 'removed' }- ]);- // The reap already deleted the local branch — re-running branch deletion- // would only produce a spurious "not found" skip.- expect(execGit).not.toHaveBeenCalledWith(['branch', '-D', 'feature/reaped'], '/repo', { ignoreExitCode: true });- expect(execGit).toHaveBeenCalledWith(['push', 'origin', '--delete', 'feature/reaped'], '/repo', { ignoreExitCode: true });+ it.each(['changed', 'missing', 'unreadable'])('holds stale or unverifiable remote defaults (%s) before any mutation', async mode => {+ const exec = execGit.getMockImplementation();+ execGit.mockImplementation(args => args[0] === 'ls-remote' && args.includes('--symref')+ ? Promise.resolve(mode === 'changed' ? ok(`ref: refs/heads/trunk\tHEAD\n${HEAD}\tHEAD\n`)+ : mode === 'missing' ? ok(`${HEAD}\tHEAD\n`) : { ...ok(), exitCode: 128 }) : exec(args));+ const reason = mode === 'changed' ? 'default-branch-changed' : 'default-branch-unverified';+ expect(await deleteMergedBranches('/repo')).toMatchObject({ deleted: [], skipped: [`cleanup (${reason})`] });+ expect(await deleteMergedRemoteBranches('/repo', ['trunk'], { defaultBranch: 'main' })).toEqual({ deleted: [], skipped: [{ branch: 'trunk', reason }] });+ expect(cleanupMerged).not.toHaveBeenCalled();+ expect(execGit.mock.calls.some(([args]) => ['fetch', 'push'].includes(args[0]))).toBe(false);+ expect(execGit).toHaveBeenCalledWith(['ls-remote', '--symref', '--', REMOTE, 'HEAD'], '/repo');});-- it('hands the reaper the protected branches, agent ids and default branch, and skips its own fetch', async () => {- const excludeBranches = new Set(['feature/agent-work']);- const activeAgentIds = new Set(['agent-1']);-- await deleteMergedBranches('/repo', { excludeBranches, activeAgentIds });-- expect(reapMergedWorktrees).toHaveBeenCalledWith('/repo', {- activeAgentIds,- excludeBranches,- includeUnmanagedTrees: true,- // Passed so the reap skips its own lookup, which can stall on `remote set-head`.- defaultBranch: 'main'+ it('reports a remote ref that advances after evidence was read', async () => {+ moved = true;+ const result = await deleteMergedBranches('/repo');+ expect(result.deleted[0]).toMatchObject({ local: 'deleted', remote: 'failed' });+ expect(result.skipped).toContain('feature/done (remote: head changed or deletion failed)');+ });+ it('sends squash-merged candidates to the shared evidence gate', async () => {+ remote = []; local.push('feature/squashed');+ await deleteMergedBranches('/repo');+ expect(cleanupMerged).toHaveBeenCalledWith('/repo', HEAD, [{ branch: 'feature/squashed' }], expect.any(Object));+ });+ it('includes remote-only squash candidates instead of relying on ancestry listing', async () => {+ local = ['main'];+ expect((await deleteMergedBranches('/repo')).deleted).toEqual([{ name: 'feature/done', local: null, remote: 'deleted' }]);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'branch' && args.includes('--merged'))).toBe(false);+ });+ it('holds active exclusions and unreadable remote ownership', async () => {+ const excluded = await deleteMergedBranches('/repo', { excludeBranches: async () => new Set(['feature/done']) });+ expect(excluded.skipped).toEqual(['feature/done (used by an active agent)']);+ expect(cleanupMerged).not.toHaveBeenCalled();+ readClaimOwnershipAgents.mockResolvedValue(null);+ const unknown = await deleteMergedBranches('/repo');+ expect(unknown.skipped.join(' ')).toContain('ownership');+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+ it.each(['different', 'multiple', 'missing'])('retains every ref when push endpoint is %s', async mode => {+ pushEndpoints = mode === 'different' ? ['https://example.com/fork/repo.git']+ : mode === 'multiple' ? [REMOTE, 'https://example.com/mirror/repo.git'] : [];+ const result = await deleteMergedBranches('/repo');+ expect(result.deleted).toEqual([]);+ expect(result.skipped).toEqual(['cleanup (fetch and push must identify one identical remote endpoint)']);+ expect(cleanupMerged).not.toHaveBeenCalled();+ expect(execGit.mock.calls.some(([args]) => ['fetch', 'push'].includes(args[0]))).toBe(false);+ });+ it('keeps reads, merge proof and writes bound when origin changes during retirement', async () => {+ cleanupMerged.mockImplementation(async (_dir, _target, [{ branch }]) => {+ fetchEndpoints = pushEndpoints = ['https://example.com/other/repo.git'];+ return { cleaned: [branch], skipped: [] };});- // reapMergedWorktrees fetches --prune itself; a second round-trip is waste.- expect(execGit).not.toHaveBeenCalledWith(['fetch', 'origin', '--prune'], '/repo', { ignoreExitCode: true });+ const result = await deleteMergedBranches('/repo');+ expect(result.deleted[0].remote).toBe('deleted');+ for (const [args] of execGit.mock.calls.filter(([args]) => ['fetch', 'ls-remote', 'push'].includes(args[0]))) {+ expect(args).toContain(REMOTE);+ expect(args).not.toContain('origin');+ expect(args).not.toContain(fetchEndpoints[0]);+ }});+});- it('retries the branch delete when the reap removed the tree but not the branch', async () => {- reapMergedWorktrees.mockResolvedValue({- reaped: [{ path: '/wt/locked', branch: 'feature/locked', locked: false, branchDeleted: false }],- skipped: []+describe('selected remote retirement', () => {+ const retire = () => deleteMergedRemoteBranches('/repo', ['feature/done'], { defaultBranch: 'main' });+ it('only retires the selected ref and never performs local cleanup', async () => {+ const result = await retire();+ expect(result).toEqual({ deleted: ['feature/done'], skipped: [] });+ expect(cleanupMerged).not.toHaveBeenCalled();+ const pushes = execGit.mock.calls.filter(([args]) => args[0] === 'push');+ expect(pushes).toHaveLength(1);+ expect(pushes[0][0]).toEqual(['push', `--force-with-lease=refs/heads/feature/done:${HEAD}`, '--', REMOTE, ':refs/heads/feature/done']);+ });+ it.each(['local ref', 'tracking alias', 'holder', 'unknown holders'])('retains a recovery ref with %s', async kind => {+ const exec = execGit.getMockImplementation();+ if (kind === 'holder') listWorktrees.mockResolvedValue([{ path: '/new', branch: 'refs/heads/feature/done' }]);+ else if (kind === 'unknown holders') listWorktrees.mockRejectedValue(new Error('unreadable'));+ else execGit.mockImplementation(args => args[0] === 'for-each-ref'+ ? Promise.resolve(ok(kind === 'local ref' ? 'feature/done\t' : 'different-name\torigin/feature/done')) : exec(args));+ const result = await retire();+ expect(result.deleted).toEqual([]);+ expect(result.skipped[0].reason).toMatch(/local|worktree/);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+ it('rechecks local ownership after merge proof', async () => {+ const exec = execGit.getMockImplementation();+ let added = false;+ execGit.mockImplementation(args => {+ if (args[0] === 'merge-base') added = true;+ if (args[0] === 'for-each-ref' && added) return Promise.resolve(ok('new-local\torigin/feature/done'));+ return exec(args);});-- const cleanup = await deleteMergedBranches('/repo');-- // The worktree hold is gone with the tree, so the branch is an ordinary- // target again rather than being reported as still checked out.- expect(execGit).toHaveBeenCalledWith(['branch', '-D', 'feature/locked'], '/repo', { ignoreExitCode: true });- expect(cleanup.deleted).toContainEqual({ name: 'feature/locked', local: 'deleted', remote: null });- expect(cleanup.skipped).toEqual([]);+ expect((await retire()).skipped).toEqual([{ branch: 'feature/done', reason: 'local branch or upstream still exists' }]);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);});-- it('falls back to branch-only cleanup when the reap throws', async () => {- reapMergedWorktrees.mockRejectedValue(new Error('worktree list failed'));-- const cleanup = await deleteMergedBranches('/repo');-- expect(cleanup.deleted).toEqual([{ name: 'feature/free', local: 'deleted', remote: null }]);- expect(execGit).toHaveBeenCalledWith(['fetch', 'origin', '--prune'], '/repo', { ignoreExitCode: true });+ it('holds a reopened or incomplete workflow at the remote boundary', async () => {+ readBranchCompletionHold.mockResolvedValue('completion-pending');+ expect((await retire()).skipped).toEqual([{ branch: 'feature/done', reason: 'completion-pending' }]);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+ it('does not retire protected refs supplied by a caller', async () => {+ expect((await deleteMergedRemoteBranches('/repo', ['main', 'release'], { defaultBranch: 'main' })).deleted).toEqual([]);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+ it('fails closed when the current remote head is no longer merged', async () => {+ const exec = execGit.getMockImplementation();+ execGit.mockImplementation(args => ['merge-base', 'cherry'].includes(args[0])+ ? Promise.resolve({ ...ok(), exitCode: 1 }) : exec(args));+ expect((await retire()).skipped).toEqual([{ branch: 'feature/done', reason: 'current head is not merged' }]);+ expect(execGit.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);});});diff --git a/server/services/git.js b/server/services/git.jsindex 154a72daf8..a3226aac7a 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1449,7 +1449,9 @@ export async function mergeBranch(dir, branchName) {* @returns {Promise<boolean>}*/export async function hasBranchMergeEvidence(dir, branch, target) {- if (!branch || !target || branch === target) return false;+ // Equal immutable commits prove inclusion; equal symbolic branch names do+ // not prove that a feature branch landed anywhere else.+ if (!branch || !target || (branch === target && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(branch))) return false;const resolve = (ref) => execGit(['rev-parse', '--verify', `${ref}^{commit}`], dir, { ignoreExitCode: true }).then(r => (r.exitCode === 0 ? r.stdout.trim() : null))@@ -1734,22 +1736,123 @@ const WORKTREE_HOLD_REASONS = {'worktree-human-claim': 'worktree is a claimed session','remove-failed': 'worktree removal failed and the checkout is still present'};-const worktreeHoldReason = (reason) => WORKTREE_HOLD_REASONS[reason] || 'checked out in a worktree';+const worktreeHoldReason = (reason) => WORKTREE_HOLD_REASONS[reason] || reason || 'checked out in a worktree';++async function prepareRemoteRetirement(dir, defaultBranch) {+ // A remote name resolves differently for fetch and push (and can change+ // while cleanup awaits). Require one identical endpoint and use its captured+ // URL for every read/write. Equivalent-looking aliases need explicit review.+ const [fetchUrls, pushUrls] = await Promise.all([+ execGitSafe(['remote', 'get-url', '--all', 'origin'], dir),+ execGitSafe(['remote', 'get-url', '--push', '--all', 'origin'], dir),+ ]);+ const fetchEndpoints = fetchUrls.stdout.trim().split(/\r?\n/).filter(Boolean);+ const pushEndpoints = pushUrls.stdout.trim().split(/\r?\n/).filter(Boolean);+ if (fetchUrls.exitCode !== 0 || pushUrls.exitCode !== 0+ || fetchEndpoints.length !== 1 || pushEndpoints.length !== 1+ || fetchEndpoints[0] !== pushEndpoints[0]) {+ return { reason: 'fetch and push must identify one identical remote endpoint' };+ }+ const remoteUrl = fetchEndpoints[0];+ // origin/HEAD and a caller's remembered default can outlive a forge default+ // change. Establish the advertised default before any refresh or retirement.+ const advertised = await execGitSafe(['ls-remote', '--symref', '--', remoteUrl, 'HEAD'], dir);+ const symrefs = advertised.stdout.split(/\r?\n/).filter(line => line.startsWith('ref: '));+ const defaultMatch = symrefs.length === 1 ? /^ref: (refs\/heads\/.+)\tHEAD$/.exec(symrefs[0]) : null;+ if (advertised.exitCode !== 0 || !defaultMatch) return { reason: 'default-branch-unverified' };+ if (defaultMatch[1] !== `refs/heads/${defaultBranch}`) return { reason: 'default-branch-changed' };+ // A stale local default or an unsuccessful fetch never authorizes deletion.+ const fetched = await execGitSafe(['fetch', '--prune', '--', remoteUrl, '+refs/heads/*:refs/remotes/origin/*'], dir, { ignoreExitCode: true });+ if (fetched.exitCode !== 0) return { reason: 'remote default could not be refreshed' };+ const targetRef = `refs/heads/${defaultBranch}`;+ const targetHead = await execGitSafe(['ls-remote', '--heads', '--', remoteUrl, targetRef], dir);+ const targetMatch = /^([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/.exec(targetHead.stdout.trim());+ const targetSha = targetMatch?.[1];+ if (targetHead.exitCode !== 0 || targetMatch?.[2] !== targetRef+ || (await execGitSafe(['rev-parse', '--verify', `${targetSha}^{commit}`], dir)).exitCode !== 0) {+ return { reason: 'remote default head unavailable' };+ }+ return { remoteUrl, targetSha, defaultBranch };+}++// Fresh local refs, upstream aliases and actual holders all retain the remote+// recovery ref. Re-read immediately before the leased push, inside the same+// ownership fence used to register managed claims.+async function remoteRetirementLocalHold(dir, name) {+ const [refs, trees] = await Promise.all([+ execGitSafe(['for-each-ref', '--format=%(refname:short)%09%(upstream:short)', 'refs/heads/'], dir),+ listWorktrees(dir).catch(() => null),+ ]);+ if (refs.exitCode !== 0 || !Array.isArray(trees)) return 'local ownership unavailable';+ if (refs.stdout.split(/\r?\n/).some(line => {+ const [branch, upstream] = line.split('\t');+ return branch === name || upstream === `origin/${name}`;+ })) return 'local branch or upstream still exists';+ if (trees.some(tree => tree.branch === `refs/heads/${name}` || tree.branch === name)) return 'checked out in a worktree';+ return null;+}++async function retireMergedRemoteHead(dir, name, context, { excludeBranches } = {}) {+ const { withClaimOwnershipLock, readClaimOwnershipAgents } = await import('./cosClaimOwnershipState.js');+ const { claimCheckoutOwnerReason } = await import('../lib/claimContinuation.js');+ const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');+ if (PROTECTED_BRANCHES.includes(name) || name === context.defaultBranch || name === 'HEAD') return { reason: 'protected branch' };+ const ref = `refs/heads/${name}`;+ if ((await execGitSafe(['check-ref-format', ref], dir)).exitCode !== 0) return { reason: 'invalid branch name' };+ return withClaimOwnershipLock(async () => {+ const hold = async tip => {+ const exclusions = typeof excludeBranches === 'function' ? await excludeBranches() : excludeBranches;+ if (exclusions?.has(name)) return 'used by an active agent';+ const agents = await readClaimOwnershipAgents();+ const owner = claimCheckoutOwnerReason({ branchName: name, holderPath: null, sourceWorkspace: dir, agents });+ if (owner) return owner;+ if (tip) {+ const policy = await readBranchCompletionHold({ repoPath: dir, branch: name, tip, retirement: true });+ if (policy) return policy;+ }+ return remoteRetirementLocalHold(dir, name);+ };+ const initialHold = await hold();+ if (initialHold) return { reason: initialHold };+ const head = await execGitSafe(['ls-remote', '--heads', '--', context.remoteUrl, ref], dir);+ const match = /^([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/.exec(head.stdout.trim());+ if (head.exitCode !== 0 || !match || match[2] !== ref) return { reason: 'head unavailable or already removed' };+ if (!await hasBranchMergeEvidence(dir, match[1], context.targetSha)) return { reason: 'current head is not merged' };+ const finalHold = await hold(match[1]);+ if (finalHold) return { reason: finalHold };+ const removed = await execGitSafe(['push', `--force-with-lease=${ref}:${match[1]}`, '--', context.remoteUrl, `:${ref}`], dir, { ignoreExitCode: true });+ return removed.exitCode === 0 ? { deleted: true } : { reason: 'head changed or deletion failed', failed: true };+ });+}++/** Retire only explicitly selected remote candidates, preserving any fresh local+ * ownership. The candidate scan grants no deletion authority: endpoint, default,+ * current head, merge proof and claim/completion gates are established here.+ */+export async function deleteMergedRemoteBranches(dir, names, { defaultBranch, excludeBranches } = {}) {+ const selected = [...new Set(names)];+ if (!selected.length) return { deleted: [], skipped: [] };+ const base = defaultBranch || (await getRepoBranches(dir)).baseBranch || 'main';+ const context = await prepareRemoteRetirement(dir, base);+ if (context.reason) return { deleted: [], skipped: selected.map(branch => ({ branch, reason: context.reason })) };+ const deleted = [];+ const skipped = [];+ for (const branch of selected) {+ const result = await retireMergedRemoteHead(dir, branch, context, { excludeBranches });+ if (result.deleted) deleted.push(branch);+ else skipped.push({ branch, reason: result.reason });+ }+ return { deleted, skipped };+}/*** Delete all merged branches (local and remote) in one operation.* Skips the `PROTECTED_BRANCHES` set (see `../lib/gitArgs.js`), the current branch,* and any explicitly excluded branches.*- * A merged branch checked out in a WORKTREE is no longer reported-and-left: the- * worktree is reaped first (`reapMergedWorktrees`, which removes the tree and the- * branch together) so the "Clean N merged" affordance actually clears instead of- * offering the same branch on every visit. That reap refuses anything it cannot- * prove disposable — an uncommitted tree, a branch not fully in- * `origin/<default>` (which is also what rules out losing unpushed work: every- * commit on a reaped branch is already on the remote), a locked tree, a live- * agent's tree, or a human `/claim` session. Those come back in `skipped` with- * the reason, so the UI can say why one survived.+ * Shares the reconciler's fresh ownership, merge, archival and retirement gates.+ * Local and remote deletion are pinned to observed heads. Retained work is+ * returned with its specific reason; the UI's merged flag is never authority.** @param {string} dir - Working directory* @param {object} options@@ -1759,104 +1862,47 @@ const worktreeHoldReason = (reason) => WORKTREE_HOLD_REASONS[reason] || 'checked* @returns {Promise<{deleted: Array<{name: string, local: string, remote: string, worktree?: string}>, skipped: string[], defaultBranch: string}>}*/export async function deleteMergedBranches(dir, { excludeBranches, activeAgentIds = null } = {}) {- const [{ baseBranch }, currentBranch, worktreeBranches] = await Promise.all([- getRepoBranches(dir),- getBranch(dir),- getWorktreeBranches(dir)- ]);+ const { cleanupMerged } = await import('./branchReconcile.js');+ const { baseBranch } = await getRepoBranches(dir);const defaultBranch = baseBranch || 'main';- const protectedSet = new Set(PROTECTED_BRANCHES);- if (baseBranch) protectedSet.add(baseBranch);-- // Worktree and agent branches are only protected from local deletion. Read- // BEFORE the reap and corrected below, so nothing the reap freed stays behind- // a hold that no longer exists.- const localOnlyProtected = new Set([...worktreeBranches]);- if (excludeBranches) {- for (const b of excludeBranches) localOnlyProtected.add(b);- }-- // Ahead of the merged-branch listing, so a reaped branch reads as an ordinary- // already-deleted local rather than as a worktree-held skip. `defaultBranch` is- // handed over because the reap's own lookup can fall back to a `remote set-head`- // probe, which is a 5s stall on this request path.- const reap = await reapMergedWorktrees(dir, {- activeAgentIds, excludeBranches, includeUnmanagedTrees: true, defaultBranch- }).catch(err => {- console.error(`❌ Worktree reap failed during merged-branch cleanup: ${err.message}`);- return null;- });- // Whatever the reap removed no longer has a worktree holding it, so drop the- // hold: a branch whose tree went but whose delete failed falls through to the- // ordinary `branch -d` pass below, which reports its own outcome.- for (const entry of reap?.reaped || []) localOnlyProtected.delete(entry.branch);- const reapedBranches = (reap?.reaped || []).filter(entry => entry.branch && entry.branchDeleted).map(entry => entry.branch);- const reapHolds = new Map((reap?.skipped || []).filter(entry => entry.branch).map(entry => [entry.branch, entry.reason]));-- // The reap already fetched --prune; a second round-trip would change nothing.- if (!reap) await execGitSafe(['fetch', 'origin', '--prune'], dir, { ignoreExitCode: true });-- const [localMergedNames, remoteMerged] = await Promise.all([- getLocalMergedBranchNames(dir, defaultBranch),- execGit(['branch', '-r', '--merged', `origin/${defaultBranch}`, '--format=%(refname:short)'], dir, { ignoreExitCode: true })- ]);-- const mergedLocalCandidates = [...localMergedNames]- .filter(name => !protectedSet.has(name));- const mergedLocalNames = mergedLocalCandidates- .filter(name => !localOnlyProtected.has(name) && name !== currentBranch);-- const mergedRemoteNames = remoteMerged.stdout.trim().split('\n').filter(Boolean)- .filter(ref => ref.startsWith('origin/'))- .map(ref => ref.replace(/^origin\//, ''))- .filter(name => !protectedSet.has(name) && name !== 'HEAD');-- const allMerged = [...new Set([...mergedLocalNames, ...mergedRemoteNames])];- const localSet = new Set(mergedLocalNames);- const remoteSet = new Set(mergedRemoteNames);-- // One record per branch, so a branch whose local half the reap already deleted- // and whose remote half is deleted below reports as a single row.- const records = new Map(reapedBranches.map(name => [name, { name, local: 'deleted', remote: null, worktree: 'removed' }]));- const skipped = mergedLocalCandidates- .filter(name => localOnlyProtected.has(name) || name === currentBranch)- .map(name => {- const reason = name === currentBranch- ? 'currently checked out'- : excludeBranches?.has(name)- ? 'used by an active agent'- : worktreeHoldReason(reapHolds.get(name));- return `${name} (local: ${reason})`;- });- const opts = { ignoreExitCode: true };-- for (const name of allMerged) {- const hasLocal = localSet.has(name);- const hasRemote = remoteSet.has(name);- const result = records.get(name) || { name, local: null, remote: null };- records.set(name, result);-- if (hasLocal) {- // `mergedLocalNames` was computed against the default branch above. Git's- // `branch -d` checks the current checkout (or the branch's upstream), which- // can differ when the app repo is currently on another branch; that would- // reject a branch this cleanup has already proved merged. Force-delete is- // safe here because worktree/current/agent-held names were filtered out.- const r = await execGitSafe(['branch', '-D', name], dir, opts);- result.local = r.exitCode === 0 ? 'deleted' : 'failed';- if (r.exitCode !== 0) skipped.push(`${name} (local: ${r.stderr?.trim()})`);+ const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);+ const skipped = [];+ const records = new Map();+ const context = await prepareRemoteRetirement(dir, defaultBranch);+ if (context.reason) return { deleted: [], skipped: [`cleanup (${context.reason})`], defaultBranch };+ const { targetSha } = context;+ const branches = await execGitSafe(['branch', '--format=%(refname:short)'], dir, { ignoreExitCode: true });+ if (branches.exitCode !== 0) return { deleted: [], skipped: ['cleanup (local branches unavailable)'], defaultBranch };+ const local = new Set(branches.stdout.trim().split('\n').filter(Boolean));+ const remote = await execGitSafe(['branch', '-r', '--format=%(refname:short)'], dir, { ignoreExitCode: true });+ if (remote.exitCode !== 0) return { deleted: [], skipped: ['cleanup (remote merge evidence unavailable)'], defaultBranch };+ const remoteNames = remote.stdout.trim().split('\n').filter(ref => ref.startsWith('origin/')).map(ref => ref.slice(7));+ const names = new Set([...local, ...remoteNames]);+ for (const name of names) {+ if (protectedSet.has(name) || name === 'HEAD') continue;+ const exclusions = typeof excludeBranches === 'function' ? await excludeBranches() : excludeBranches;+ if (exclusions?.has(name)) { skipped.push(`${name} (used by an active agent)`); continue; }+ const record = { name, local: null, remote: null };+ records.set(name, record);+ if (local.has(name)) {+ const retired = await cleanupMerged(dir, targetSha, [{ branch: name }], { activeAgentIds });+ if (retired.cleaned.includes(name)) record.local = 'deleted';+ else {+ for (const hold of retired.skipped) skipped.push(`${name} (local: ${worktreeHoldReason(hold.reason)}${hold.detail ? `: ${hold.detail}` : ''})`);+ // Retention is a whole-branch outcome. In particular, archive failure+ // must leave both the checkout and its remote recovery ref intact.+ continue;+ }}-- if (hasRemote) {- const r = await execGitSafe(['push', 'origin', '--delete', name], dir, opts);- result.remote = r.exitCode === 0 ? 'deleted' : 'failed';- if (r.exitCode !== 0) skipped.push(`${name} (remote: ${r.stderr?.trim()})`);+ if (!remoteNames.includes(name)) continue;+ const removed = await retireMergedRemoteHead(dir, name, context, { excludeBranches });+ if (removed.deleted) record.remote = 'deleted';+ else {+ if (removed.failed) record.remote = 'failed';+ skipped.push(`${name} (remote: ${removed.reason})`);}}-- const deleted = [...records.values()].filter(r => r.local === 'deleted' || r.remote === 'deleted');-- return { deleted, skipped, defaultBranch };+ return { deleted: [...records.values()].filter(row => row.local === 'deleted' || row.remote === 'deleted'), skipped, defaultBranch };}/**diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.jsindex 941610a541..bb3bc7a141 100644--- a/server/services/heldCheckoutRecovery.js+++ b/server/services/heldCheckoutRecovery.js@@ -18,16 +18,16 @@* failure leaves the checkout, its lock and its branch exactly as found.*/-import { createReadStream } from 'node:fs';-import { lstat, readlink, readdir, chmod } from 'node:fs/promises';-import { createHash } from 'node:crypto';-import { dirname, join } from 'node:path';+import { createReadStream, realpathSync } from 'node:fs';+import { lstat, stat, readlink, readdir, readFile, chmod } from 'node:fs/promises';+import { createHash, randomUUID } from 'node:crypto';+import { basename, dirname, join, resolve } from 'node:path';import { atomicWrite, copyFileGuarded, ensureDir, PATHS, rmGuarded, sha256File, writeFileGuarded } from '../lib/fileUtils.js';import { execGit } from '../lib/execGit.js';import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';import { claimCheckoutOwnerReason } from '../lib/claimContinuation.js';import { backupSlug } from './supersededBackup.js';-import { listWorktrees, forceRemoveWorktreeDir } from './worktreeManager.js';+import { listWorktrees, forceRemoveWorktreeDir, deleteCompletedLocalBranch } from './worktreeManager.js';import { getDefaultBranch, hasBranchMergeEvidence } from './git.js';import { withClaimOwnershipLock, readClaimOwnershipAgents } from './cosClaimOwnership.js';@@ -48,8 +48,8 @@ const git = (args, cwd) => execGit(args, cwd, { maxBuffer: GIT_OUTPUT_BYTES }).t/** Preserve worktree-private Git evidence, never follow its links into the* common repository. The lock is archived but matched separately by release.*/-async function snapshotAdministration(path) {- const root = (await git(['rev-parse', '--absolute-git-dir'], path)).trim();+async function snapshotAdministration(path, missingRoot = null) {+ const root = missingRoot || (await git(['rev-parse', '--absolute-git-dir'], path)).trim();const files = [];const symlinks = [];let bytes = 0;@@ -65,8 +65,10 @@ async function snapshotAdministration(path) {};await visit(root, 'gitdir');const pointer = join(path, '.git');- if (!(await lstat(pointer)).isFile()) throw new Error('checkout git indirection is not a file');- await visit(pointer, 'git-indirection');+ if (!missingRoot) {+ if (!(await lstat(pointer)).isFile()) throw new Error('checkout git indirection is not a file');+ await visit(pointer, 'git-indirection');+ }const fingerprint = createHash('sha256').update(JSON.stringify({files: files.filter(file => file.path !== 'gitdir/locked').map(({ source: _source, ...file }) => file), symlinks,})).digest('hex');@@ -193,7 +195,7 @@ async function snapshotContent(path) {*/async function archiveCheckout(input) {const stamp = new Date().toISOString().replace(/[:.]/g, '-');- const dir = join(heldCheckoutArchiveRoot(input.cosDir), `${backupSlug(input.branch || `detached-${input.tree.head}`)}-${stamp}`);+ const dir = join(heldCheckoutArchiveRoot(input.cosDir), `${backupSlug(input.branch || `detached-${input.tree.head}`)}-${stamp}-${randomUUID()}`);// An incomplete archive must not read as a restore point.return writeArchive(dir, input).catch(async (error) => {await rmGuarded(dir, { recursive: true, force: true }).catch(() => {});@@ -201,17 +203,127 @@ async function archiveCheckout(input) {});}-async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, release, review }) {- const [snapshot, administration] = await Promise.all([snapshotContent(tree.path), snapshotAdministration(tree.path)]);+// A missing tail has no filesystem identity yet. Match its exact spelling under+// the deepest existing directory's identity, so Git's expanded Windows 8.3+// names and directory aliases agree without case-folding nonexistent names.+async function missingPathIdentity(path) {+ let ancestor = resolve(path);+ const tail = [];+ for (;;) {+ const info = await lstat(ancestor).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (info) {+ // Native realpath expands Windows short names; JavaScript realpath may+ // retain them. Existing dangling links/errors must hold, never walk past.+ const canonical = realpathSync.native(ancestor);+ const identity = await stat(canonical, { bigint: true });+ if ((!identity.isDirectory() && tail.length) || identity.ino === 0n) throw new Error('missing-checkout-ancestor-unverified');+ return { ancestor: canonical, dev: String(identity.dev), ino: String(identity.ino), tail };+ }+ const parent = dirname(ancestor);+ if (parent === ancestor) throw new Error('missing-checkout-ancestor-unverified');+ tail.unshift(basename(ancestor));+ ancestor = parent;+ }+}++// A vanished checkout can still own a staged index and private recovery files.+// Locate its exact registration without recreating the missing working tree.+async function missingCheckoutAdministration(repoPath, path) {+ const present = await lstat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (present) return null;+ const common = resolve(repoPath, (await git(['rev-parse', '--git-common-dir'], repoPath)).trim());+ const roots = [];+ const target = await missingPathIdentity(join(path, '.git'));+ const mismatches = [];+ for (const name of await readdir(join(common, 'worktrees'))) {+ const root = join(common, 'worktrees', name);+ if (!(await lstat(root)).isDirectory()) continue;+ const pointer = await readFile(join(root, 'gitdir'), 'utf8').catch(() => null);+ if (!pointer?.trim()) continue;+ const candidate = await missingPathIdentity(resolve(root, pointer.trim()));+ if (candidate.dev === target.dev && candidate.ino === target.ino && JSON.stringify(candidate.tail) === JSON.stringify(target.tail)) roots.push(root);+ else if (mismatches.length < 4) mismatches.push({ registration: name, pointer: pointer.trim().slice(0, 1024), identity: candidate });+ }+ if (roots.length !== 1) throw new Error(`missing-checkout-administration-unverified: ${JSON.stringify({ target, matches: roots.length, mismatches })}`);+ return roots[0];+}++async function archiveSnapshots(tree, repoPath, missingRoot) {+ if (!missingRoot) return Promise.all([snapshotContent(tree.path), snapshotAdministration(tree.path)]);+ const present = await lstat(tree.path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (present) throw new Error('missing-checkout-reappeared');+ const prefix = ['--git-dir', missingRoot, '--work-tree', tree.path];+ if ((await git([...prefix, 'ls-files', '-u', '-z'], repoPath)).length) throw new Error('unmerged index entries cannot be archived');+ const indexDiff = await git([...prefix, 'diff', '--cached', '--binary', '--no-textconv', '--no-ext-diff'], repoPath);+ const content = { indexDiff, worktreeDiff: '', files: [], symlinks: [], gitlinks: [], missingCheckout: true,+ fingerprint: createHash('sha256').update('missing-checkout\0').update(indexDiff).digest('hex') };+ return [content, await snapshotAdministration(tree.path, missingRoot)];+}++/** Preserve ignored content and recovery evidence before a clean merged tree+ * is removed. The caller owns the live ownership fence and merge proof; this+ * guard verifies that every preserved byte still matches immediately at removal.+ */+export async function preserveMergedCheckout(repoPath, tree, defaultBranch, { cosDir } = {}) {+ if (!tree?.head || (!tree.branch && tree.detached !== true) || tree.locked) throw new Error('checkout-identity-unavailable');+ const branch = shortBranch(tree.branch);+ const missingRoot = await missingCheckoutAdministration(repoPath, tree.path);+ const archive = await archiveCheckout({ repoPath, tree, branch, defaultBranch, cosDir, missingRoot });+ return {+ archiveDir: archive.dir,+ async verify(holder) {+ if (!holder || holder.head !== tree.head || holder.branch !== tree.branch || Boolean(holder.detached) !== Boolean(tree.detached)) return 'worktree-holder-changed';+ const [content, administration] = await archiveSnapshots(tree, repoPath, missingRoot);+ return content.fingerprint === archive.fingerprint && administration.fingerprint === archive.administrationFingerprint+ ? null : 'checkout-content-changed';+ },+ };+}++async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, release, review, missingRoot = null }) {+ const [snapshot, administration] = await archiveSnapshots(tree, repoPath, missingRoot);+ // Sequencer state can contain abbreviated or external object references.+ // Keep that checkout for recovery instead of claiming a complete bundle.+ if (administration.files.some(file => /^gitdir\/(rebase-merge|rebase-apply|sequencer)\//.test(file.path))) {+ throw new Error('retirement-operation-active');+ }await ensureDir(dir);await chmod(dir, 0o700);// A bundle keeps the original commit objects, merges included, which a// squash-merged branch would otherwise lose to garbage collection.const bundle = join(dir, 'commits.bundle');- await git(['bundle', 'create', bundle, 'HEAD'], tree.path);- const [, heads] = await Promise.all([git(['bundle', 'verify', bundle], repoPath), git(['bundle', 'list-heads', bundle], repoPath)]);- if (!heads.startsWith(`${tree.head} `)) throw new Error('bundle head mismatch');+ // Private reflogs and operation files may name commits no longer reachable+ // from HEAD. Preserve their objects too, not just text that later GC would+ // make useless. Unknown/missing recovery objects hold the checkout.+ const recoveryHeads = new Set([tree.head]);+ for (const file of administration.files) {+ if (file.path === 'git-indirection' || /\/(index|gitdir|commondir|locked)$/.test(file.path)) continue;+ const contents = await readFile(file.source, 'utf8');+ for (const match of contents.matchAll(/(?<![a-f0-9])[a-f0-9]{40}(?:[a-f0-9]{24})?(?![a-f0-9])/gi)) {+ if (!/^0+$/.test(match[0])) recoveryHeads.add(match[0].toLowerCase());+ }+ }+ if (recoveryHeads.size > 1024) throw new Error('too many private recovery objects');+ const recoveryRefs = [];+ const namespace = `refs/portos/archive/${randomUUID()}`;+ try {+ for (const head of recoveryHeads) {+ const type = (await git(['cat-file', '-t', head], repoPath)).trim();+ if (type !== 'commit') throw new Error('private recovery object is not a commit');+ const ref = `${namespace}/${head}`;+ await git(['update-ref', ref, head, ''], repoPath);+ recoveryRefs.push({ ref, head });+ }+ await git([...(missingRoot ? ['--git-dir', missingRoot, '--work-tree', tree.path] : []), 'bundle', 'create', bundle, 'HEAD', ...recoveryRefs.map(entry => entry.ref)], missingRoot ? repoPath : tree.path);+ const [, heads] = await Promise.all([git(['bundle', 'verify', bundle], repoPath), git(['bundle', 'list-heads', bundle], repoPath)]);+ const bundled = new Set(heads.trim().split('\n').map(line => line.split(' ')[0]));+ if ([...recoveryHeads].some(head => !bundled.has(head))) throw new Error('bundle recovery head mismatch');+ } finally {+ // These are private temporary refs, never branch refs. The checkout and its+ // original reflog remain intact unless the entire archive later verifies.+ for (const { ref, head } of recoveryRefs) await git(['update-ref', '-d', ref, head], repoPath);+ }await chmod(bundle, 0o600);for (const file of administration.files) {const destination = join(dir, 'administration', file.path);@@ -231,14 +343,14 @@ async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, releasif (await sha256File(destination) !== file.sha256) throw new Error(`archived copy of ${file.path} does not match`);}// Re-read after every copy so the check covers the whole archive window.- const [after, administrationAfter] = await Promise.all([snapshotContent(tree.path), snapshotAdministration(tree.path)]);+ const [after, administrationAfter] = await archiveSnapshots(tree, repoPath, missingRoot);if (administrationAfter.fingerprint !== administration.fingerprint) throw new Error('administration changed while archiving');if (after.fingerprint !== snapshot.fingerprint) throw new Error('checkout content changed while archiving');await atomicWrite(join(dir, 'manifest.json'), {repoPath, defaultBranch, path: tree.path, head: tree.head, branch,release, review, administration: { ...administration, files: administration.files.map(({ source: _source, ...file }) => file) }, archivedAt: new Date().toISOString(),- captured: { commitBundle: true, gitlinks: snapshot.gitlinks, indexDiff: Boolean(snapshot.indexDiff), worktreeDiff: Boolean(snapshot.worktreeDiff), files, symlinks },+ captured: { commitBundle: true, recoveryHeads: [...recoveryHeads], ...(snapshot.missingCheckout ? { missingCheckout: true } : {}), gitlinks: snapshot.gitlinks, indexDiff: Boolean(snapshot.indexDiff), worktreeDiff: Boolean(snapshot.worktreeDiff), files, symlinks },restore: ['git -C <repo> fetch commits.bundle HEAD:refs/heads/<restored-branch>',`git -C <repo> worktree add <checkout> ${tree.head}`,@@ -376,8 +488,8 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {// A new checkout/commit cannot be deleted by a stale name-only operation.const holders = await listWorktrees(repoPath).catch(() => null);if (!holders || holders.some(holder => shortBranch(holder.branch) === branch)) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-has-new-holder' };- const deleted = await execGit(['update-ref', '-d', `refs/heads/${branch}`, release.head], repoPath, { ignoreExitCode: true }).catch(() => null);- if (!deleted || deleted.exitCode !== 0) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-ref-changed-or-delete-failed' };+ const deleted = await deleteCompletedLocalBranch(repoPath, branch, release.head);+ if (!deleted) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-ref-changed-or-delete-failed' };return { ok: true, archiveDir: archive.dir, branchDeleted: true };});}diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.jsindex 9f70433094..66bfb1f794 100644--- a/server/services/heldCheckoutRecovery.test.js+++ b/server/services/heldCheckoutRecovery.test.js@@ -4,13 +4,20 @@* mutation, and an ownership change or archive failure leaves the checkout,* its lock and its branch as found.*/-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';import { mkdtemp, mkdir, rm, writeFile, readFile, readdir, symlink, utimes } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { execGit } from '../lib/execGit.js';import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { PATHS } from '../lib/paths.js';++// Local branch deletion archives the common reflog using PATHS.cos, independently+// of the checkout archive's explicit cosDir option.+vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-held-branch-archives-') }));+afterAll(cleanupTempDataRoots);const SYMLINKS = process.platform !== 'win32';const injected = vi.hoisted(() => ({ policies: [], schedule: null, app: null, fetchRemote: null, fetches: [] }));@@ -40,7 +47,7 @@ vi.mock('./taskScheduleStore.js', async (importOriginal) => ({}));vi.mock('./apps.js', () => ({ getAppById: async (id) => (injected.app?.id === id ? injected.app : null) }));-const { retireInventoriedCheckout, prepareInventoriedCheckoutRetirement, retirePendingMergeCheckout, heldCheckoutArchiveRoot } = await import('./heldCheckoutRecovery.js');+const { retireInventoriedCheckout, prepareInventoriedCheckoutRetirement, retirePendingMergeCheckout, heldCheckoutArchiveRoot, preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');const { recordBranchReconcileOutcome, getBranchReconcileOutcome } = await import('./taskSchedule.js');describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', () => {@@ -94,6 +101,92 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()}const archives = async () => (existsSync(heldCheckoutArchiveRoot(cosDir)) ? readdir(heldCheckoutArchiveRoot(cosDir)) : []);+ it('preserves ignored evidence before unattended cleanup and refuses later byte or head changes', async () => {+ const path = join(external, 'merged');+ await execGit(['worktree', 'add', '-b', 'feature/done', path, 'main'], repo);+ await writeFile(join(path, 'ignored.txt'), 'recovery evidence');+ await writeFile(join(repo, '.git', 'info', 'exclude'), 'ignored.txt\n');+ expect((await execGit(['status', '--porcelain'], path)).stdout.trim()).toBe('');+ const tree = { path, branch: 'refs/heads/feature/done', head: (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim() };+ const saved = await preserveMergedCheckout(repo, tree, 'main', { cosDir });+ expect(await readFile(join(saved.archiveDir, 'files', 'ignored.txt'), 'utf8')).toBe('recovery evidence');+ await execGit(['bundle', 'verify', join(saved.archiveDir, 'commits.bundle')], repo);+ expect(await saved.verify(tree)).toBe(null);+ expect(await saved.verify({ ...tree, head: 'f'.repeat(40) })).toBe('worktree-holder-changed');+ await writeFile(join(path, 'ignored.txt'), 'new evidence');+ expect(await saved.verify(tree)).toBe('checkout-content-changed');+ expect(existsSync(path)).toBe(true);+ });++ it('bundles reflog-only commits into a standalone recovery repository', async () => {+ const path = join(external, 'reflog');+ await execGit(['worktree', 'add', '-b', 'feature/reflog', path, 'main'], repo);+ await writeFile(join(path, 'lost.txt'), 'recover this private commit');+ await execGit(['add', 'lost.txt'], path);+ await execGit(['commit', '-m', 'private recovery commit'], path);+ const lost = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();+ await execGit(['reset', '--hard', 'main'], path);+ const tree = { path, branch: 'refs/heads/feature/reflog', head: (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim() };+ const saved = await preserveMergedCheckout(repo, tree, 'main', { cosDir });+ const manifest = JSON.parse(await readFile(join(saved.archiveDir, 'manifest.json'), 'utf8'));+ expect(manifest.captured.recoveryHeads).toContain(lost);+ const restored = join(scratch, 'restored');+ await execGit(['init', '--bare', restored], scratch);+ await execGit(['fetch', join(saved.archiveDir, 'commits.bundle'), '+refs/portos/archive/*:refs/recovered/*'], restored);+ expect((await execGit(['show', `${lost}:lost.txt`], restored)).stdout).toBe('recover this private commit');+ expect(await saved.verify(tree)).toBe(null);+ });++ it.each([false, true])('archives a missing checkout private index and staged contents before pruning, parentAlias=%s', async parentAlias => {+ const path = join(external, 'missing');+ await execGit(['worktree', 'add', '-b', 'feature/missing', path, 'main'], repo);+ await writeFile(join(path, 'staged.txt'), 'only in the private index');+ await execGit(['add', 'staged.txt'], path);+ const tree = { path, branch: 'refs/heads/feature/missing', head: (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim() };+ if (parentAlias) {+ const alias = join(scratch, 'external-alias');+ // Directory junctions need no Windows symlink privilege. This reproduces+ // two filesystem spellings of the existing parent of a missing checkout.+ await symlink(external, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const admin = (await execGit(['rev-parse', '--absolute-git-dir'], path)).stdout.trim();+ await writeFile(join(admin, 'gitdir'), `${join(alias, 'missing', '.git')}\n`);+ await execGit(['worktree', 'add', '--detach', join(external, 'unrelated'), 'main'], repo);+ }+ await rm(path, { recursive: true, force: true });+ const saved = await preserveMergedCheckout(repo, tree, 'main', { cosDir });+ expect(await readFile(join(saved.archiveDir, 'index.diff'), 'utf8')).toContain('only in the private index');+ expect(existsSync(join(saved.archiveDir, 'administration', 'gitdir', 'index'))).toBe(true);+ expect(JSON.parse(await readFile(join(saved.archiveDir, 'manifest.json'), 'utf8')).captured.missingCheckout).toBe(true);+ expect(await saved.verify(tree)).toBe(null);+ const restored = join(scratch, 'restored-missing');+ await mkdir(restored);+ await materializeGitRepo(restored);+ await execGit(['fetch', join(saved.archiveDir, 'commits.bundle'), 'HEAD:refs/heads/recovered'], restored);+ await execGit(['checkout', 'recovered'], restored);+ await execGit(['apply', '--index', join(saved.archiveDir, 'index.diff')], restored);+ expect(await readFile(join(restored, 'staged.txt'), 'utf8')).toBe('only in the private index');+ expect((await execGit(['show', ':staged.txt'], restored)).stdout).toBe('only in the private index');+ await mkdir(path);+ await expect(saved.verify(tree)).rejects.toThrow('missing-checkout-reappeared');+ });++ it.each(['different-tail', 'different-parent', 'tail-case'])('refuses a missing checkout whose private registration points elsewhere: %s', async mismatch => {+ const path = join(external, 'missing-mismatched');+ await execGit(['worktree', 'add', '-b', 'feature/mismatched', path, 'main'], repo);+ const admin = (await execGit(['rev-parse', '--absolute-git-dir'], path)).stdout.trim();+ const tree = { path, branch: 'refs/heads/feature/mismatched', head: (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim() };+ await rm(path, { recursive: true, force: true });+ const otherParent = join(scratch, 'other-parent');+ await mkdir(otherParent);+ const pointer = mismatch === 'different-parent' ? join(otherParent, 'missing-mismatched', '.git')+ : join(external, mismatch === 'tail-case' ? 'MISSING-MISMATCHED' : 'another-checkout', '.git');+ await writeFile(join(admin, 'gitdir'), `${pointer}\n`);+ await expect(preserveMergedCheckout(repo, tree, 'main', { cosDir }))+ .rejects.toThrow('missing-checkout-administration-unverified');+ expect(await archives()).toEqual([]);+ expect(existsSync(join(admin, 'index'))).toBe(true);+ });+it('archives staged, unstaged, untracked, ignored and symlinked content, then retires a locked detached checkout', async () => {await writeFile(join(repo, 'eol.txt'), 'one\ntwo\n');// No newline: Windows core.autocrlf must not make this stat-only fixture@@ -146,9 +239,19 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()remaining: [{ ...release, managed: false, reason: 'worktree-locked' }, { branch: 'other', reason: 'actionable' }],});+ const branchArchiveRoot = join(PATHS.cos, 'branch-retirement-archives');+ const priorArchives = new Set(await readdir(branchArchiveRoot).catch(() => []));+ const originalReflog = await readFile(join(repo, '.git', 'logs', 'refs', 'heads', 'feature', 'held'));const result = await retireInventoriedCheckout({ appId: 'app-1', release }, { cosDir, readAgents: noOwners });- expect(result).toMatchObject({ ok: true, branchDeleted: true });+ expect(result, JSON.stringify(result)).toMatchObject({ ok: true, branchDeleted: true });+ const newArchives = (await readdir(branchArchiveRoot)).filter(name => !priorArchives.has(name));+ expect(newArchives).toHaveLength(1);+ const branchArchive = join(branchArchiveRoot, newArchives[0]);+ expect(await readFile(join(branchArchive, 'reflog'))).toEqual(originalReflog);+ const branchManifest = JSON.parse(await readFile(join(branchArchive, 'manifest.json'), 'utf8'));+ expect(branchManifest).toMatchObject({ branch: release.branch, expectedHead: release.head });+ await execGit(['bundle', 'verify', join(branchArchive, 'commits.bundle')], repo);expect(existsSync(path)).toBe(false);expect((await execGit(['branch', '--list', 'feature/held'], repo)).stdout.trim()).toBe('');// The original commit stays recoverable after its branch is gone.diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex 541ab535e0..df1664a31d 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -365,7 +365,7 @@ function followUpPolicy(entry, binding) {};}-async function currentHandoffOwnerPolicy(binding) {+async function currentHandoffOwnerPolicy(binding, { recovery = false } = {}) {if (!binding) return null; // Legacy PortOS-opened entries have no task binding.const { getTaskById } = await import('./cosTaskStore.js');const task = binding.taskId && await getTaskById(binding.taskId).catch(() => null);@@ -375,7 +375,7 @@ async function currentHandoffOwnerPolicy(binding) {|| resolvePrCompletion(metadata) !== binding.prCompletion) {return { ownerBlocked: 'The coordinating task completion policy changed; a fresh verified handoff is required' };}- if (task.status === 'pending') return { ownerDeferred: true };+ if (task.status === 'pending' || (recovery && task.status === 'in_progress')) return { ownerDeferred: true };if (!['in_progress', 'completed'].includes(task.status)) {return { ownerBlocked: `The coordinating task is ${task.status || 'unreadable'}` };}@@ -387,7 +387,9 @@ async function notifyPendingMergeTimeout(app, pending, reason, description = nultype: NOTIFICATION_TYPES.AGENT_WARNING,priority: PRIORITY_LEVELS.HIGH,title: `Pending PR #${pending.prNumber} needs attention`,- description: description || `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`,+ description: description || (readHandoffBinding(pending)+ ? `PR polling needs attention after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}. PortOS retains its pending-merge receipt and continues checking for recovery.`+ : `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`),link: pending.prUrl,metadata: { appId: app.id, pendingMergePrNumber: pending.prNumber }}).catch((err) => {@@ -396,11 +398,39 @@ async function notifyPendingMergeTimeout(app, pending, reason, description = nul});}+// A permanent cleanup hold needs a named task, not an invisible retry loop.+// Manual policy holds remain with their owner and never grant new authority.+async function recoverHeldCleanup(app, entry, binding) {+ if (entry.cleanup?.reason === 'pr-completion-human-handoff') return entry;+ const { getTaskById } = await import('./cosTaskStore.js');+ if (entry.cleanup?.recoveryTaskId) {+ const task = await getTaskById(entry.cleanup.recoveryTaskId).catch(() => null);+ return task?.status === 'completed' && !entry.cleanup.recoveryCompleted+ ? { ...entry, cleanup: { ...entry.cleanup, status: 'pending', retryAt: 0, recoveryCompleted: true } } : entry;+ }+ if (await currentHandoffOwnerPolicy(binding, { recovery: true })) return entry;+ const { addTask } = await import('./cos.js');+ const task = await addTask({+ description: `[Recovery] Prepare retained checkout for coordinator retirement: ${entry.prBranch} in ${app.name || app.id}`,+ app: app.id, priority: 'HIGH', isRecovery: true, useWorktree: false,+ metadata: { existingBranch: entry.prBranch, recoveryOrigin: { parentAgentId: binding.agentId,+ parentTaskId: binding.taskId, subsystem: 'repository-cleanup' } },+ context: `PR ${entry.prUrl} is MERGED at ${binding.headSha}; cleanup is still owned by its receipt.+Repository: ${app.repoPath}+Checkout: ${binding.worktreePath}+Retained reason: ${entry.cleanup.reason}+Archive: ${entry.cleanup.archiveDir || 'not yet verified'}+Repair preservation prerequisites for only this checkout, leaving final worktree/ref removal to its receipt coordinator. Do not delete the checkout or refs yourself. Re-read live ownership, locks, head and completion policy. Preserve every unique tracked, untracked and ignored byte and verify recovery evidence before removal. Never infer inactivity from an absent process or missing registry entry. Do not reopen or merge the PR, change the primary checkout, bypass unmanaged-location guards, remove another agent’s lock, or discard content. If retirement is not authorized, retain the checkout and record the exact owner, blocker and next step.`,+ }, 'user').catch(() => null);+ return task?.id ? { ...entry, cleanup: { ...entry.cleanup, recoveryTaskId: task.id } } : entry;+}+async function finishMergedReceipt(app, entry, binding) {// Legacy queue records did not bind a checkout. Their existing branch// reconciliation remains the cleanup owner; never infer a deletion target.if (!binding?.worktreePath) return null;- if (entry.cleanup?.status === 'held' || Date.now() < (entry.cleanup?.retryAt || 0)) return entry;+ if (entry.cleanup?.status === 'held') return recoverHeldCleanup(app, entry, binding);+ if (Date.now() < (entry.cleanup?.retryAt || 0)) return entry;const { retirePendingMergeCheckout } = await import('./heldCheckoutRecovery.js');const result = await retirePendingMergeCheckout({repoPath: app.repoPath, prUrl: entry.prUrl, expectedHeadSha: binding.headSha,@@ -413,7 +443,7 @@ async function finishMergedReceipt(app, entry, binding) {const attempts = (entry.cleanup?.attempts || 0) + 1;const reason = result.reason || result.branchRetainedReason || 'branch-retained';const requiresRecovery = CLEANUP_REQUIRES_RECOVERY.has(reason);- const cleanup = { status: requiresRecovery || attempts >= MAX_PENDING_MERGE_TICKS ? 'held' : 'pending',+ const cleanup = { ...entry.cleanup, status: entry.cleanup?.recoveryCompleted || requiresRecovery || attempts >= MAX_PENDING_MERGE_TICKS ? 'held' : 'pending',reason, attempts, retryAt: Date.now() + PENDING_MERGE_SWEEP_INTERVAL_MS,...(result.archiveDir ? { archiveDir: result.archiveDir } : {}) };if (!entry.cleanup || cleanup.status === 'held') {@@ -472,7 +502,7 @@ async function runPendingMergePrs(app, { spendTicks }) {for (const entry of pending) {const key = pendingMergeKey(entry);- if (entry.cleanup?.status === 'held' || Date.now() < (entry.cleanup?.retryAt || 0)) {+ if (Date.now() < (entry.cleanup?.retryAt || 0)) {outcomes.set(key, entry);continue;}@@ -482,9 +512,9 @@ async function runPendingMergePrs(app, { spendTicks }) {if (binding.repository !== repositoryKey(origin)) binding = INVALID_HANDOFF;}if (binding === INVALID_HANDOFF) {- await notifyPendingMergeTimeout(app, entry, null,+ if (!entry.recoveryBlocked) await notifyPendingMergeTimeout(app, entry, null,'PortOS will not merge this handed-off PR: its recorded head/policy binding is unreadable or names another repository. Verify the PR and merge or re-dispatch it.');- outcomes.set(key, null);+ outcomes.set(key, { ...entry, recoveryBlocked: 'handoff-binding-unreadable' });result.invalidated += 1;continue;}@@ -500,8 +530,8 @@ async function runPendingMergePrs(app, { spendTicks }) {result.errors += 1;const unreadable = { ...entry, ticks: entry.ticks + charge };if (unreadable.ticks >= MAX_PENDING_MERGE_TICKS) {- await notifyPendingMergeTimeout(app, entry, 'it could not be read from the forge');- outcomes.set(key, null);+ if (!entry.attention) await notifyPendingMergeTimeout(app, entry, 'it could not be read from the forge');+ outcomes.set(key, binding ? { ...unreadable, ticks: MAX_PENDING_MERGE_TICKS, attention: 'forge-unreadable' } : null);result.timedOut += 1;} else {outcomes.set(key, unreadable);@@ -515,6 +545,13 @@ async function runPendingMergePrs(app, { spendTicks }) {continue;}+ if (binding && String(prView.state || '').toUpperCase() === 'CLOSED') {+ if (!entry.recoveryBlocked) await notifyPendingMergeTimeout(app, entry, null,+ `PR #${entry.prNumber} was closed without merging. Its receipt retains the branch and checkout; explicit disposition is required.`);+ outcomes.set(key, { ...entry, recoveryBlocked: 'pr-closed-unmerged' });+ continue;+ }+// A refused owner/policy or exhausted budget remains refused even if CI// later turns green. Only a fresh verified handoff replaces this receipt.if (entry.recoveryBlocked) {@@ -528,7 +565,7 @@ async function runPendingMergePrs(app, { spendTicks }) {const failure = headMoved ? 'head-moved' : classifyPrFailure(prView);if (failure) {try {- const ownerPolicy = await currentHandoffOwnerPolicy(binding);+ const ownerPolicy = await currentHandoffOwnerPolicy(binding, { recovery: true });if (ownerPolicy) {outcomes.set(key, ownerPolicy.ownerBlocked ? { ...entry, recoveryBlocked: ownerPolicy.ownerBlocked } : entry);result.waiting = (result.waiting || 0) + 1;@@ -556,6 +593,11 @@ async function runPendingMergePrs(app, { spendTicks }) {`PR #${entry.prNumber} remains owned by review task ${recovery.id}: ${recovery.blocked}. Resume that task after resolving the blocker; its worktree and exact-head merge gate are preserved.`);continue;}+ if (!recovery?.id) {+ outcomes.set(key, { ...entry, attention: 'recovery-not-persisted' });+ result.errors += 1;+ continue;+ }outcomes.set(key, null);result.escalated += 1;console.log(`🔁 Pending PR #${entry.prNumber}: ${failure}; coordinator ${recovery?.id || 'queued'}${recovery?.resumed ? ' resumed' : ''}`);@@ -638,8 +680,8 @@ async function runPendingMergePrs(app, { spendTicks }) {const reason = String(prView.state || '').toUpperCase() !== 'OPEN'? `it is ${String(prView.state).toLowerCase()} rather than open`: withheldReason || 'CI or mergeability did not settle';- await notifyPendingMergeTimeout(app, entry, reason);- outcomes.set(key, null);+ if (!entry.attention) await notifyPendingMergeTimeout(app, entry, reason);+ outcomes.set(key, binding ? { ...next, ticks: MAX_PENDING_MERGE_TICKS, attention: reason } : null);result.timedOut += 1;} else {outcomes.set(key, next);@@ -736,8 +778,12 @@ function receiptSweep(appId) {* queued (CI pending, admission deferred, forge briefly unreadable) — the app's* bounded follow-up poll. Never rejects.*/+export async function mergeHandoffSuccessorBlocked() {+ return handoffFollowUpGate ? await handoffFollowUpGate().catch(() => 'gate-unreadable') : 'daemon-stopped';+}+export function followUpHandoffReceipt(appId, receiptId) {- return _sweepPendingMergeApp(appId)+ return mergeHandoffSuccessorBlocked().then(blocked => blocked ? null : _sweepPendingMergeApp(appId)).then(() => armHandoffFollowUp(appId, receiptId)).catch((err) => {console.error(`❌ Handoff follow-up for app ${appId} could not be armed: ${err.message}`);diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txtindex fd5213b844..6069837cee 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt@@ -25,11 +25,11 @@ fiOnly an `ok: true` response with a validated `clean` or `findings` verdict and a successfully extracted `.findings` value is review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.-6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txtindex de550d5e89..8783bd155e 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt@@ -30,11 +30,11 @@ fiOnly an `ok: true` response with a validated `clean` or `findings` verdict and a successfully extracted `.findings` value is review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.-6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txtindex b304480044..e51da36085 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt@@ -12,11 +12,11 @@ A previous agent finished task **task-example** and opened **PR https://github.c1. For EACH reviewer in order — `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: wait for the initial Copilot review the system already pre-requested (Copilot leads the list) (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.-6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txtindex 694cea9817..70b17c1d0f 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt@@ -35,11 +35,11 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.-6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txtindex 798711d0e6..6bac2ae557 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt@@ -40,11 +40,11 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.5. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.-6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txtindex a03b96f66d..76fea505c2 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt@@ -1,11 +1,11 @@## Merge Follow-up (PRIMARY OBJECTIVE)A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **No code review was requested for this task, so nothing else will merge this PR Your job is to land it once CI is green.**-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.2. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, `git push --force-with-lease`, and re-check.-3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged (a saved `/do:pr` default can merge it for you), skip to the next step:+3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged (a saved `/do:pr` default can merge it for you), skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txtindex 2054dd9afa..fd710202c7 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt@@ -1,11 +1,11 @@## Merge GateThis runs as **step 4 of the Completion Workflow above**, against the PR you just opened on `feature/example` (`https://github.com/example-org/example-repo/pull/42` / `42` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR Land it yourself once CI is green.**-**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. A verified pending handoff is successful only outside local admission: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.+**Own delivery through completion:** By default stay responsible for "https://github.com/example-org/example-repo/pull/42" through all required CI, review, confirmed MERGED and safe cleanup. GitHub auto-merge enabled is not completion and does not transfer failure recovery or cleanup. Early finish is allowed only with an explicit persisted PortOS pending-merge receipt for the exact published/reviewed head, accepted after the server observes the configured CI backlog threshold. The app setting `mergeHandoffMinQueuedRuns` is opt-in: absent/null means keep ownership; no threshold is inferred from elapsed time. Unknown backlog, refused handoff or failed receipt persistence means continue in-session. The receipt owns CI failure recovery, changed heads, merge confirmation and preserved cleanup across restarts. Report its receipt ID and PR/head as pending, never merged; preserve the checkout and issue until the successor confirms completion. Intentional leave-open policies remain unchanged. Never enable native GitHub auto-merge to bypass local admission or a refused handoff.**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request's CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.2. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, `git push --force-with-lease`, and re-check.-3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:+3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, unless the exact-head durable PortOS successor above accepted responsibility for the remaining work. If it is already merged, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>```diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex eeb42c21ac..ba5ad2426a 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -602,9 +602,9 @@ function buildPendingMergeHandoffLines(agentId) {const command = agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/merge-handoff',payload: JSON.stringify({ agentId, prUrl: 'PR_URL', headSha: 'HEAD_SHA', worktreePath: 'WORKTREE_PATH' }) });return [- '**PortOS pending-merge handoff (GitHub, same-repository PR, before waiting for CI):** The server coordinator waits for required CI and merges exactly your recorded head under its own admission, so this run need not hold its session open. When a configured local review round returns clean, record the head it reviewed beside REVIEW_STATUS (any later commit, fix, rebase or conflict resolution means that head was not reviewed, so rerun the affected review first):',+ '**PortOS pending-merge handoff (GitHub, same-repository PR, only for measured CI backlog):** By default this run owns CI, confirmed merge and safe cleanup. Early finish requires the app setting `mergeHandoffMinQueuedRuns` and a fresh server-observed queued workflow count meeting that threshold; absent settings or unknown backlog keep ownership here. The server coordinator then owns the exact reviewed head, failure recovery, merge confirmation and cleanup across restarts. When a configured local review round returns clean, record the head it reviewed beside REVIEW_STATUS (any later commit, fix, rebase or conflict resolution means that head was not reviewed, so rerun the affected review first):','```bash', RECORD_REVIEW_HEAD, '```',- 'Once the published head (`git rev-parse HEAD` equals the PR head) has passed local validation and every configured review, and the PR is ready (not draft), hand it off — unless review is `review-blocked` or the PR is being left open, whose stop rules still apply. Replace PR_URL, HEAD_SHA (the full 40-character head) and WORKTREE_PATH (this checkout):',+ 'Once the published head (`git rev-parse HEAD` equals the PR head) has passed local validation and every configured review, and the PR is ready (not draft), request a handoff only if backlog policy is configured — unless review is `review-blocked` or the PR is being left open, whose stop rules still apply. Replace PR_URL, HEAD_SHA (the full 40-character head) and WORKTREE_PATH (this checkout):','```bash', command, '```','Require a parsed JSON response with queued:true and a receipt whose headSha equals HEAD_SHA. Then the receipt is your merge outcome: do not wait for CI, acquire admission, merge, enable auto-merge, close the issue, release a claim, or remove the branch or worktree; the coordinator merges or dispatches recovery (a moved head, failed check or conflict). Report the PR URL, head and receipt id, say the PR is handed to the PortOS pending-merge coordinator with CI pending and is NOT yet merged, write the completion sentinel if this run uses one, and stop. This overrides later CI waits, MERGED-only completion and cleanup instructions, including delegated slashdo workflows. On queued:false with retryable:true, retry up to 3 times 5 seconds apart. Any other refusal, an HTTP/auth/transport error or unreadable JSON means no handoff: continue with the CI wait and admission-gated merge below. A refusal never permits merging without admission.',];diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsindex 77a9f912f7..1bfb12e130 100644--- a/server/services/promptSections/completion.test.js+++ b/server/services/promptSections/completion.test.js@@ -27,13 +27,10 @@ describe('review-enabled completion merge gate', () => {expect(section).toContain('gh pr checks "<PR_URL>" --watch --fail-fast --interval 30');expect(section).toContain('repeat the configured review loop for `copilot` against the new HEAD');expect(section).toContain('gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>');- expect(section.indexOf('GitHub auto-merge handoff')).toBeLessThan(section.indexOf('4. **Wait for CI to finish**'));- expect(section).toContain('allow_auto_merge: true');- expect(section).toContain('autoMergeRequest.enabledAt');- expect(section).toContain('If this run requires repository merge admission, do not enable GitHub auto-merge');- expect(section).toContain('every outstanding check');- expect(section).toContain('Missing/unknown required-check policy');- expect(section).toContain('all configured reviews pass');+ expect(section).toContain('By default stay responsible');+ expect(section).toContain('mergeHandoffMinQueuedRuns');+ expect(section).toContain('Unknown backlog, refused handoff');+ expect(section).not.toContain('--auto --merge');expect(section).toContain('8. Write a short markdown summary');});diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex b86165a799..fa5ea1beef 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -1139,7 +1139,7 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',gh ? PREGATE_ATTESTATION_STEP : null,`${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,`${startStep + 1}. **Clear whatever blocks the merge, then re-check.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push.${reviewRecheckAfterCodeFix} Then go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent,${rebaseReviewSuffix} re-run the tests, \`git push --force-with-lease\`, and re-check.`,- `${startStep + 2}. **Merge** ${gh ? 'with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed' : 'with exactly these flags, nothing else'} — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, ${gh ? 'unless the verified GitHub auto-merge handoff above already completed this run' : 'and any merge-deferral flag leaves the PR open after you exit'}. If it is already merged${alreadyMergedHint}, skip to the next step:`,+ `${startStep + 2}. **Merge** ${gh ? 'with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed' : 'with exactly these flags, nothing else'} — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, ${gh ? 'unless the exact-head durable PortOS successor above accepted responsibility for the remaining work' : 'and any merge-deferral flag leaves the PR open after you exit'}. If it is already merged${alreadyMergedHint}, skip to the next step:`,' ```bash',gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --match-head-commit <verified-head>` : null,// `glab mr merge` takes an MR IID or source branch — a URL is not accepted.diff --git a/server/services/worktreeExternalCleanup.test.js b/server/services/worktreeExternalCleanup.test.jsindex 96450a0284..14339270fd 100644--- a/server/services/worktreeExternalCleanup.test.js+++ b/server/services/worktreeExternalCleanup.test.js@@ -11,12 +11,19 @@ import { cleanupOrphanedWorktrees } from './worktreeManager.js';vi.mock('fs', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, realpathSync: path => fault.pathAlias && (path === fault.aliasTarget || path === fault.pathAlias) ? path : actual.realpathSync(path) };+ return { ...actual, realpathSync: Object.assign(+ path => fault.pathAlias && (path === fault.aliasTarget || path === fault.pathAlias) ? path : actual.realpathSync(path),+ { native: actual.realpathSync.native },+ ) };});vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {dataRoot: () => lazyTempDataRoot('portos-external-cleanup-'),}));+// Shared branch reflog archives import the leaf paths module directly.+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-external-cleanup-'),+}));const fault = vi.hoisted(() => ({ command: null, subcommand: null, cwd: null, successfulMatches: 0, pathAlias: null, aliasTarget: null, registrationPath: null, onGit: null, calls: [] }));vi.mock('../lib/execGit.js', async (importOriginal) => {const actual = await importOriginal();@@ -98,6 +105,9 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('external orphan cleanup recovery policyawait resetGitWorktreeSandbox(external, initialHead);await rm(PATHS.worktrees, { recursive: true, force: true });await mkdir(PATHS.worktrees, { recursive: true });+ // Retirement reads durable completion policy independently of the supplied+ // owner snapshot. Missing state is unknown, not a known-empty registry.+ await writeFile(join(PATHS.cos, 'state.json'), JSON.stringify({ agents: {} }));fault.calls = [];});afterAll(cleanupTempDataRoots);@@ -214,4 +224,12 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('external orphan cleanup recovery policyexpect(await cleanupOrphanedWorktrees(primary, null, NO_OWNERS)).toBe(0);expect(existsSync(path)).toBe(true);});++ it('retains merged work when durable completion policy is unreadable despite an empty owner snapshot', async () => {+ const path = await addTree('agent-policy-unreadable');+ await writeFile(join(PATHS.cos, 'state.json'), '{');+ expect(await cleanupOrphanedWorktrees(primary, new Set(), NO_OWNERS)).toBe(0);+ expect(existsSync(path)).toBe(true);+ expect(await branchExists('agent-policy-unreadable')).toBe(true);+ });});diff --git a/server/services/worktreeManager.fork.test.js b/server/services/worktreeManager.fork.test.jsindex 06ac3d2393..4ff3bbf827 100644--- a/server/services/worktreeManager.fork.test.js+++ b/server/services/worktreeManager.fork.test.js@@ -7,9 +7,10 @@ import { execGit } from '../lib/execGit.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-worktree-fork-' });vi.mock('../lib/fileUtils.js', async importOriginal => makeProxy(await importOriginal()));+vi.mock('../lib/paths.js', async importOriginal => makeProxy(await importOriginal()));vi.mock('./instanceIdentity.js', () => mockTestIdentity());const { PATHS } = await import('../lib/fileUtils.js');-const { createWorktree, removeWorktree } = await import('./worktreeManager.js');+const { createWorktree, removeWorktree, adoptWorktree } = await import('./worktreeManager.js');afterAll(cleanup);const git = async (repo, ...args) => (await execGit(args, repo)).stdout.trim();@@ -37,6 +38,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('fork checkout and publication', () => {const primaryHead = await commit(repo, 'primary-only.txt');await git(repo, 'push', 'origin', 'main');await mkdir(PATHS.worktrees, { recursive: true });+ await writeFile(join(PATHS.cos, 'state.json'), JSON.stringify({ agents: {} }));const options = { existingBranch: 'main', forkHead: { remoteUrl: fork, ownerLogin: 'contributor' }, linkDependencies: false };const attached = await createWorktree('agent-fork', repo, 'task-fork', options);@@ -56,12 +58,18 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('fork checkout and publication', () => {expect(sameRepo.branchName).toBe('same-repo-head');expect(await git(sameRepo.worktreePath, 'rev-parse', 'HEAD')).toBe(primaryHead);const unpublished = await commit(attached.worktreePath, 'retry-work.txt');- await removeWorktree('agent-fork', repo, attached.branchName, { merge: false, preserveBranchWithCommits: true });- const retry = await createWorktree('agent-retry', repo, 'task-fork', options);+ expect(await removeWorktree('agent-fork', repo, attached.branchName, { merge: false, preserveBranchWithCommits: true }))+ .toMatchObject({ removed: false, warnings: expect.arrayContaining([expect.stringContaining('merge-evidence-unavailable')]) });+ const retry = await adoptWorktree('agent-retry', repo, attached.worktreePath, attached.branchName);+ expect(retry).toMatchObject({ adopted: true, branchName: attached.branchName });expect(await git(retry.worktreePath, 'rev-parse', 'HEAD')).toBe(unpublished);expect(await git(fork, 'rev-parse', 'main')).toBe(published);expect(await git(origin, 'rev-parse', 'main')).toBe(primaryHead);- await removeWorktree('agent-retry', repo, retry.branchName, { merge: false, preserveBranchWithCommits: true });+ expect(await removeWorktree('agent-retry', repo, retry.branchName, { merge: false, preserveBranchWithCommits: true }))+ .toMatchObject({ removed: false });+ // Simulate a checkout an older workflow already removed; createWorktree+ // must recover its local-only branch even after the fork ref disappears.+ await git(repo, 'worktree', 'remove', retry.worktreePath);await git(fork, 'update-ref', '-d', 'refs/heads/main');await git(repo, 'fetch', '--prune', 'fork-contributor');const orphaned = await createWorktree('agent-local-recovery', repo, 'task-fork', options);diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex a6908df91f..147b1cd766 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -17,12 +17,14 @@ import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fiimport { DONE_SENTINEL_NAME, doneSentinelCandidateNames } from '../lib/agentSentinel.js';import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';import { execGit } from '../lib/execGit.js';+import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';import { clearStaleGitLock } from '../lib/gitStaleLock.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { forkRemoteName, normalizeForkHead, forkLocalBranch } from '../lib/forkHead.js';import { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';import { ensureInstanceId } from './instanceIdentity.js';+import { preserveBranchRetirement } from '../lib/branchRetirementArchive.js';export { isHumanClaimWorktree } from '../lib/worktreeOwnership.js';@@ -220,13 +222,44 @@ export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null)// realpath-resolved repo path so /var vs /private/var (macOS) don't split the// tail into two lanes that can still collide.const queueWorktreeCreateForKey = createKeyCachedQueue();-function queueWorktreeCreate(repo, fn) {- let key = repo;- try { key = realpathSync(repo); } catch { /* repo may not resolve — fall back to the raw path */ }+async function queueWorktreeCreate(repo, fn) {+ // Linked checkouts share branch refs even when their working paths differ.+ // Resolve that common identity before entering the mutation lane.+ const common = await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], repo)+ .then(result => result.stdout.trim()).catch(() => null);+ let key = common && isAbsolute(common) ? common : repo;+ try { key = realpathSync(key); } catch { /* invalid repositories fail in the operation itself */ }if (!key) key = '__unknown__';return queueWorktreeCreateForKey(key, fn);}+/** Delete one completed local ref through Git's receiver. Unlike update-ref,+ * receive-pack checks all registered worktree holders; unlike branch -D, its+ * transaction also compares the old object id. The local absolute destination+ * cannot resolve through an origin push URL. Existing hooks and denyDeletes+ * policy still apply. Share the creation lane so managed attachments cannot+ * enter between the receiver's holder check and ref transaction.+ */+export function deleteCompletedLocalBranch(repoPath, branch, expectedHead) {+ return queueWorktreeCreate(repoPath, async () => {+ if (PROTECTED_BRANCHES.includes(branch)) return false;+ const { getDefaultBranch } = await import('./git.js');+ const defaultBranch = await getDefaultBranch(repoPath, { strict: true }).catch(() => null);+ if (!defaultBranch || branch === defaultBranch) return false;+ if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(expectedHead || '')) return false;+ const ref = `refs/heads/${branch}`;+ if ((await execGit(['check-ref-format', ref], repoPath, { ignoreExitCode: true })).exitCode !== 0) return false;+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoPath)).stdout.trim();+ if (!isAbsolute(common)) return false;+ const preservation = await preserveBranchRetirement(repoPath, common, branch, expectedHead);+ if (!await preservation.verify()) return false;+ const result = await execGit(['push',+ '--receive-pack=git -c receive.denyCurrentBranch=refuse -c receive.denyDeleteCurrent=refuse -c receive.autogc=false receive-pack',+ `--force-with-lease=${ref}:${expectedHead}`, '--', common, `:${ref}`], repoPath, { ignoreExitCode: true });+ return result.exitCode === 0;+ }).catch(() => false);+}+/*** A git error saying the target BRANCH already exists (`fatal: a branch named* 'X' already exists`) — a permanent precondition failure meaning the ref@@ -377,7 +410,7 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =const check = async () => {const entries = await listWorktrees(repo).catch(() => null);if (!entries) return 'worktree-ownership-unreadable';- const holder = entries.find(wt => pathsEqual(wt.path, worktreePath)) || null;+ const holder = entries.find(wt => canonicalPath(wt.path) === canonicalPath(worktreePath)) || null;if (holder?.locked) return 'worktree-locked';if (!verifyRemoval) return null;const reason = await verifyRemoval(holder).catch(() => 'worktree-ownership-unreadable');@@ -386,7 +419,7 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =// Git's own removal still honors locks acquired after this final read.const fresh = await listWorktrees(repo).catch(() => null);if (!fresh) return 'worktree-ownership-unreadable';- const current = fresh.find(wt => pathsEqual(wt.path, worktreePath)) || null;+ const current = fresh.find(wt => canonicalPath(wt.path) === canonicalPath(worktreePath)) || null;if (current?.locked) return 'worktree-locked';if (current?.branch !== holder?.branch || current?.head !== holder?.head) return 'worktree-holder-changed';return null;@@ -1179,9 +1212,23 @@ async function resolveMergeTarget(sourceWorkspace, defaultBranch) {// arrive after the first removed the directory but preserved unpublished work;// every successful removal path must apply the same branch-retention policy.async function cleanupWorktreeBranch(sourceWorkspace, branchName, {- preserveBranchWithCommits = false, hasUnmergedCommits = false, warnings,+ hasUnmergedCommits = false, warnings, expectedHead,}) {- if (!hasUnmergedCommits && preserveBranchWithCommits) {+ const present = await execGit(['show-ref', '--verify', '--quiet', `refs/heads/${branchName}`], sourceWorkspace, { ignoreExitCode: true }).catch(() => null);+ if (present?.exitCode === 1) return;+ if (present?.exitCode !== 0) {+ warnings.push(`Branch ${branchName} preserved — ref state unavailable`);+ return;+ }+ // Pin even a branch whose checkout was already removed. Unknown or changed+ // refs stay available for recovery instead of falling through to branch -D.+ const currentHead = (await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace).catch(() => null))?.stdout?.trim();+ expectedHead ||= currentHead;+ if (!expectedHead || currentHead !== expectedHead) {+ warnings.push(`Branch ${branchName} preserved — current head unavailable or changed`);+ return;+ }+ if (!hasUnmergedCommits) {// A prior cleanup may have already deleted a landed branch. Confirmed// absence is a clean no-op; an unreadable ref is still work to preserve.const localRef = await execGit(@@ -1214,10 +1261,13 @@ async function cleanupWorktreeBranch(sourceWorkspace, branchName, {if (hasUnmergedCommits) {console.warn(`⚠️ Preserving worktree branch ${branchName} for manual/automated recovery`);} else {- await execGit(['branch', '-D', branchName], sourceWorkspace)- .catch(err => {- console.warn(`⚠️ Branch delete failed for ${branchName}: ${err.message}`);- });+ const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');+ const policy = await readBranchCompletionHold({ repoPath: sourceWorkspace, branch: branchName, retirement: true }).catch(() => 'pr-completion-policy-unavailable');+ if (policy) { warnings.push(`Branch ${branchName} preserved — ${policy}`); return; }+ const recoveryRef = await execGit(['update-ref', `refs/portos/completed/${expectedHead}`, expectedHead], sourceWorkspace, { ignoreExitCode: true }).catch(() => null);+ if (recoveryRef?.exitCode !== 0 || !await deleteCompletedLocalBranch(sourceWorkspace, branchName, expectedHead)) {+ warnings.push(`Branch ${branchName} preserved — head changed, new holder, or deletion refused`);+ }}}@@ -1232,10 +1282,8 @@ async function cleanupWorktreeBranch(sourceWorkspace, branchName, {* @param {string} branchName - The worktree branch to clean up* @param {object} options* @param {boolean} [options.merge] - attempt to merge the branch back first- * @param {boolean} [options.preserveBranchWithCommits] - keep the branch (rather- * than deleting it) whenever it still holds commits the default branch doesn't,- * so a retry can resume the work instead of restarting. Used by the FAILED-agent- * cleanup path; the PR path leaves it off so its local branch is still tidied up.+ * @param {boolean} [options.preserveBranchWithCommits] - legacy caller hint;+ * unmerged branches and checkouts are now always retained until merge proof.* @param {boolean} [options.discardDirt] - remove even when the tree is dirty.* The dirty-abort exists to protect work that might still be wanted; the* throwaway-worktree posture has already declared this tree's contents@@ -1244,21 +1292,77 @@ async function cleanupWorktreeBranch(sourceWorkspace, branchName, {* run, forever. ONLY the discard path may pass this.*/export async function removeWorktree(agentId, sourceWorkspace, branchName, options = {}) {+ const { withClaimOwnershipLock, readClaimOwnershipAgents } = await import('./cosClaimOwnershipState.js');+ const ownershipHold = async () => claimCheckoutOwnerReason({+ branchName, holderPath: join(WORKTREES_DIR, agentId), sourceWorkspace,+ agents: await readClaimOwnershipAgents().catch(() => null), ignoreIds: [agentId],+ });+ return withClaimOwnershipLock(() => removeWorktreeNow(agentId, sourceWorkspace, branchName, options, ownershipHold));+}++async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options, ownershipHold) {const worktreePath = join(WORKTREES_DIR, agentId);const warnings = [];+ const { getDefaultBranch } = await import('./git.js');+ const defaultBranch = await getDefaultBranch(sourceWorkspace, { strict: true }).catch(() => null);+ const protectedReason = PROTECTED_BRANCHES.includes(branchName) || branchName === defaultBranch+ ? 'protected-branch' : !defaultBranch ? 'default-branch-unavailable' : null;+ if (protectedReason) return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false,+ warnings: [`Worktree preserved — ${protectedReason}`] };+ const owner = await ownershipHold();+ if (owner) return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false,+ warnings: [`Worktree preserved — ${owner}`] };+ const completionHold = async (expectedHead) => {+ const owner = await ownershipHold();+ if (owner) return owner;+ const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');+ const policy = await readBranchCompletionHold({ repoPath: sourceWorkspace, branch: branchName, retirement: true });+ if (policy) return policy;+ const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');+ const base = await getDefaultBranch(sourceWorkspace, { strict: true }).catch(() => null);+ if (!base) return 'default-branch-unavailable';+ if (PROTECTED_BRANCHES.includes(branchName) || branchName === base) return 'protected-branch';+ const target = await resolveMergeTarget(sourceWorkspace, base);+ const head = (await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace).catch(() => null))?.stdout?.trim();+ if (!head || (expectedHead && head !== expectedHead)) return 'branch-head-changed-or-unavailable';+ return await hasBranchMergeEvidence(sourceWorkspace, head, target).catch(() => false) ? null : 'merge-evidence-unavailable';+ };+ const preserve = async () => {+ const tree = (await listWorktrees(sourceWorkspace)).find(wt => canonicalPath(wt.path) === canonicalPath(worktreePath));+ if (!tree || tree.branch !== `refs/heads/${branchName}`) throw new Error('worktree-holder-changed');+ const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');+ const hold = await completionHold(tree.head);+ if (hold) throw new Error(hold);+ const archive = await preserveMergedCheckout(sourceWorkspace, tree, null);+ return { ...archive, head: tree.head,+ verify: async holder => await completionHold(tree.head) || await archive.verify(holder) };++ };+ const preserveOrHold = () => preserve().catch(error => {+ warnings.push(`Worktree preserved — archive failed: ${error.message}`);+ return null;+ });if (!existsSync(worktreePath)) {// The directory is gone, but git may still register it (a stale entry pins the// branch). Verify rather than assume; prune when the registration survives.let gone = removalOutcome(worktreePath, await probeWorktreeRemoval(sourceWorkspace, worktreePath));- if (!gone.removed) gone = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath);+ let preservation = null;+ if (!gone.removed) {+ preservation = await preserveOrHold();+ if (!preservation) return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };+ gone = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, { verifyRemoval: preservation.verify });+ }if (!gone.removed) {warnings.push(gone.warning);return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };}console.log(`🌳 Worktree already removed for ${agentId}, cleaning up branch`);+ const finalOwner = await ownershipHold();+ if (finalOwner) return { merged: false, removed: true, uncommittedSaved: false,+ warnings: [...warnings, `Branch ${branchName} preserved — ${finalOwner}`] };await cleanupWorktreeBranch(sourceWorkspace, branchName, {- preserveBranchWithCommits: options.preserveBranchWithCommits || options.merge, warnings,+ preserveBranchWithCommits: options.preserveBranchWithCommits || options.merge, warnings, expectedHead: preservation?.head,});return { merged: false, removed: true, uncommittedSaved: false, warnings };}@@ -1309,6 +1413,9 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// Discard auto-generated lockfile changes that agents don't intend to commit// (e.g., npm install resolving ^version to exact version in package-lock.json)if (dirt.lockfileOnly) {+ // Preserve the original bytes before the intentional lockfile cleanup.+ // A second snapshot below guards the post-cleanup removal boundary.+ if (!await preserveOrHold()) return { merged: false, removed: false, uncommittedSaved: false, warnings };console.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in worktree ${agentId}`);// Never throws past removeWorktree: an undiscardable lockfile keeps the tree.const discarded = await discardLockfileChanges(worktreePath, dirt).then(() => true, err => {@@ -1383,7 +1490,10 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio}}+ const preservation = await preserveOrHold();+ if (!preservation) return { merged, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };const removal = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {+ verifyRemoval: preservation.verify,label: `Worktree remove failed for ${agentId}, falling back to manual cleanup`,log: 'all',subject: agentId,@@ -1398,22 +1508,16 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optioreturn { merged, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };}- // Preserve branch when (a) merge was attempted, failed, and has unmerged commits,- // OR (b) merge was refused because HEAD is on a non-default branch — the commits- // are still there and the user / a follow-up task may want to integrate manually.+ // Merge evidence and completion policy were checked before removal; the+ // branch helper checks them again before its leased local deletion.const hasUnmergedCommits = options.merge && !merged && (commitsAhead > 0 || mergeRefused);- // ...OR (c) the caller asked us to keep any branch that still holds commits- // (`preserveBranchWithCommits`). The no-merge path — which is what a FAILED- // agent's cleanup takes — otherwise deletes the branch unconditionally, taking- // the agent's committed work with it. That is what forces a retry to restart- // from scratch instead of resuming: measured on agent-d2ae0352 (2026-07-27),- // reaped 30s after its PR merged, whose branch was deleted and whose task was- // re-dispatched to a fresh agent. Opt-in rather than automatic so the PR flow- // (which deletes the LOCAL branch after pushing — the remote branch is what the- // PR points at) keeps cleaning up after itself.+ const finalOwner = await ownershipHold();+ if (finalOwner) {+ warnings.push(`Branch ${branchName} preserved — ${finalOwner}`);+ return { merged, removed: true, uncommittedSaved: false, warnings };+ }await cleanupWorktreeBranch(sourceWorkspace, branchName, {- preserveBranchWithCommits: options.preserveBranchWithCommits && !merged,- hasUnmergedCommits, warnings,+ hasUnmergedCommits, warnings, expectedHead: preservation.head,});console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);@@ -1691,7 +1795,8 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, getActiveIds, {// If merge fails, the branch is preserved for manual recovery.const result = await removeIfStillOrphaned({ isOwned: ownershipReason, branchName, holderPath: wt.path, sourceWorkspace, readOwners },- () => removeWorktree(agentId, sourceWorkspace, branchName, { merge: true }),+ () => removeWorktreeNow(agentId, sourceWorkspace, branchName, { merge: true }, async () =>+ ownershipReason() || claimCheckoutOwnerReason({ branchName, holderPath: wt.path, sourceWorkspace, agents: await readOwners() })),).catch(err => {console.log(`⚠️ Failed to clean orphaned worktree ${agentId}: ${err.message}`);return { removed: false };@@ -1865,18 +1970,24 @@ export async function reapMergedWorktrees(sourceWorkspace, {else reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false });return;}+ const initialHold = await verifyRemoval(wt);+ if (initialHold) { hold(initialHold); return; }+ const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');+ const preservation = await preserveMergedCheckout(sourceWorkspace, wt, target).catch(error => ({ error }));+ if (preservation.error) { skipped.push({ path: wt.path, branch: branchName, reason: 'archive-failed', detail: preservation.error.message }); return; }const removal = await forceRemoveWorktreeDir(sourceWorkspace, wt.path, {- label: `worktree remove failed for ${wt.path}`, verifyRemoval,+ label: `worktree remove failed for ${wt.path}`,+ verifyRemoval: async holder => await verifyRemoval(holder) || await preservation.verify(holder),});if (!removal.removed) {skipped.push({ path: wt.path, branch: branchName, reason: removal.reason || 'remove-failed', warning: removal.warning });return;}- const branchDeleted = await execGit(['branch', '-D', branchName], sourceWorkspace).then(() => true).catch(err => {- console.log(`⚠️ branch delete failed for ${branchName}: ${err.message}`);- return false;- });- reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted });+ const holders = await listWorktrees(sourceWorkspace).catch(() => null);+ const branchDeleted = holders && !holders.some(holder => holder.branch === wt.branch)+ && await deleteCompletedLocalBranch(sourceWorkspace, branchName, wt.head);+ reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: Boolean(branchDeleted), archiveDir: preservation.archiveDir });+ if (!branchDeleted) hold('branch-ref-changed-or-new-holder');});}@@ -1948,14 +2059,20 @@ async function cleanupExternalRepoWorktrees(readActiveIds, alreadyHandled, readOconst removed = await removeIfStillOrphaned({ isOwned: () => ownership({ locked: wt.locked }), branchName, holderPath: worktreePath, sourceWorkspace: parentRepo, readOwners },async () => {+ const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');+ const preservation = await preserveMergedCheckout(parentRepo, wt, target);+ const latest = (await listWorktrees(parentRepo)).find(holder => pathsEqual(holder.path, worktreePath));+ if (ownership({ locked: latest?.locked }) || await preservation.verify(latest)+ || claimCheckoutOwnerReason({ branchName, holderPath: worktreePath, sourceWorkspace: parentRepo, agents: await readOwners() })+ || !await hasBranchMergeEvidence(parentRepo, wt.head, target).catch(() => false)) return false;+ const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');+ if (await readBranchCompletionHold({ repoPath: parentRepo, branch: branchName, retirement: true })) return false;const ok = await execGit(['worktree', 'remove', worktreePath], parentRepo).then(() => true).catch(err => {console.warn(`⚠️ Preserved external worktree ${entry.name}: ${err.message}`);return false;});- if (ok) {- await execGit(['branch', '-D', branchName], parentRepo).catch(err => {- console.warn(`⚠️ External branch cleanup failed for ${branchName}: ${err.message}`);- });+ if (ok && !await deleteCompletedLocalBranch(parentRepo, branchName, wt.head)) {+ console.warn(`⚠️ External branch ${branchName} retained: head changed, new holder, or deletion refused`);}return ok;},diff --git a/server/services/worktreeManager.recovery.test.js b/server/services/worktreeManager.recovery.test.jsindex 4d7194c8e7..63d19f571d 100644--- a/server/services/worktreeManager.recovery.test.js+++ b/server/services/worktreeManager.recovery.test.js@@ -1,5 +1,5 @@import { afterAll, describe, expect, it, vi } from 'vitest';-import { mkdir, writeFile, rm, readFile } from 'fs/promises';+import { mkdir, writeFile, rm, readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot, mockTestIdentity } from '../lib/mockPathsDataRoot.js';@@ -8,16 +8,18 @@ import { execGit } from '../lib/execGit.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-worktree-recovery-' });vi.mock('../lib/fileUtils.js', async importOriginal => makeProxy(await importOriginal()));+vi.mock('../lib/paths.js', async importOriginal => makeProxy(await importOriginal()));vi.mock('./instanceIdentity.js', () => mockTestIdentity());const { PATHS } = await import('../lib/fileUtils.js');const { removeWorktree, adoptWorktree, createWorktree } = await import('./worktreeManager.js');afterAll(cleanup);describe.skipIf(SKIP_HEAVY_INTEGRATION)('failed worktree cleanup recovery', () => {- it('keeps the only committed copy recoverable when cleanup runs again after removing its checkout', async () => {+ it('retains unfinished work across callbacks and recovers a checkout removed by an earlier workflow', async () => {const repo = join(tempRoot, 'source');await materializeGitRepo(repo);await mkdir(PATHS.worktrees, { recursive: true });+ await writeFile(join(PATHS.cos, 'state.json'), JSON.stringify({ agents: {} }));const branch = 'cos/recovery/agent-example';const worktree = join(PATHS.worktrees, 'agent-example');await execGit(['worktree', 'add', '-b', branch, worktree, 'main'], repo);@@ -26,8 +28,19 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('failed worktree cleanup recovery', () =await execGit(['commit', '-m', 'unpublished work'], worktree);const options = { merge: false, preserveBranchWithCommits: true };- expect((await removeWorktree('agent-example', repo, branch, options)).removed).toBe(true);- expect((await removeWorktree('agent-example', repo, branch, options)).removed).toBe(true);+ for (let attempt = 0; attempt < 2; attempt++) {+ expect(await removeWorktree('agent-example', repo, branch, options)).toMatchObject({+ removed: false, warnings: expect.arrayContaining([expect.stringContaining('merge-evidence-unavailable')]),+ });+ expect(await readFile(join(worktree, 'recoverable.txt'), 'utf8')).toBe('unpublished agent work\n');+ }++ // Older workflows removed the checkout before preserving its branch. Model+ // that already-completed removal only inside this disposable repository.+ await execGit(['worktree', 'remove', worktree], repo);+ expect(await removeWorktree('agent-example', repo, branch, options)).toMatchObject({+ removed: true, warnings: expect.arrayContaining([expect.stringContaining('merge evidence was not established')]),+ });// A retry can attach a new checkout and read the authored file, without// reflog surgery or a remote branch that the failed run never pushed.@@ -38,8 +51,16 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('failed worktree cleanup recovery', () =// Once that retry lands, both its first cleanup and any later completion// callback must report success without inventing a preserved branch.await execGit(['merge', branch, '--no-edit'], repo);+ const reflog = await readFile(join(repo, '.git', 'logs', 'refs', 'heads', ...branch.split('/')));expect(await removeWorktree('agent-retry', repo, branch, options)).toMatchObject({ removed: true, warnings: [] });expect(await removeWorktree('agent-retry', repo, branch, options)).toMatchObject({ removed: true, warnings: [] });+ const archiveRoot = join(PATHS.cos, 'branch-retirement-archives');+ const archives = await readdir(archiveRoot);+ expect(archives).toHaveLength(1);+ expect(await readFile(join(archiveRoot, archives[0], 'reflog'))).toEqual(reflog);+ await expect(execGit(['bundle', 'verify', join(archiveRoot, archives[0], 'commits.bundle')], repo))+ .resolves.toMatchObject({ exitCode: 0 });+ expect((await execGit(['show-ref', '--verify', `refs/heads/${branch}`], repo, { ignoreExitCode: true })).exitCode).not.toBe(0);});});diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 3dba413b51..93ee38392a 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -3,6 +3,14 @@ import { dirname, join } from 'path';// Stub every git operation; lifecycle tests exercise the real service without// creating, changing or removing a live repository.+const preserveCheckoutMock = vi.fn(async () => ({ archiveDir: '/archive', verify: async () => null }));+const preserveBranchMock = vi.fn(async () => ({ archiveDir: '/branch-archive', verify: async () => true }));+vi.mock('../lib/branchRetirementArchive.js', () => ({ preserveBranchRetirement: (...args) => preserveBranchMock(...args) }));+vi.mock('./heldCheckoutRecovery.js', () => ({ preserveMergedCheckout: (...args) => preserveCheckoutMock(...args) }));+const completionOwnersMock = vi.fn(async () => []);+vi.mock('./cosClaimOwnershipState.js', async importOriginal => ({ ...await importOriginal(), readClaimOwnershipAgents: (...args) => completionOwnersMock(...args) }));+const completionHoldMock = vi.fn(async () => null);+vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: (...args) => completionHoldMock(...args) }));const execGitMock = vi.fn();vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));@@ -38,6 +46,7 @@ vi.mock('./git.js', () => ({const {shouldRefuseDefaultBranchMerge,+ deleteCompletedLocalBranch,isHumanClaimWorktree,classifyWorktreeDirt,isGitLockError,@@ -62,6 +71,27 @@ const { existsSync, realpathSync } = await import('fs');const { lstat, readdir, rm, stat, readlink, symlink, unlink } = await import('fs/promises');const { PATHS } = await import('../lib/fileUtils.js');+describe('completed branch archival boundary', () => {+ const head = 'a'.repeat(40);+ beforeEach(() => {+ execGitMock.mockReset().mockImplementation(async args => ({+ stdout: args.includes('--git-common-dir') ? '/repo/.git' : '', exitCode: 0,+ }));+ getDefaultBranchMock.mockResolvedValue('main');+ preserveBranchMock.mockReset().mockResolvedValue({ archiveDir: '/branch-archive', verify: async () => true });+ });+ afterEach(() => {+ preserveBranchMock.mockReset().mockResolvedValue({ archiveDir: '/branch-archive', verify: async () => true });+ });+ it.each(['archive failure', 'archive verification failure'])('never sends the deletion when there is an %s', async failure => {+ if (failure === 'archive failure') preserveBranchMock.mockRejectedValue(new Error('archive disk full'));+ else preserveBranchMock.mockResolvedValue({ archiveDir: '/branch-archive', verify: async () => false });+ expect(await deleteCompletedLocalBranch('/repo', 'done', head)).toBe(false);+ expect(preserveBranchMock).toHaveBeenCalledWith('/repo', '/repo/.git', 'done', head);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+});+describe('Worktree dependency preparation', () => {const directories = ['client', 'server', 'admin', 'uninstalled', 'assets', '.hidden', 'node_modules', 'nested'];const missing = () => Promise.reject(Object.assign(new Error('missing'), { code: 'ENOENT' }));@@ -683,8 +713,13 @@ describe('removeWorktree identity, dirt and branch preservation', () => {// mocked `hasBranchMergeEvidence` (see the ./git.js mock at the top of this file).function scriptGit({ porcelain = '', remoteTargetResolves = true, detectedToplevel } = {}) {execGitMock.mockReset();+ let registered = true;execGitMock.mockImplementation((args, cwd) => {const [sub] = args;+ if (sub === 'worktree' && args[1] === 'list') return Promise.resolve({ stdout: registered ? `worktree ${join(PATHS.worktrees, 'agent-x')}\nHEAD ${'a'.repeat(40)}\nbranch refs/heads/cos/task-1/agent-x\n` : '', exitCode: 0 });+ if (sub === 'worktree' && args[1] === 'remove') registered = false;+ if (sub === 'rev-parse' && args[1] === '--path-format=absolute') return Promise.resolve({ stdout: '/repo/.git', exitCode: 0 });+ if (sub === 'rev-parse' && args[1] === '--verify' && String(args[2]).startsWith('refs/heads/')) return Promise.resolve({ stdout: 'a'.repeat(40), exitCode: 0 });// Whether this clone has an `origin/<default>` to prefer over the local branch.if (sub === 'rev-parse' && args[1] === '--verify' && String(args[2]).startsWith('origin/')) {return Promise.resolve({ stdout: remoteTargetResolves ? 'deadbeef' : '', stderr: '', exitCode: remoteTargetResolves ? 0 : 1 });@@ -705,11 +740,14 @@ describe('removeWorktree identity, dirt and branch preservation', () => {execGitMock.mock.calls.some(([args]) => JSON.stringify(args) === JSON.stringify(subcommandArgs));beforeEach(() => {+ preserveCheckoutMock.mockReset().mockResolvedValue({ archiveDir: '/archive', verify: async () => null });+ completionHoldMock.mockReset().mockResolvedValue(null);+ completionOwnersMock.mockReset().mockResolvedValue([]);getDefaultBranchMock.mockResolvedValue('main');// mockReset (not just mockResolvedValue): the opt-in test asserts the merged// check was NOT consulted, so recorded calls must not leak in from a prior test.hasBranchMergeEvidenceMock.mockReset();- hasBranchMergeEvidenceMock.mockResolvedValue(false);+ hasBranchMergeEvidenceMock.mockResolvedValue(true);existsSync.mockReset().mockReturnValue(true);realpathSync.mockReset().mockImplementation(p => p);realpathSync.native = realpathSync;@@ -738,7 +776,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.warnings.join(' ')).toMatch(/preserved.*retry/i);expect(rm).not.toHaveBeenCalled();expect(calledWith(['worktree', 'remove', join(PATHS.worktrees, 'agent-x'), '--force'])).toBe(false);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(calledWith(['merge', 'cos/task-1/agent-x', '--no-edit'])).toBe(false);});@@ -782,7 +820,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: true });expect(result.removed).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);});it('attempts and records a merge after a verified positive commit count', async () => {@@ -796,7 +834,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result).toMatchObject({ merged: true, removed: true });expect(calledWith(['merge', 'cos/task-1/agent-x', '--no-edit'])).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);});it('preserves a branch after a verified positive count and failed merge', async () => {@@ -812,7 +850,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(true);expect(result.merged).toBe(false);expect(calledWith(['merge', 'cos/task-1/agent-x', '--no-edit'])).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});afterEach(() => {@@ -840,7 +878,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result).toMatchObject({ merged: false, removed: false, cleanupIncomplete: true });expect(result.warnings.join(' ')).toMatch(/cleanup incomplete.*directory still present.*retryable/);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('keeps `merged` accurate for the publication outcome while still refusing to claim removal', async () => {@@ -855,27 +893,28 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(false);expect(result.merged).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('verifies a missing directory whose registration is stale instead of assuming it is gone', async () => {existsSync.mockReturnValue(false);const path = join(PATHS.worktrees, 'agent-x');let pruned = false;- execGitMock.mockImplementation((args) => {+ const scripted = execGitMock.getMockImplementation();+ execGitMock.mockImplementation((args, ...rest) => {if (args[0] === 'worktree' && args[1] === 'prune') pruned = true;if (args[0] === 'worktree' && args[1] === 'remove') return Promise.reject(new Error('is not a working tree'));if (args[0] === 'worktree' && args[1] === 'list') {- return Promise.resolve({ stdout: pruned ? '' : `worktree ${path}\nHEAD abc\nbranch refs/heads/cos/task-1/agent-x\nprunable\n` });+ return Promise.resolve({ stdout: pruned ? '' : `worktree ${path}\nHEAD ${'a'.repeat(40)}\nbranch refs/heads/cos/task-1/agent-x\nprunable\n` });}- return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ return scripted(args, ...rest);});const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });expect(result.removed).toBe(true);expect(pruned).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);});it('does not report an already-gone directory as removed while its registration survives', async () => {@@ -890,7 +929,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });expect(result).toMatchObject({ removed: false, cleanupIncomplete: true });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('persistent removal reports the survivor and keeps the branch', async () => {@@ -919,7 +958,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result).toMatchObject({ merged: false, removed: false, cleanupIncomplete: true });expect(result.warnings.join(' ')).toContain('broken checkout identity');expect(rm).not.toHaveBeenCalled();- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(execGitMock.mock.calls.some(([args]) => args[0] === 'status')).toBe(false);expect(execGitMock.mock.calls.some(([args]) => args[0] === 'worktree')).toBe(false);});@@ -935,7 +974,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(false);expect(result.warnings.join(' ')).toContain('src/index.js');expect(rm).not.toHaveBeenCalled();- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('preserves authored work when only native realpath unifies the Git and Node directory spellings', async () => {@@ -951,7 +990,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(false);expect(result.warnings.join(' ')).toContain('src/recoverable.js');expect(rm).not.toHaveBeenCalled();- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('prunes a missing checkout registered through an alias of its surviving parent', async () => {@@ -966,7 +1005,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {const scripted = execGitMock.getMockImplementation();execGitMock.mockImplementation((args, ...rest) => {if (args[0] === 'worktree' && args[1] === 'list') {- return Promise.resolve({ stdout: pruned ? '' : `worktree ${alias}\nbranch refs/heads/cos/task-1/agent-x\nprunable\n`, exitCode: 0 });+ return Promise.resolve({ stdout: pruned ? '' : `worktree ${alias}\nHEAD ${'a'.repeat(40)}\nbranch refs/heads/cos/task-1/agent-x\nprunable\n`, exitCode: 0 });}if (args[0] === 'worktree' && args[1] === 'remove') return Promise.reject(new Error('missing checkout'));if (args[0] === 'worktree' && args[1] === 'prune') pruned = true;@@ -979,7 +1018,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(true);expect(pruned).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);});it('preserves work when identity lookup and status both fail', async () => {@@ -994,7 +1033,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(result.removed).toBe(false);expect(result.warnings.join(' ')).toContain('git status failed');expect(rm).not.toHaveBeenCalled();- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);});it('discards only lockfile churn before removing the worktree', async () => {@@ -1024,12 +1063,75 @@ describe('removeWorktree identity, dirt and branch preservation', () => {});+ it.each([+ ['main', 'main', 'protected-branch'],+ ['release', 'main', 'protected-branch'],+ ['trunk', 'trunk', 'protected-branch'],+ ['cos/task-1/agent-x', null, 'default-branch-unavailable'],+ ])('retains %s before trusting erroneous cleanup metadata (default %s)', async (branch, base, reason) => {+ getDefaultBranchMock.mockResolvedValue(base);+ const result = await removeWorktree('agent-x', '/repo', branch, { merge: true });+ expect(result.removed).toBe(false);+ expect(result.warnings.join(' ')).toContain(reason);+ expect(preserveCheckoutMock).not.toHaveBeenCalled();+ expect(execGitMock.mock.calls.some(([args]) => ['merge', 'push', 'checkout'].includes(args[0])+ || (args[0] === 'worktree' && ['remove', 'prune'].includes(args[1])))).toBe(false);+ });++ it.each(['active', 'unreadable', 'arrives-during-archive'])('preserves a finalizing checkout when ownership is %s', async state => {+ const otherOwner = { id: 'agent-other', status: 'running', workspacePath: join(PATHS.worktrees, 'agent-x'), metadata: { sourceWorkspace: '/repo', worktreeBranch: 'cos/task-1/agent-x' } };+ if (state === 'active') completionOwnersMock.mockResolvedValue([otherOwner]);+ if (state === 'unreadable') completionOwnersMock.mockResolvedValue(null);+ if (state === 'arrives-during-archive') preserveCheckoutMock.mockImplementation(async () => {+ completionOwnersMock.mockResolvedValue([otherOwner]);+ return { archiveDir: '/archive', verify: async () => null };+ });+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x');+ expect(result.removed).toBe(false);+ expect(result.warnings.join(' ')).toMatch(/claim-owner/);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push'+ || (args[0] === 'worktree' && args[1] === 'remove'))).toBe(false);+ });++ it.each(['present', 'missing', 'lockfile'])('retains %s checkout evidence when archival fails', async state => {+ if (state === 'missing') existsSync.mockReturnValue(false);+ if (state === 'lockfile') scriptGit({ porcelain: ' M package-lock.json' });+ preserveCheckoutMock.mockRejectedValue(new Error('archive disk full'));+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x');+ expect(result.removed).toBe(false);+ expect(result.warnings.join(' ')).toContain('archive disk full');+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'checkout' || args[0] === 'push'+ || (args[0] === 'worktree' && ['remove', 'prune'].includes(args[1])))).toBe(false);+ expect(rm).not.toHaveBeenCalled();+ });++ it('retains checkout and ref when preserved bytes change before removal', async () => {+ preserveCheckoutMock.mockResolvedValue({ archiveDir: '/archive', verify: async () => 'checkout-content-changed' });+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x');+ expect(result.removed).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push'+ || (args[0] === 'worktree' && args[1] === 'remove'))).toBe(false);+ });++ it('rechecks manual completion policy before deleting the remaining branch', async () => {+ const scripted = execGitMock.getMockImplementation();+ execGitMock.mockImplementation((args, ...rest) => {+ if (args[0] === 'worktree' && args[1] === 'remove') completionHoldMock.mockResolvedValue('manual-pr-completion');+ return scripted(args, ...rest);+ });+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x');+ expect(result.removed).toBe(true);+ expect(result.warnings.join(' ')).toContain('manual-pr-completion');+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);+ });+it('KEEPS the branch when it is not yet merged into the default branch', async () => {+ hasBranchMergeEvidenceMock.mockResolvedValue(false);const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {merge: false, preserveBranchWithCommits: true,});- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(result.warnings.join(' ')).toMatch(/preserved/i);});@@ -1051,24 +1153,25 @@ describe('removeWorktree identity, dirt and branch preservation', () => {merge: false, preserveBranchWithCommits: true,});- expect(result.removed).toBe(checkout === 'missing');- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(checkout === 'missing' && evidence === true);+ expect(result.removed).toBe(checkout === 'missing' && evidence === true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(checkout === 'missing' && evidence === true);if (evidence !== true) expect(result.warnings.join(' ')).toMatch(/preserved/);});it('preserves unlanded commits when the requested merge cannot use a checkout', async () => {+ hasBranchMergeEvidenceMock.mockResolvedValue(false);const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: true });- expect(result).toMatchObject({ merged: false, removed: checkout === 'missing' });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(result).toMatchObject({ merged: false, removed: false });+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(result.warnings.join(' ')).toMatch(/preserved/);});- it('only honors explicit branch disposal when the checkout is proven absent', async () => {+ it('requires merge proof even when the checkout directory is absent', async () => {await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(checkout === 'missing');- expect(hasBranchMergeEvidenceMock).not.toHaveBeenCalled();+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(checkout === 'missing');+ if (checkout === 'missing') expect(hasBranchMergeEvidenceMock).toHaveBeenCalled();});it('preserves the branch when its existence probe fails', async () => {@@ -1082,7 +1185,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {merge: false, preserveBranchWithCommits: true,});- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(result.warnings.join(' ')).toMatch(/preserved/);});});@@ -1097,23 +1200,13 @@ describe('removeWorktree identity, dirt and branch preservation', () => {merge: false, preserveBranchWithCommits: true,});- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);});it('calls an empty branch unused instead of already merged', async () => {hasBranchMergeEvidenceMock.mockResolvedValue(true);const log = vi.spyOn(console, 'log').mockImplementation(() => {});- execGitMock.mockImplementation((args, cwd) => {- if (args[0] === 'rev-list') return Promise.resolve({ stdout: '0\n', stderr: '', exitCode: 0 });- if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') {- return Promise.resolve({ stdout: cwd, stderr: '', exitCode: 0 });- }- if (args[0] === 'status') return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });- if (args[0] === 'rev-parse' && args[1] === '--verify') {- return Promise.resolve({ stdout: '', stderr: '', exitCode: 1 });- }- return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });- });+ scriptGit();await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {merge: false, preserveBranchWithCommits: true,@@ -1122,7 +1215,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {const lines = log.mock.calls.flat().join('\n');expect(lines).toContain('has no commits beyond');expect(lines).not.toContain('already merged');- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(true);log.mockRestore();});@@ -1133,7 +1226,7 @@ describe('removeWorktree identity, dirt and branch preservation', () => {merge: false, preserveBranchWithCommits: true,});- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);expect(result.warnings.join(' ')).toMatch(/preserved/i);});@@ -1143,12 +1236,12 @@ describe('removeWorktree identity, dirt and branch preservation', () => {it('refreshes and asks origin/<default>, not the stale local branch', async () => {scriptGit({ remoteTargetResolves: true });- await removeWorktree('agent-x', '/repo', 'claim/issue-7625', {+ await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {merge: false, preserveBranchWithCommits: true,});expect(calledWith(['fetch', 'origin', '--prune'])).toBe(true);- expect(hasBranchMergeEvidenceMock).toHaveBeenCalledWith('/repo', 'claim/issue-7625', 'origin/main');+ expect(hasBranchMergeEvidenceMock).toHaveBeenCalledWith('/repo', 'a'.repeat(40), 'origin/main');});it('falls back to the local branch when origin has no copy of the default', async () => {@@ -1161,12 +1254,12 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(hasBranchMergeEvidenceMock).toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');});- it('is opt-in: without the flag the no-merge path still deletes an unmerged branch', async () => {+ it('retains an unmerged checkout and branch even without the legacy preservation flag', async () => {+ hasBranchMergeEvidenceMock.mockResolvedValue(false);await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);- // The resume gate never consulted the merged check for THIS branch.- expect(hasBranchMergeEvidenceMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' || (args[0] === 'worktree' && args[1] === 'remove'))).toBe(false);+ expect(hasBranchMergeEvidenceMock).toHaveBeenCalled();});// The bare "uncommitted changes detected" message left the user unable to tell@@ -1267,14 +1360,14 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()scriptPaths({ source: false });await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();- expect(execGitMock).not.toHaveBeenCalled();+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([]);});it('refuses to clobber an occupied destination', async () => {scriptPaths({ target: true });await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();- expect(execGitMock).not.toHaveBeenCalled();+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([]);});// git refuses to move a locked worktree or one with initialized submodules —@@ -1303,7 +1396,7 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()const result = await adoptWorktree('agent-new', '/repo', NEW_TREE, 'cos/task-1/agent-dead');- expect(execGitMock).toHaveBeenCalledExactlyOnceWith(['status', '--porcelain', '--untracked-files=no'], NEW_TREE);+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([[['status', '--porcelain', '--untracked-files=no'], NEW_TREE]]);expect(result).toMatchObject({ worktreePath: NEW_TREE, adopted: true });});@@ -1340,20 +1433,20 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()execGitMock.mockResolvedValue({ stdout: Array.from({ length: 100 }, (_, i) => ` D file-${i}`).join('\n') });await expect(adoptWorktree('agent-new', '/repo', NEW_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();- expect(execGitMock).toHaveBeenCalledExactlyOnceWith(['status', '--porcelain', '--untracked-files=no'], NEW_TREE);+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([[['status', '--porcelain', '--untracked-files=no'], NEW_TREE]]);});it('preserves the tree when its status cannot be inspected', async () => {execGitMock.mockRejectedValue(new Error('index unreadable'));await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();- expect(execGitMock).toHaveBeenCalledExactlyOnceWith(['status', '--porcelain', '--untracked-files=no'], DEAD_TREE);+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([[['status', '--porcelain', '--untracked-files=no'], DEAD_TREE]]);});it('returns null on incomplete input instead of guessing', async () => {await expect(adoptWorktree(null, '/repo', DEAD_TREE, 'b')).resolves.toBeNull();await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, null)).resolves.toBeNull();- expect(execGitMock).not.toHaveBeenCalled();+ expect(execGitMock.mock.calls.filter(([args]) => args[0] !== 'rev-parse')).toEqual([]);});});@@ -1611,6 +1704,8 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {lstat.mockReset().mockRejectedValue(Object.assign(new Error('gone'), { code: 'ENOENT' }));rm.mockClear();getDefaultBranchMock.mockResolvedValue('main');+ hasBranchMergeEvidenceMock.mockResolvedValue(true);+ completionHoldMock.mockResolvedValue(null);execGitMock.mockReset();});@@ -1635,7 +1730,7 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {// verified against the registration afterwards.const removedPaths = new Set();const listing = () => entries.filter(entry => !removedPaths.has(entry.path)).flatMap(entry => [- 'worktree ' + entry.path, 'HEAD abc123',+ 'worktree ' + entry.path, 'HEAD ' + 'a'.repeat(40),entry.detached ? 'detached' : 'branch refs/heads/' + entry.branch,...(entry.locked ? ['locked protected'] : []), '',]).join('\n');@@ -1647,7 +1742,7 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {execGitMock.mockImplementation((args, cwd) => {if (args[0] === 'worktree' && args[1] === 'list') return Promise.resolve({ stdout: listing() });if (args[0] === 'worktree' && args[1] === 'remove') removedPaths.add(args[2]);- if (args[0] === 'rev-parse') return Promise.resolve({ stdout: args[1] === '--show-toplevel' ? cwd : 'main' });+ if (args[0] === 'rev-parse') return Promise.resolve({ stdout: args[1] === '--show-toplevel' ? cwd : args[1] === '--path-format=absolute' ? '/repo/.git' : args[1] === '--verify' ? 'a'.repeat(40) : 'main', exitCode: 0 });if (args[0] === 'status') return Promise.resolve({ stdout: cwd === tree('agent-dirty') ? ' M src/work.js' : '' });if (args[0] === 'rev-list') return Promise.resolve({ stdout: '0', stderr: '', exitCode: 0 });return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });@@ -1656,8 +1751,8 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {expect(await cleanupOrphanedWorktrees('/repo', new Set(['agent-active']), { claimOwners: { agents: [] } })).toBe(1);expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'worktree' && args[1] === 'remove')).toEqual([[['worktree', 'remove', tree('agent-dead'), '--force'], '/repo', { timeout: WORKTREE_ADD_TIMEOUT_MS }]]);- expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'branch' && args[1] === '-D'))- .toEqual([[['branch', '-D', 'cos/task/agent-dead'], '/repo']]);+ expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'push').map(([args]) => args.at(-1)))+ .toEqual([':refs/heads/cos/task/agent-dead']);expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'status').map(([, cwd]) => cwd)).toEqual([tree('agent-dead'), tree('agent-dirty')]);expect(rm).not.toHaveBeenCalled();@@ -1677,10 +1772,10 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {// CoS dispatches agent-late after the job snapshot, before this pass reaches its tree.live.add('agent-late');return Promise.resolve({ stdout: entries.filter(e => !removedPaths.has(e.path))- .flatMap(e => ['worktree ' + e.path, 'HEAD abc123', 'branch refs/heads/' + e.branch, '']).join('\n') });+ .flatMap(e => ['worktree ' + e.path, 'HEAD ' + 'a'.repeat(40), 'branch refs/heads/' + e.branch, '']).join('\n') });}if (args[0] === 'worktree' && args[1] === 'remove') removedPaths.add(args[2]);- if (args[0] === 'rev-parse') return Promise.resolve({ stdout: args[1] === '--show-toplevel' ? cwd : 'main' });+ if (args[0] === 'rev-parse') return Promise.resolve({ stdout: args[1] === '--show-toplevel' ? cwd : args[1] === '--path-format=absolute' ? '/repo/.git' : args[1] === '--verify' ? 'a'.repeat(40) : 'main', exitCode: 0 });if (args[0] === 'rev-list') return Promise.resolve({ stdout: '0', stderr: '', exitCode: 0 });return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });});@@ -1689,13 +1784,13 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {expect(await cleanupOrphanedWorktrees('/repo', () => new Set(live), { claimOwners })).toBe(1);expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'worktree' && args[1] === 'remove')).toEqual([[['worktree', 'remove', tree('agent-dead'), '--force'], '/repo', { timeout: WORKTREE_ADD_TIMEOUT_MS }]]);- expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'branch' && args[1] === '-D'))- .toEqual([[['branch', '-D', 'cos/task/agent-dead'], '/repo']]);+ expect(execGitMock.mock.calls.filter(([args]) => args[0] === 'push').map(([args]) => args.at(-1)))+ .toEqual([':refs/heads/cos/task/agent-dead']);});it('holds every tree when the agent registry cannot be read', async () => {execGitMock.mockImplementation((args) => args[0] === 'worktree' && args[1] === 'list'- ? Promise.resolve({ stdout: ['worktree ' + tree('agent-dead'), 'HEAD abc123', 'branch refs/heads/cos/task/agent-dead', ''].join('\n') })+ ? Promise.resolve({ stdout: ['worktree ' + tree('agent-dead'), 'HEAD ' + 'a'.repeat(40), 'branch refs/heads/cos/task/agent-dead', ''].join('\n') }): Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }));expect(await cleanupOrphanedWorktrees('/repo', () => new Set(), { claimOwners: { agents: null } })).toBe(0);diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.jsindex c9d4f0fa81..89380c65bd 100644--- a/server/services/worktreeReap.test.js+++ b/server/services/worktreeReap.test.js@@ -10,8 +10,8 @@* Repos are copied from the shared `gitTestRepo.js` template. The whole file* is excluded from `npm run test:fast` (`VITEST_FAST=1`).*/-import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';-import { mkdtemp, rm, writeFile, mkdir, chmod } from 'fs/promises';+import { describe, it, expect, beforeAll, beforeEach, afterEach, afterAll, vi } from 'vitest';+import { mkdtemp, rm, writeFile, readFile, readdir, mkdir, chmod } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -22,8 +22,13 @@ import {resetGitWorktreeSandbox,SKIP_HEAVY_INTEGRATION,} from '../lib/gitTestRepo.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-reap-archives-') }));+afterAll(cleanupTempDataRoots);+import { PATHS } from '../lib/paths.js';+import { preserveBranchRetirement } from '../lib/branchRetirementArchive.js';import { hasBranchMergeEvidence } from './git.js';-import { reapMergedWorktrees } from './worktreeManager.js';+import { reapMergedWorktrees, deleteCompletedLocalBranch } from './worktreeManager.js';vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: async () => null }));vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: {} }) }));@@ -68,6 +73,133 @@ async function initRepo() {return { dir, safePath };}+describe.skipIf(SKIP_HEAVY_INTEGRATION)('local completed ref retirement', () => {+ let dir;+ beforeEach(async () => { ({ dir } = await initRepo()); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); });++ it('uses an exact-head lease and native holder refusal for a late attachment', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ const path = join(dir, 'late-holder');+ await execGit(['worktree', 'add', path, 'done'], dir);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ await execGit(['worktree', 'remove', path], dir);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(true);+ });++ it('retains a branch that advanced after the merge proof', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ await commitFile(dir, 'new.txt', 'new work', 'new work');+ const advanced = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();+ await execGit(['update-ref', 'refs/heads/done', advanced, head], dir);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(advanced);+ });++ it('retains protected and custom default refs even without holders', async () => {+ await execGit(['branch', 'release'], dir);+ await execGit(['branch', 'trunk'], dir);+ const head = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();+ await execGit(['update-ref', 'refs/remotes/origin/trunk', head], dir);+ await execGit(['symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/trunk'], dir);+ for (const branch of ['release', 'trunk']) {+ expect(await deleteCompletedLocalBranch(dir, branch, head)).toBe(false);+ expect((await execGit(['rev-parse', branch], dir)).stdout.trim()).toBe(head);+ }+ });++ it('retains a ref when the repository default cannot be established', async () => {+ await execGit(['branch', '-m', 'main', 'trunk'], dir);+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ });++ it('preserves the full shared branch reflog and orphaned historical commit objects without a checkout', async () => {+ await execGit(['checkout', '-b', 'done'], dir);+ await commitFile(dir, 'history.txt', 'original evidence', 'original commit');+ const original = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();+ await writeFile(join(dir, 'history.txt'), 'amended evidence');+ await execGit(['add', 'history.txt'], dir);+ await execGit(['commit', '--amend', '-m', 'amended commit'], dir);+ const head = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();+ await execGit(['checkout', 'main'], dir);+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)).stdout.trim();+ const reflog = join(common, 'logs', 'refs', 'heads', 'done');+ const evidence = await readFile(reflog);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(true);+ expect(existsSync(reflog)).toBe(false);+ const archiveRoot = join(PATHS.cos, 'branch-retirement-archives');+ const archives = await Promise.all((await readdir(archiveRoot)).map(async id => ({+ path: join(archiveRoot, id), manifest: JSON.parse(await readFile(join(archiveRoot, id, 'manifest.json'), 'utf8')),+ })));+ const archive = archives.find(entry => entry.manifest.repoPath === dir && entry.manifest.expectedHead === head);+ expect(archive).toBeDefined();+ expect(await readFile(join(archive.path, 'reflog'))).toEqual(evidence);+ expect(archive.manifest.recoveryHeads).toEqual(expect.arrayContaining([original, head]));+ const restored = join(dir, 'restored.git');+ await execGit(['init', '--bare', restored], dir);+ await execGit(['--git-dir', restored, 'fetch', join(archive.path, 'commits.bundle'), '+refs/*:refs/*'], dir);+ expect((await execGit(['--git-dir', restored, 'show', `${original}:history.txt`], dir)).stdout).toBe('original evidence');+ expect((await execGit(['--git-dir', restored, 'show', `${head}:history.txt`], dir)).stdout).toBe('amended evidence');+ });++ it('retains the branch when a reflog recovery object is missing', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)).stdout.trim();+ const log = join(common, 'logs', 'refs', 'heads', 'done');+ await writeFile(log, `${'b'.repeat(40)} ${head} Test <[email protected]> 1 +0000\tmissing historical object\n`);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ expect(await readFile(log, 'utf8')).toContain('missing historical object');+ });++ it('refuses a changed shared reflog even when the branch tip is unchanged', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)).stdout.trim();+ const preserved = await preserveBranchRetirement(dir, common, 'done', head);+ expect(await preserved.verify()).toBe(true);+ const log = join(common, 'logs', 'refs', 'heads', 'done');+ await writeFile(log, `${await readFile(log, 'utf8')}${head} ${head} Test <[email protected]> 1 +0000\tnew recovery evidence\n`);+ expect(await preserved.verify()).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ });++ it.each(['reflog', 'commits.bundle', 'manifest.json'])('refuses an archive whose %s changes before retirement', async name => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)).stdout.trim();+ const preserved = await preserveBranchRetirement(dir, common, 'done', head);+ await writeFile(join(preserved.archiveDir, name), 'changed after archival');+ expect(await preserved.verify()).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ });++ it('holds the branch on archive storage failure', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ const common = (await execGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)).stdout.trim();+ const blocked = join(dir, 'not-a-directory');+ await writeFile(blocked, 'keep');+ await expect(preserveBranchRetirement(dir, common, 'done', head, { cosDir: blocked })).rejects.toThrow();+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ });++ it('preserves the repository receiver deletion policy', async () => {+ await execGit(['branch', 'done'], dir);+ const head = (await execGit(['rev-parse', 'done'], dir)).stdout.trim();+ await execGit(['config', 'receive.denyDeletes', 'true'], dir);+ expect(await deleteCompletedLocalBranch(dir, 'done', head)).toBe(false);+ expect((await execGit(['rev-parse', 'done'], dir)).stdout.trim()).toBe(head);+ });+});+describe.skipIf(SKIP_HEAVY_INTEGRATION)('hasBranchMergeEvidence', () => {let dir;let safePath;