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): preserve uncertain worktree retirement and issue holds
atomantic372b8974e5d1
diff --git a/AGENTS.md b/AGENTS.mdindex f3de8e1f9d..187dcc9297 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -224,6 +224,7 @@ This complements the Security Model (the deployed product) — this section gove- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.- **Before pushing**: inspect branch/upstream and working-tree state, preserve unrelated changes, and commit the intended work. Fetch the workflow's intended base explicitly for comparison; a feature branch's tracking branch is not necessarily the default branch. Integrate it only when needed under the merge policy below. Run `npm run pregate` on the resulting commits, then push. Re-run it after any subsequent rebase; do not blindly pull with autostash.- **Merge ready branches without chasing `main`.** A branch that is behind the default branch may merge when it is conflict-free, required checks pass for its current head, and configured reviews are satisfied. Default-branch movement alone does not invalidate those results or require a rebase, branch update, or another CI run. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk (including semantic overlap without textual conflicts); after changing the head, rerun affected validation and required reviews/checks. Keep implementation, review, and CI concurrent; hold repository merge admission only for the final live-state check, merge attempt, and readback, releasing it before recovery or further CI waits. Never bypass required checks or confuse a queued merge with `MERGED`. This policy overrides mandatory base-sync instructions in delegated slashdo workflows.+- **Finish authorized merges and teardown before reporting success.** When merge is authorized, finish review and required checks, merge, and verify the merge completed. Archive unique content, including untracked and ignored files, before deleting a checkout. Recheck live ownership, release only this task's locks on its completed work, remove its worktree, and delete its explicitly named local branch; never infer the branch to delete from its upstream. Preserve other owners' locks and explicit manual handoffs. If work must remain, name its owner, blocker, and next step in the handoff.- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json` through an immediately-merged pull request; with no local evidence it commits nothing and says so.- **Versioning**: `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.jsindex 3e6ae5f986..76fda4e161 100644--- a/client/src/hooks/useOnDemandTaskToast.js+++ b/client/src/hooks/useOnDemandTaskToast.js@@ -21,6 +21,7 @@ const PARK_REASON_LABELS = {'merged-branches-held-back': 'every remaining branch is already merged and waiting on a protected worktree','no-zombie-issues': 'no stale issues to reconcile','no-actionable-plan-items': 'no unblocked PLAN items',+ 'claim-markers-held': 'local cleanup completed; issue reservation ownership remains unverified','branches-blocked': 'remaining branches or worktrees need attention','owner-state-unavailable': 'ownership state could not be read; reconciliation is paused to protect active work','no-progress': 'remaining items were attempted but did not advance',@@ -130,10 +131,11 @@ export function useOnDemandTaskToast() {// branch-reconcile's breakdown instead names merged branches whose worktree// a protection guard still holds — the park is a wait, not an empty repo, so// the count has to show or the toast reads as "nothing exists".- if (c && (c.heldBranches > 0 || c.heldDetached > 0)) {+ if (c && (c.heldBranches > 0 || c.heldDetached > 0 || c.heldClaims > 0)) {const parts = [];if (c.heldBranches) parts.push(`${c.heldBranches} branch(es) held`);if (c.heldDetached) parts.push(`${c.heldDetached} detached worktree(s) held`);+ if (c.heldClaims) parts.push(`${c.heldClaims} issue reservation(s) unverified`);if (c.unchangedBranches) parts.push(`${c.unchangedBranches} branch(es) still blocked`);const causes = formatSkipCauses(data?.skipCauses);countSuffix = ` (${parts.join(', ')}${causes ? ` — ${causes}` : ''})`;diff --git a/client/src/hooks/useOnDemandTaskToast.test.jsx b/client/src/hooks/useOnDemandTaskToast.test.jsxindex 61141527dd..b426f09350 100644--- a/client/src/hooks/useOnDemandTaskToast.test.jsx+++ b/client/src/hooks/useOnDemandTaskToast.test.jsx@@ -112,6 +112,16 @@ describe('useOnDemandTaskToast — parked outcome', () => {expect(toastSpy.mock.calls[0][0]).toMatch(/did not advance.*4 branch\(es\) still blocked/);});+ it('distinguishes unverified issue reservations from branches already cleaned locally', () => {+ renderHook(() => useOnDemandTaskToast());+ fire({ taskType: 'branch-reconcile', outcome: 'parked', parkReason: 'claim-markers-held',+ counts: { heldBranches: 0, heldDetached: 0, heldClaims: 1 },+ skipCauses: { 'claim-reservation-owner-unverified': 1 } });+ const message = toastSpy.mock.calls[0][0];+ expect(message).toMatch(/local cleanup completed.*1 issue reservation\(s\) unverified/);+ expect(message).not.toMatch(/branch\(es\) held|nothing to do/);+ });+it('shows typed branch holds and an automatic retry only when the server confirms eligibility', () => {renderHook(() => useOnDemandTaskToast());fire({ taskType: 'branch-reconcile', outcome: 'parked', parkReason: 'branches-blocked',diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.jsindex 312846cd96..1f67c98eed 100644--- a/server/lib/claimContinuation.js+++ b/server/lib/claimContinuation.js@@ -400,7 +400,8 @@ export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace,* @returns {'claim-owner-active'|'claim-owner-ambiguous'|'claim-ownership-unreadable'|null}*/export function claimCheckoutOwnerReason({ branchName, holderPath = null, sourceWorkspace, agents, ignoreIds = [] }) {- if (!Array.isArray(agents) || !branchName) return 'claim-ownership-unreadable';+ if (!Array.isArray(agents) || !branchName+ || agents.some(agent => !agent || !['running', 'paused', 'completed'].includes(agent.status))) return 'claim-ownership-unreadable';const occupancy = claimHolderOccupancy({agents, holderPath, branchName, sourceWorkspace, ignoreIds: new Set(ignoreIds.filter(Boolean)),});diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.jsindex 0042baa678..1946fd8260 100644--- a/server/services/branchCompletionPolicy.js+++ b/server/services/branchCompletionPolicy.js@@ -93,10 +93,6 @@ function completionDecision({ repoPath, branch, prUrl, tip, agents }) {return { release, obligation, reason: handoff ? held : 'pr-completion-review-required' };}-export function branchCompletionHold(input) {- return completionDecision(input).reason;-}-export async function readBranchCompletionHold(input, deps = {}) {const readPolicies = deps.readPolicies || readBranchCompletionPolicies;const agents = input.agents ?? await readPolicies().catch(() => null);diff --git a/server/services/branchCompletionPolicy.test.js b/server/services/branchCompletionPolicy.test.jsindex 96f66aadfb..017f7a58c1 100644--- a/server/services/branchCompletionPolicy.test.js+++ b/server/services/branchCompletionPolicy.test.js@@ -39,7 +39,7 @@ vi.mock('./worktreeManager.js', () => ({ listWorktrees: async () => [], classifyimport { spawnReviewLoopFollowUp } from './agentWorktreeCleanup.js';import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';-import { branchCompletionHold, readBranchCompletionHold, readBranchCompletionPolicies, recordBranchCompletionPolicy } from './branchCompletionPolicy.js';+import { readBranchCompletionHold, readBranchCompletionPolicies, recordBranchCompletionPolicy } from './branchCompletionPolicy.js';import { gatherBranchState, classifyBranches, filterActionable, formatInFlightForPrompt } from './branchReconcile.js';import { checkReconcileOwnership } from './cosClaimOwnership.js';@@ -51,7 +51,7 @@ function register(id, completion, startedAt = '2026-01-01T00:00:00Z', extra = {}runtime.agents[id] = { id, status: 'completed', startedAt, completedAt: startedAt, result: { success: true }, metadata };return assigned;}-const snapshotHold = agents => branchCompletionHold({ repoPath, branch, prUrl, tip: runtime.tip, agents });+const snapshotHold = agents => readBranchCompletionHold({ repoPath, branch, prUrl, tip: runtime.tip, agents });const recheck = () => checkReconcileOwnership({ appId: 'example', branch }, {getAppById: async () => ({ repoPath }), listWorktrees: async () => [], getAgents: async () => [], getActiveAgentIds: () => [],});@@ -169,11 +169,11 @@ describe('completion policy across lifecycle and reconciliation boundaries', ()const grant = register('agent-merge', 'merge-on-green', '2026-01-01T00:00:00Z', { reviewLoopFollowUp: true, reviewLoopPRBranch: branch, reviewLoopPRUrl: prUrl });runtime.agents['agent-merge'].completedAt = '2026-01-03T00:00:00Z';await recordBranchCompletionPolicy({ agentId: 'agent-merge', task: grant, repoPath, branch, prUrl });- expect(snapshotHold(Object.values(runtime.agents))).toBe('pr-completion-human-handoff');+ expect(await snapshotHold(Object.values(runtime.agents))).toBe('pr-completion-human-handoff');runtime.agents['agent-merge'].startedAt = '2026-01-03T00:00:00Z';runtime.remoteTip = 'b'.repeat(40);await recordBranchCompletionPolicy({ agentId: 'agent-merge', task: grant, repoPath, branch, prUrl });- expect(snapshotHold(Object.values(runtime.agents))).toBe('pr-completion-human-handoff');+ expect(await snapshotHold(Object.values(runtime.agents))).toBe('pr-completion-human-handoff');await recordBranchCompletionPolicy({ agentId: 'agent-human', task: grant, repoPath, branch, prUrl });expect(runtime.agents['agent-human'].metadata.branchCompletionPolicy.completion).toBe('leave-open');});@@ -184,9 +184,9 @@ describe('completion policy across lifecycle and reconciliation boundaries', ()const grant = register('agent-merge', 'merge-on-green', '2026-01-02T00:00:00Z', { reviewLoopFollowUp: true, reviewLoopPRBranch: branch, reviewLoopPRUrl: prUrl });await recordBranchCompletionPolicy({ agentId: 'agent-merge', task: grant, repoPath, branch, prUrl });register('agent-review', 'review-then-merge', '2026-01-03T00:00:00Z');- expect(snapshotHold(Object.values(runtime.agents))).not.toBeNull();- expect(branchCompletionHold({ repoPath, branch, prUrl: `${prUrl}0`, tip: runtime.tip, agents: [runtime.agents['agent-human']] })).toBeNull();- expect(branchCompletionHold({ repoPath: '/other', branch, prUrl, agents: Object.values(runtime.agents) })).toBeNull();+ expect(await snapshotHold(Object.values(runtime.agents))).not.toBeNull();+ expect(await readBranchCompletionHold({ repoPath, branch, prUrl: `${prUrl}0`, tip: runtime.tip, agents: [runtime.agents['agent-human']] })).toBeNull();+ expect(await readBranchCompletionHold({ repoPath: '/other', branch, prUrl, agents: Object.values(runtime.agents) })).toBeNull();});it.each(['missing-index', 'corrupt-index', 'missing-record', 'untrusted-state'])('holds when policy storage is %s', async failure => {diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 0718c64195..80ea66245f 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -27,7 +27,7 @@ import { join } from 'node:path';import { isHostShuttingDown } from '../lib/hostShutdown.js';import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';import { execGit } from '../lib/execGit.js';-import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';+import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees, readWorktreeStatus } from './worktreeManager.js';import { isAgentWorktreeId, isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';import { execGh, ensureForgeReachable, getIssueDispatchHint } from './github.js';import { resolveForgeExecOptions } from './forgeExecOptions.js';@@ -41,7 +41,7 @@ import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';import { ledgerPath, readVerdictLedger, partitionSuperseded, recordVerdictInstruction, recordVerdict, sameDirtyPaths } from './supersededLedger.js';import { backupSupersededBranch } from './supersededBackup.js';import { claimCheckoutOwnerReason, RECONCILE_AGENT_ID_PLACEHOLDER } from '../lib/claimContinuation.js';-import { withClaimOwnershipLock } from './cosClaimOwnership.js';+import { withClaimOwnershipLock, readClaimOwnershipAgents } from './cosClaimOwnership.js';import { agentApiCurl } from '../lib/agentApiToken.js';import { localApiBaseUrl } from '../lib/networkExposure.js';@@ -577,7 +577,7 @@ export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds })}/**- * A worktree's real uncommitted paths, or [] when clean/unreadable.+ * A worktree's real uncommitted paths, [] when clean, or null when unreadable.** `classifyWorktreeDirt` subtracts what is not work product — auto-generated* lockfiles and PortOS's own runtime scratch — so this list is only authored@@ -585,22 +585,23 @@ export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds })* the state that dispatches a coordinator agent.** @param {string} worktreePath- * @returns {Promise<string[]>}+ * @returns {Promise<string[]|null>}*/async function worktreeDirtyPaths(worktreePath) {- const { stdout } = await execGit(['status', '--porcelain'], worktreePath, { ignoreExitCode: true })- .catch(() => ({ stdout: '' }));- const dirt = classifyWorktreeDirt(stdout);+ const status = await readWorktreeStatus(worktreePath);+ if (status === null) return null;+ const dirt = classifyWorktreeDirt(status);return dirt.hasRealChanges ? (dirt.realChangePaths || []) : [];}/*** Is a worktree's working tree carrying real (non-lockfile) uncommitted changes?* @param {string} worktreePath- * @returns {Promise<boolean>}+ * @returns {Promise<boolean|null>}*/async function isWorktreeDirty(worktreePath) {- return (await worktreeDirtyPaths(worktreePath)).length > 0;+ const paths = await worktreeDirtyPaths(worktreePath);+ return paths === null ? null : paths.length > 0;}/** Newline-separated git stdout → trimmed non-empty lines. */@@ -940,7 +941,9 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdconst worktreePath = wt?.path || null;const worktreeLocked = Boolean(wt?.locked);const worktreeAge = worktreePath ? await worktreeAgeMs(worktreePath) : null;- const dirtyPaths = worktreePath ? await worktreeDirtyPaths(worktreePath) : [];+ const observedPaths = worktreePath ? await worktreeDirtyPaths(worktreePath) : [];+ const worktreeStatusUnavailable = observedPaths === null;+ const dirtyPaths = observedPaths || [];const worktreeDirty = dirtyPaths.length > 0;const divergence = await gatherDivergence(repoPath, b.name, defaultBranch, dirtyPaths);// getBranches' `merged` is ancestor-based (misses squash/rebase); confirm@@ -983,6 +986,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdworktreeLocked,worktreeAgeMs: worktreeAge,worktreeDirty,+ worktreeStatusUnavailable,dirtyPaths,// Non-null ⇒ somebody owns this branch right now (active CoS agent / live// human claim / locked worktree). Built on the same predicate `cleanupMerged`@@ -994,7 +998,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId// set nor the branch name can see it (#10089).liveOwnerReason: resolveLiveOwnerReason({branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds- }) || claimOwnerReason,+ }) || claimOwnerReason || (worktreeStatusUnavailable ? 'worktree-status-unavailable' : null),claimOwnerReason,behind: divergence.behind,ahead: divergence.ahead,@@ -1013,14 +1017,14 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId* Persist counts and typed causes, with the earliest known hold expiry as the* next possible wake-up; raw cleanup diagnostics stay out of scheduler state.*/-export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [], detachedWorktrees = [], superseded = [], gated = [] } = {}) {+export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [], detachedWorktrees = [], superseded = [], gated = [], claimMarkersHeld = [] } = {}) {// One entry per surviving branch/checkout, even when it appears in both the// skipped and detached/superseded projections. Never persist raw error text.const holds = new Map();const lifts = [];- const add = (entry, rawCause) => {+ const add = (entry, rawCause, key = entry.branch || entry.path) => {const cause = String(rawCause).split(':', 1)[0];- holds.set(entry.branch || entry.path, { ...entry, cause: /^[a-z]+(?:-[a-z]+)*$/.test(cause) ? cause : 'cleanup-failed' });+ holds.set(key, { ...entry, cause: /^[a-z]+(?:-[a-z]+)*$/.test(cause) ? cause : 'cleanup-failed' });for (const deadline of [entry.retryAt, entry.holdRetryAt]) {const timestamp = Date.parse(deadline);if (Number.isFinite(timestamp)) lifts.push(timestamp);@@ -1036,16 +1040,20 @@ export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [for (const entry of wip) add(entry, entry.openPr?.isDraft ? 'draft-review-required' : entry.liveOwnerReason || entry.completionPolicyReason || 'unfinished-work');for (const entry of heldLive) if (!holds.has(entry.branch || entry.path)) add(entry, entry.liveOwnerReason || 'live-owner');for (const entry of gated) add(entry, entry.openPr?.isDraft ? 'draft-review-required' : 'action-disabled');+ // Marker cleanup is distinct from successful local branch retirement.+ for (const entry of claimMarkersHeld) add({ ...entry, claimMarker: true }, entry.reason || 'claim-marker-held', `claim-marker:${entry.issue ?? entry.branch}`);const entries = [...holds.values()];const heldBackMerged = skipped.filter(s => !s.detached && s.reason?.startsWith('worktree-'));const skipCauses = {};for (const entry of entries) skipCauses[entry.cause] = (Object.hasOwn(skipCauses, entry.cause) ? skipCauses[entry.cause] : 0) + 1;const counts = entries.length ? {- heldBranches: entries.filter(entry => !entry.detached && entry.branch).length,- heldDetached: entries.filter(entry => entry.detached || !entry.branch).length,+ heldBranches: entries.filter(entry => !entry.claimMarker && !entry.detached && entry.branch).length,+ heldDetached: entries.filter(entry => !entry.claimMarker && (entry.detached || !entry.branch)).length,+ ...(claimMarkersHeld.length ? { heldClaims: entries.filter(entry => entry.claimMarker).length } : {}),...(heldBackMerged.length ? { heldBackMerged: heldBackMerged.length } : {})} : null;const reason = !entries.length ? 'no-in-flight-branches'+ : entries.every(entry => entry.claimMarker) ? 'claim-markers-held': heldLive.length ? 'branches-held-by-live-owners': heldBackMerged.length === entries.length ? 'merged-branches-held-back' : 'branches-blocked';return {@@ -1129,6 +1137,7 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgeconst 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,@@ -1274,6 +1283,9 @@ 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 },+ };// 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@@ -1299,7 +1311,11 @@ 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 }) {+async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false }) {+ 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 };if (b.worktreePath) {// Never tear down a worktree outside the managed roots (see// reconcileWorktreeRoots), one that's locked, a RECENT human /claim session,@@ -1324,16 +1340,34 @@ async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleCconst retryAt = worktreeProtectionExpiresAt(gate);return { ok: false, reason: protectedReason, ...(retryAt ? { retryAt } : {}) };}- if (requireCleanWorktree && await isWorktreeDirty(b.worktreePath)) return { ok: false, reason: 'worktree-dirty' };+ const dirty = await isWorktreeDirty(b.worktreePath);+ if (dirty === null) return { ok: false, reason: 'worktree-status-unavailable' };+ if (requireCleanWorktree && dirty) return { ok: false, reason: 'worktree-dirty' };}const prepared = prepare ? await prepare() : null;if (prepared?.error) return { ok: false, reason: prepared.error };if (b.worktreePath) {- const removal = await forceRemoveWorktreeDir(repoPath, b.worktreePath, { label, log: 'all' });+ const verifyRemoval = async (holder) => {+ if (!holder || holder.branch !== `refs/heads/${b.branch}`) 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 });+ if (reason) return reason;+ }+ const policyHold = await readPolicyHold();+ if (policyHold) return policyHold;+ const dirty = await isWorktreeDirty(b.worktreePath);+ if (dirty === null) return 'worktree-status-unavailable';+ if (requireCleanWorktree && dirty) return 'worktree-dirty';+ return 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// fail, and reporting success would mark the branch reconciled while it is held.- if (!removal.removed) return { ok: false, reason: 'worktree-remove-failed' };+ if (!removal.removed) return { ok: false, reason: removal.reason || 'worktree-remove-failed' };}+ 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}` };@@ -1426,16 +1460,38 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { activehold(tree, protectedReason, worktreeProtectionExpiresAt(gate));continue;}- if (tree.dirtyPaths.length > 0 || await isWorktreeDirty(tree.path)) {+ const dirty = await isWorktreeDirty(tree.path);+ if (tree.dirtyPaths === null || dirty === null) {+ hold(tree, 'worktree-status-unavailable');+ continue;+ }+ if (tree.dirtyPaths.length > 0 || dirty) {hold(tree, 'worktree-dirty');continue;}// Re-verify at action time against what the tree holds NOW: its HEAD may have// been switched to a branch or an unmerged commit since the gather.if (!await isStillDetachedOnMerged(repoPath, tree.path, defaultBranch)) continue;- const removal = await forceRemoveWorktreeDir(repoPath, tree.path, { label: '🔀 branch-reconcile: remove detached worktree', log: 'all' });+ const removal = await withClaimOwnershipLock(async () => {+ const verifyRemoval = async (holder) => {+ if (!holder || holder.branch) return 'worktree-holder-changed';+ if (claimOwners !== undefined) {+ const agents = claimOwners?.readAgents ? await claimOwners.readAgents().catch(() => null) : claimOwners?.agents;+ // Detached HEAD has no claim branch, but a run may occupy its directory.+ const reason = claimCheckoutOwnerReason({ branchName: 'HEAD', holderPath: tree.path, sourceWorkspace: repoPath, agents });+ if (reason) return reason;+ }+ const dirty = await isWorktreeDirty(tree.path);+ if (dirty === null) return 'worktree-status-unavailable';+ if (dirty) return 'worktree-dirty';+ return await isStillDetachedOnMerged(repoPath, tree.path, defaultBranch) ? null : 'worktree-head-changed';+ };+ return forceRemoveWorktreeDir(repoPath, tree.path, {+ label: '🔀 branch-reconcile: remove detached worktree', log: 'all', verifyRemoval,+ });+ });if (!removal.removed) {- hold(tree, 'worktree-remove-failed');+ hold(tree, removal.reason || 'worktree-remove-failed');continue;}cleaned.push(tree.path);@@ -1478,13 +1534,14 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { active* 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 } = {}) {+ 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// that every branch commit is already in the default branch (including// squash/rebase-equivalent merges). Keeping this pass ahead of gh means a// temporary forge outage cannot strand locally-provable completed work.const worktreeCleanup = cleanup- ? await reapMergedWorktrees(repoPath, { activeAgentIds, includeClaudeTrees: true }).catch(() => ({ reaped: [] }))+ ? await reapMergedWorktrees(repoPath, { activeAgentIds, claimOwners, includeClaudeTrees: true }).catch(() => ({ reaped: [] })): { reaped: [] };const cleanedWorktrees = (worktreeCleanup.reaped || []).map((entry) => typeof entry === 'string' ? entry : entry?.branch)diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.jsindex 124fb3e25c..4b86e494df 100644--- a/server/services/branchReconcile.ownership.test.js+++ b/server/services/branchReconcile.ownership.test.js@@ -1,8 +1,3 @@-vi.mock('./branchCompletionPolicy.js', async () => ({- ...await vi.importActual('./branchCompletionPolicy.js'),- readBranchCompletionPolicies: vi.fn(async () => []),- readBranchCompletionHold: vi.fn(async () => null),-}));/*** Worktree ownership through branch-reconcile's real cleanup boundary (#10270).*@@ -14,13 +9,43 @@ vi.mock('./branchCompletionPolicy.js', async () => ({* operator's explicit merged-branch cleanup keeps its wider reach.*/import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdtemp, mkdir, rm, utimes, writeFile } from 'fs/promises';+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';+const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [] }));+vi.mock('../lib/execGit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, execGit: async (args, cwd, options) => {+ if (args[0] === 'status' && cwd === injected.statusPath) {+ if (injected.statusThrows || !options?.ignoreExitCode) throw new Error('synthetic unreadable index');+ return { stdout: '', stderr: 'synthetic unreadable index', exitCode: 128 };+ }+ if (args[0] === 'worktree' && args[1] === 'remove' && injected.beforeRemove) {+ const before = injected.beforeRemove;+ injected.beforeRemove = null;+ await before();+ throw new Error('synthetic Git removal failure');+ }+ return actual.execGit(args, cwd, options);+ } };+});+vi.mock('./cosState.js', () => ({+ readAgentsStateForSafetyCheck: async () => ({ trusted: injected.owners !== null,+ agents: injected.owners && Object.fromEntries(injected.owners.map(agent => [agent.id, agent])) }),+}));++// Keep archive I/O at the boundary; use the real completion-policy evaluator.+vi.mock('./branchCompletionPolicy.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, readBranchCompletionPolicies: async () => injected.policies, readBranchCompletionHold: input => actual.readBranchCompletionHold(input, {+ readPolicies: async () => injected.policies,+ }) };+});+// Keep the run hermetic: the verdict ledger otherwise reads this install's// real CoS data directory.vi.mock('./supersededLedger.js', async (importOriginal) => ({@@ -28,7 +53,7 @@ vi.mock('./supersededLedger.js', async (importOriginal) => ({readVerdictLedger: async () => [],}));-const { reconcile } = await import('./branchReconcile.js');+const { reconcile, cleanupMerged, reapSupersededBranches } = await import('./branchReconcile.js');const { deleteMergedBranches } = await import('./git.js');const DAY = 24 * 60 * 60 * 1000;@@ -39,6 +64,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (relet external;beforeEach(async () => {+ Object.assign(injected, { statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [] });scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reconcile-own-')));const safeRepo = join(scratch, 'repo');await mkdir(safeRepo);@@ -138,4 +164,140 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(existsSync(loose)).toBe(false);expect(await branches()).not.toContain('loose-br');});++ it.each([false, true])('preserves authored files when status is unreadable (throws=%s)', async (throws) => {+ const path = await addTree(join(repo, '.claude', 'worktrees', 'claim-unreadable'), 'claim/issue-31', { ageMs: 30 * DAY });+ await writeFile(join(path, 'unfinished.txt'), 'keep this work\n');+ injected.statusPath = path;+ injected.statusThrows = throws;+ const result = await reconcile(repo, { activeAgentIds: new Set() });+ expect(result.cleaned).not.toContain('claim/issue-31');+ expect(result.skipped).toContainEqual(expect.objectContaining({ branch: 'claim/issue-31', reason: 'worktree-status-unavailable' }));+ expect(existsSync(join(path, 'unfinished.txt'))).toBe(true);+ expect(await branches()).toContain('claim/issue-31');+ });++ it('does not let a superseded verdict authorize retirement of an unreadable checkout', async () => {+ const branch = 'fix/superseded-unreadable';+ const path = await addTree(join(repo, '.claude', 'worktrees', 'superseded'), branch);+ await writeFile(join(path, 'unfinished.txt'), 'preserve before backup\n');+ const tip = (await execGit(['rev-parse', branch], repo)).stdout.trim();+ injected.statusPath = path;+ const result = await reapSupersededBranches(repo, 'main', [{+ branch, tip, worktreePath: path, dirtyPaths: ['unfinished.txt'],+ verdict: { branch, tip, verdict: 'SUPERSEDED', dirtyPaths: ['unfinished.txt'] },+ }], { cosDir: join(scratch, 'cos') });++ expect(result.reaped).toEqual([]);+ expect(result.skipped).toContainEqual({ branch, reason: 'worktree-status-unavailable' });+ expect(existsSync(join(path, 'unfinished.txt'))).toBe(true);+ expect(await branches()).toContain(branch);+ });++ it('checks current owners when direct cleanup receives only a previously merged ref', async () => {+ const branch = 'fix/newly-reserved';+ await execGit(['branch', branch, 'main'], repo);+ injected.owners = [{ id: 'coordinator', status: 'running', metadata: {+ sourceWorkspace: repo, claimBranches: [branch],+ } }];++ const result = await cleanupMerged(repo, 'main', [{ branch, upstreamGone: true }]);++ expect(result.cleaned).toEqual([]);+ expect(result.skipped).toEqual([{ branch, reason: 'claim-owner-active' }]);+ expect(await branches()).toContain(branch);+ });++ it('refreshes a completion handoff before direct retirement and after a Git refusal', async () => {+ const ref = 'fix/policy-held-ref';+ const checkedOut = 'fix/policy-held-tree';+ await execGit(['branch', ref, 'main'], repo);+ const path = await addTree(join(repo, '.claude', 'worktrees', 'policy-held'), checkedOut);+ const hold = branch => ({ id: `completed-${branch.replaceAll('/', '-')}`, status: 'completed', metadata: {+ sourceWorkspace: repo, worktreeBranch: branch, prCompletionPolicy: 'leave-open',+ } });+ injected.policies = [hold(ref)];+ const direct = await cleanupMerged(repo, 'main', [{ branch: ref, upstreamGone: true }]);+ expect(direct.cleaned).toEqual([]);+ expect(direct.skipped).toEqual([{ branch: ref, reason: 'pr-completion-human-handoff' }]);++ injected.beforeRemove = async () => { injected.policies.push(hold(checkedOut)); };+ const result = await reconcile(repo);+ expect(result.cleaned).not.toContain(checkedOut);+ expect(result.wip).toContainEqual(expect.objectContaining({ branch: checkedOut, completionPolicyReason: 'pr-completion-human-handoff' }));+ expect(existsSync(path)).toBe(true);+ expect(await branches()).toEqual(expect.arrayContaining([ref, checkedOut]));+ });++ it('protects registered branch owners and coordinator reservations during the early reap', async () => {+ const root = join(repo, '.claude', 'worktrees');+ const owned = await addTree(join(root, 'owned'), 'claim/issue-32');+ const reserved = await addTree(join(root, 'reserved'), 'next/issue-33');+ injected.owners = [+ { id: 'agent-owner', status: 'paused', sourceWorkspace: repo, workspacePath: repo, metadata: { claimBranch: 'claim/issue-32' } },+ { id: 'agent-coordinator', status: 'running', sourceWorkspace: repo, workspacePath: repo, metadata: { claimBranches: ['next/issue-33'] } },+ ];+ const result = await reconcile(repo, { activeAgentIds: new Set(), claimOwners: { agents: injected.owners, readAgents: async () => injected.owners } });+ expect(result.cleaned).toEqual([]);+ for (const path of [owned, reserved]) expect(existsSync(path)).toBe(true);+ expect(result.skipped.map(row => row.reason)).toEqual(['claim-owner-active', 'claim-owner-active']);+ });++ it.each(['owner', 'lock', 'status failure'])('preserves a tree when a new %s appears before the early reaper fallback', async (change) => {+ const path = await addTree(join(repo, '.claude', 'worktrees', 'fallback'), 'fix/fallback');+ const owners = { agents: [], readAgents: async () => injected.owners };+ injected.beforeRemove = async () => {+ if (change === 'lock') await execGit(['worktree', 'lock', path], repo);+ else if (change === 'status failure') injected.statusPath = path;+ else injected.owners = [{ id: 'agent-new-owner', status: 'running', workspacePath: path }];+ };+ const result = await reconcile(repo, { activeAgentIds: new Set(), claimOwners: owners });+ expect(result.cleaned).toEqual([]);+ expect(existsSync(path)).toBe(true);+ expect(await branches()).toContain('fix/fallback');+ const registration = (await execGit(['worktree', 'list', '--porcelain'], repo)).stdout;+ expect(registration).toContain(`worktree ${path}`);+ if (change === 'lock') expect(registration).toContain('locked');+ expect(result.skipped).toContainEqual(expect.objectContaining({ branch: 'fix/fallback', reason: change === 'lock' ? 'worktree-locked' : change === 'status failure' ? 'worktree-status-unavailable' : 'claim-owner-active' }));+ });++ it('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');+ 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(existsSync(path)).toBe(true);+ expect(await branches()).toContain('fix/unknown-owner');+ }+ });++ it('preserves an unreadable detached tree and still retires a clean detached peer', async () => {+ const root = join(repo, '.claude', 'worktrees');+ const unreadable = join(root, 'unreadable-detached');+ const clean = join(root, 'clean-detached');+ await execGit(['worktree', 'add', '--detach', unreadable, 'main'], repo);+ await execGit(['worktree', 'add', '--detach', clean, 'main'], repo);+ await writeFile(join(unreadable, 'unfinished.txt'), 'preserve\n');+ injected.statusPath = unreadable;+ const result = await reconcile(repo, { activeAgentIds: new Set(), claimOwners: { agents: [], readAgents: async () => [] } });+ expect(result.detachedWorktrees).toContainEqual(expect.objectContaining({ path: unreadable, reason: 'worktree-status-unavailable' }));+ expect(existsSync(join(unreadable, 'unfinished.txt'))).toBe(true);+ expect(existsSync(clean)).toBe(false);+ expect(result.cleaned).toContain(clean);+ });++ it('preserves a prunable checkout whose missing pointer makes Git report the parent clean', async () => {+ await appendFile(join(repo, '.git', 'info', 'exclude'), '\n.claude/\n');+ const path = await addTree(join(repo, '.claude', 'worktrees', 'broken'), 'fix/broken');+ await writeFile(join(path, 'unique.txt'), 'uncommitted work\n');+ await unlink(join(path, '.git'));+ expect((await execGit(['status', '--porcelain'], path)).stdout).toBe('');+ expect((await execGit(['worktree', 'list', '--porcelain'], repo)).stdout).toContain('prunable');+ const result = await reconcile(repo, { activeAgentIds: new Set() });+ expect(result.cleaned).toEqual([]);+ expect(result.skipped).toContainEqual(expect.objectContaining({ branch: 'fix/broken', reason: 'worktree-status-unavailable' }));+ expect(existsSync(join(path, 'unique.txt'))).toBe(true);+ expect(await branches()).toContain('fix/broken');+ });});diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex ee805a5147..3664d0e7e7 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -25,12 +25,20 @@ vi.mock('./git.js', () => ({vi.mock('../lib/execGit.js', () => ({execGit: vi.fn(async () => ({ stdout: '', exitCode: 0 }))}));+vi.mock('./cosClaimOwnership.js', async (importOriginal) => ({+ ...await importOriginal(), readClaimOwnershipAgents: async () => [],+}));vi.mock('./worktreeManager.js', async () => {const { AGENT_SCRATCH_PATHS, matchesScratchRoot } = await import('../lib/agentScratchPaths.js');return {listWorktrees: vi.fn(async () => []),forceRemoveWorktreeDir: vi.fn(async () => ({ removed: true, warning: null })),reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),+ readWorktreeStatus: async (path) => {+ const { execGit } = await import('../lib/execGit.js');+ const result = await execGit(['status', '--porcelain'], path, { ignoreExitCode: true }).catch(() => null);+ return result?.exitCode === 0 ? result.stdout : null;+ },// Real pure classifier semantics: empty porcelain = clean, and every non-empty// line is a real change path (the suite never feeds it lockfile churn) EXCEPT// PortOS's own runtime scratch, which the real classifier subtracts for every@@ -402,14 +410,14 @@ describe('cleanupMerged', () => {expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();});- it('never tears down a locked / human-claim / active-agent worktree', async () => {+ it('keeps legacy snapshot-only callers behind locked / human-claim / active-agent gates', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);const activeAgentIds = new Set(['agent-abc12345']);const res = await cleanupMerged('/repo', 'main', [{ branch: 'locked-b', worktreePath: '/repo/data/cos/worktrees/locked', worktreeLocked: true },{ branch: 'claim-b', worktreePath: '/repo/data/cos/worktrees/claim-foo' },{ branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345' }- ], { activeAgentIds });+ ], { activeAgentIds, claimOwners: { agents: [] } });expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'locked-b', reason: 'worktree-locked' },@@ -483,13 +491,13 @@ describe('cleanupMerged', () => {expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'claim/issue-', { local: true });});- it('still protects a RECENT claim worktree even when merged + clean, and says when the hold lifts', async () => {+ it('still protects a RECENT claim worktree for snapshot-only callers even when merged + clean, and says when the hold lifts', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // cleanconst before = Date.now();const 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' });@@ -510,12 +518,12 @@ describe('cleanupMerged', () => {git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean- const reaped = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-0', ...shipped() }]);+ const 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- const dirty = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-1', ...shipped() }]);+ const dirty = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-1', ...shipped() }], { claimOwners: { agents: [] } });expect(dirty.cleaned).toEqual([]);expect(dirty.skipped).toEqual([{ branch: 'claim/issue-1', reason: 'worktree-dirty' }]);@@ -524,7 +532,7 @@ describe('cleanupMerged', () => {// remote could not be read. The week-long window still applies.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' });@@ -533,7 +541,7 @@ describe('cleanupMerged', () => {// caller is told when the short window lapses.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);@@ -1086,7 +1094,8 @@ describe('unreachable forge (#3358)', () => {const res = await reconcile('/repo');expect(res.cleaned).toEqual(['feature/done']);expect(wt.reapMergedWorktrees).toHaveBeenCalledWith('/repo', {- activeAgentIds: new Set(), includeClaudeTrees: true+ activeAgentIds: new Set(), includeClaudeTrees: true,+ claimOwners: { agents: [], readAgents: expect.any(Function) },});expect(wt.reapMergedWorktrees.mock.invocationCallOrder[0]).toBeLessThan(ensureForgeReachableMock.mock.invocationCallOrder[0]);@@ -1175,7 +1184,9 @@ describe('reconcile', () => {worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;git.hasBranchMergeEvidence.mockResolvedValue(true);- const res = await reconcile('/repo');+ // A snapshot-only caller cannot replace the human-claim age protection+ // with a fresh registry proof under the binding lock.+ 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(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.jsindex 7a17859669..c5add5797a 100644--- a/server/services/cosClaimOwnership.js+++ b/server/services/cosClaimOwnership.js@@ -32,6 +32,23 @@ export function withClaimOwnershipLock(work) {return run;}+/** Destructive callers must not consume loadState's empty recovery default. */+export async function readClaimOwnershipAgents() {+ const { readAgentsStateForSafetyCheck } = await import('./cosState.js');+ const snapshot = await readAgentsStateForSafetyCheck().catch(() => null);+ if (snapshot?.trusted !== true || !snapshot.agents || typeof snapshot.agents !== 'object' || Array.isArray(snapshot.agents)) return null;+ const entries = Object.entries(snapshot.agents);+ if (entries.some(([id, agent]) => {+ if (!agent || agent.id !== id || !['running', 'paused', 'completed'].includes(agent.status)) return true;+ if (agent.metadata != null && (typeof agent.metadata !== 'object' || Array.isArray(agent.metadata))) return true;+ return ['claimBranches', 'claimReleasedBranches'].some(key => {+ const bindings = agent.metadata?.[key] ?? agent[key];+ return bindings != null && (!Array.isArray(bindings) || bindings.some(branch => typeof branch !== 'string'));+ });+ })) return null;+ return entries.map(([, agent]) => agent);+}+/*** @param {{ agentId: string, action: 'bind'|'release', branch: string }} input* @returns {Promise<{ bound: true, branch: string }|{ released: true, branch: string }|{ bound?: false, released?: false, reason: string }>}@@ -74,11 +91,7 @@ export async function checkReconcileOwnership(input, deps = {}) {const { appId, branch, prUrl, worktreePath, agentId } = input;const getAppById = deps.getAppById ?? (await import('./apps.js')).getAppById;const listWorktrees = deps.listWorktrees ?? (await import('./worktreeManager.js')).listWorktrees;- const getAgents = deps.getAgents ?? (async () => {- const { readAgentsStateForSafetyCheck } = await import('./cosState.js');- const snapshot = await readAgentsStateForSafetyCheck();- return snapshot.trusted && snapshot.agents ? Object.values(snapshot.agents) : null;- });+ const getAgents = deps.getAgents ?? readClaimOwnershipAgents;const readCompletionHold = deps.readCompletionHold ?? (await import('./branchCompletionPolicy.js')).readBranchCompletionHold;const getActiveAgentIds = deps.getActiveAgentIds ?? (await import('./agentState.js')).getActiveAgentIds;const { buildActiveOwnerIds, resolveLiveOwnerReason } = await import('./branchReconcile.js');diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.jsindex c72baa6de1..c4fd69e752 100644--- a/server/services/cosTaskPreStepBlocks.compose.test.js+++ b/server/services/cosTaskPreStepBlocks.compose.test.js@@ -91,14 +91,14 @@ vi.mock('./agentState.js', async (importActual) => ({getActiveAgentIds: vi.fn(() => []),}));-vi.mock('./cos.js', () => ({- getAgents: vi.fn(async () => []),+vi.mock('./cosState.js', () => ({+ readAgentsStateForSafetyCheck: vi.fn(async () => ({ trusted: true, agents: {} })),}));import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';-import { getAgents } from './cos.js';import { getTaskInterval } from './taskSchedule.js';import { applyPerpetualDrainCap } from './cosTaskPreStepBlocks.js';+import { readAgentsStateForSafetyCheck } from './cosState.js';const APP = { id: 'app-1', name: 'Example App', repoPath: '/tmp/example-repo' };const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };@@ -121,7 +121,7 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-stvi.clearAllMocks();parkPerpetual.mockReset().mockResolvedValue();recordPerpetualDispatch.mockReset().mockResolvedValue(1);- getAgents.mockResolvedValue([]);+ readAgentsStateForSafetyCheck.mockResolvedValue({ trusted: true, agents: {} });getPerpetualDrainState.mockResolvedValue({ signature: null, dispatchCount: 0 });reconcileMock.mockResolvedValue(scan());getTaskInterval.mockResolvedValue({ type: 'on-demand', perpetual: true, drainDispatchCap: 5, taskMetadata: { branchesPerAgent: 3 } });@@ -148,9 +148,9 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st});it('protects a live claim worktree by passing its recorded path token to reconcile', async () => {- getAgents.mockResolvedValue([- { id: 'agent-live', status: 'running', workspacePath: '/repo/data/cos/worktrees/claim-issue-99' }- ]);+ readAgentsStateForSafetyCheck.mockResolvedValue({ trusted: true, agents: {+ 'agent-live': { id: 'agent-live', status: 'running', workspacePath: '/repo/data/cos/worktrees/claim-issue-99' },+ } });reconcileMock.mockResolvedValue(scan({ inFlight: [] }));await generate();@@ -161,7 +161,7 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st});it('does not reconcile when the live-agent state cannot be read', async () => {- getAgents.mockRejectedValue(new Error('state unavailable'));+ readAgentsStateForSafetyCheck.mockRejectedValue(new Error('state unavailable'));expect(await generate()).toBeNull();expect(reconcileMock).not.toHaveBeenCalled();@@ -222,6 +222,21 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st});});+ it('reports protected issue markers separately after local cleanup succeeded', async () => {+ reconcileMock.mockResolvedValue(scan({ inFlight: [], cleaned: ['claim/issue-42', 'next/issue-42'],+ claimMarkersHeld: [+ { branch: 'claim/issue-42', issue: 42, reason: 'claim-reservation-owner-unverified' },+ { branch: 'next/issue-42', issue: 42, reason: 'claim-reservation-owner-unverified' },+ ]+ }));+ expect(await generate()).toBeNull();+ expect(parkPerpetual).toHaveBeenCalledWith('branch-reconcile', APP.id, expect.objectContaining({+ reason: 'claim-markers-held', counts: { heldBranches: 0, heldDetached: 0, heldClaims: 1 },+ skipCauses: { 'claim-reservation-owner-unverified': 1 }+ }));+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();+ });+it('parks typed draft, owner, detached and cleanup blockers without treating them as an empty repo', async () => {reconcileMock.mockResolvedValue(scan({ inFlight: [],wip: [@@ -248,4 +263,16 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-stexpect(recordPerpetualDispatch).not.toHaveBeenCalled();});+ it.each([+ { trusted: false, agents: {} },+ { trusted: true, agents: { owner: { id: 'owner', status: 'unknown' } } },+ { trusted: true, agents: { owner: { id: 'different-owner', status: 'running' } } },+ { trusted: true, agents: { owner: { id: 'owner', status: 'running', metadata: { claimBranches: 'claim/issue-99' } } } },+ ])('does not dispatch cleanup from untrusted or malformed persisted ownership: %j', async (snapshot) => {+ readAgentsStateForSafetyCheck.mockResolvedValue(snapshot);++ expect(await generate()).toBeNull();+ expect(reconcileMock).not.toHaveBeenCalled();+ });+});diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex 4e34236c27..7392a8181c 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -424,8 +424,8 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSconst { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature, describeIdleReconcilePark, buildActiveOwnerIds } = await import('./branchReconcile.js');const { formatSupersededForPrompt } = await import('./supersededLedger.js');const { getActiveAgentIds } = await import('./agentState.js');- const { getAgents } = await import('./cos.js');- const liveAgents = await getAgents().catch((err) => {+ const { readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');+ const liveAgents = await readClaimOwnershipAgents().catch((err) => {emitLog('warn', `branch-reconcile skipped for ${app.name}: active agent state unreadable (${err.message})`, { appId: app.id, analysisType: taskType });return null;});@@ -450,7 +450,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSconst result = await reconcile(app.repoPath, {cleanup: actions.cleanupMerged !== false,activeAgentIds,- claimOwners: { agents: liveAgents, readAgents: getAgents },+ claimOwners: { agents: liveAgents, readAgents: readClaimOwnershipAgents },// The app's gh account pin, so a repo owned by another GitHub account is// polled with a credential that can see it (#7540).forgeAccount: app.forgeAccount || null@@ -503,6 +503,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSconst allActionable = filterActionable(result.inFlight, actions);const idlePark = describeIdleReconcilePark(result.skipped || [], heldLive, {wip: result.wip, detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,+ claimMarkersHeld: result.claimMarkersHeld,gated: result.inFlight.filter(branch => !allActionable.includes(branch))});if (allActionable.length === 0) {diff --git a/server/services/worktreeManager.forceRemove.test.js b/server/services/worktreeManager.forceRemove.test.jsindex c715306d3e..921dd5336b 100644--- a/server/services/worktreeManager.forceRemove.test.js+++ b/server/services/worktreeManager.forceRemove.test.js@@ -1,33 +1,24 @@import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';-import { mkdtemp, rm as realRm, writeFile, lstat, mkdir } from 'fs/promises';+import { mkdtemp, rm, writeFile, lstat, mkdir } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { materializeGitRepo, resetGitWorktreeSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';-// Failure injection seams over REAL git and a REAL filesystem: both default to-// the genuine implementation, and a test opts one call into rejecting. The+// Failure injection over REAL git and a REAL filesystem: a test opts one Git+// call into rejecting or acquiring a real lock before executing it. The// assertions then look at the surviving directory and registration, not at the// order the mocks were called in.-const injected = vi.hoisted(() => ({ gitFails: () => false, rmFails: false }));+const injected = vi.hoisted(() => ({ gitFails: () => false }));vi.mock('../lib/execGit.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,- execGit: vi.fn((args, ...rest) => (injected.gitFails(args)+ execGit: vi.fn(async (args, ...rest) => (await injected.gitFails(args)? Promise.reject(new Error(`injected git failure: ${args.slice(0, 2).join(' ')}`)): actual.execGit(args, ...rest))),};});-vi.mock('fs/promises', async (importOriginal) => {- const actual = await importOriginal();- return {- ...actual,- rm: vi.fn((...args) => (injected.rmFails- ? Promise.reject(Object.assign(new Error('injected EPERM'), { code: 'EPERM' }))- : actual.rm(...args))),- };-});import { execGit } from '../lib/execGit.js';import { forceRemoveWorktreeDir } from './worktreeManager.js';@@ -46,14 +37,12 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {});beforeEach(async () => {injected.gitFails = () => false;- injected.rmFails = false;vi.spyOn(console, 'log').mockImplementation(() => {});vi.spyOn(console, 'warn').mockImplementation(() => {});await resetGitWorktreeSandbox(repo, initialHead, safePath);});afterAll(async () => {- injected.rmFails = false; // the cleanup below goes through the same mocked module- await realRm(repo, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ await rm(repo, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });});async function addWorktree() {@@ -68,24 +57,15 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {it('removes a clean worktree and verifies both its directory and registration are gone', async () => {const path = await addWorktree();- const outcome = await forceRemoveWorktreeDir(repo, path);+ const outcome = await forceRemoveWorktreeDir(repo, path, { verifyRemoval: async () => null });expect(outcome).toMatchObject({ removed: true, directory: 'absent', registration: 'absent', warning: null });expect(existsSync(path)).toBe(false);expect(await registered(path)).toBe(false);});- it('falls back to rm + prune when git refuses, and reports the verified result', async () => {- const path = await addWorktree();- injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';- const outcome = await forceRemoveWorktreeDir(repo, path);- expect(outcome.removed).toBe(true);- expect(existsSync(path)).toBe(false);- expect(await registered(path)).toBe(false);- });-it('reports an already-removed directory with a stale registration as removed once pruned', async () => {const path = await addWorktree();- await realRm(path, { recursive: true, force: true });+ await rm(path, { recursive: true, force: true });expect(await registered(path)).toBe(true);const outcome = await forceRemoveWorktreeDir(repo, path);expect(outcome.removed).toBe(true);@@ -98,13 +78,12 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {expect((await forceRemoveWorktreeDir(repo, path)).removed).toBe(true);});- it('returns an incomplete outcome with an actionable warning when git removal AND rm both fail', async () => {+ it.each([false, true])('preserves surviving contents after Git refusal even with a fresh guard (%s)', async (guarded) => {const path = await addWorktree();await writeFile(join(path, 'keep.txt'), 'still here\n');injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';- injected.rmFails = true;- const outcome = await forceRemoveWorktreeDir(repo, path, { label: 'test cleanup' });+ const outcome = await forceRemoveWorktreeDir(repo, path, { label: 'test cleanup', ...(guarded ? { verifyRemoval: async () => null } : {}) });expect(outcome).toMatchObject({ removed: false, directory: 'present', registration: 'registered' });expect(outcome.warning).toMatch(/cleanup incomplete/);@@ -112,36 +91,61 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {expect(outcome.warning).toMatch(/directory still present/);expect(outcome.warning).toMatch(/registration still registered/);expect(outcome.warning).toMatch(/retryable/);- expect(outcome.warning).toContain('injected EPERM');+ expect(outcome.reason).toBe('worktree-removal-refused');// The checkout genuinely survived — the report is not a guess.expect(existsSync(join(path, 'keep.txt'))).toBe(true);expect(await registered(path)).toBe(true);expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('cleanup incomplete'));});- it('keeps a locked registration visible: the directory is removed but the outcome is incomplete', async () => {+ it('preserves a locked directory and registration', async () => {const path = await addWorktree();await execGit(['worktree', 'lock', path], repo);const outcome = await forceRemoveWorktreeDir(repo, path);- expect(outcome).toMatchObject({ removed: false, directory: 'absent', registration: 'registered' });- expect(existsSync(path)).toBe(false);+ expect(outcome).toMatchObject({ removed: false, directory: 'present', registration: 'registered', reason: 'worktree-locked' });+ expect(existsSync(path)).toBe(true);+ expect(await registered(path)).toBe(true);+ });++ it('preserves a lock acquired during the fallback ownership check', async () => {+ const path = await addWorktree();+ await writeFile(join(path, 'keep.txt'), 'preserve\n');+ injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';+ let checks = 0;+ const outcome = await forceRemoveWorktreeDir(repo, path, { verifyRemoval: async () => {+ if (++checks === 2) await execGit(['worktree', 'lock', path], repo);+ return null;+ } });+ expect(outcome).toMatchObject({ removed: false, reason: 'worktree-locked' });+ expect(existsSync(join(path, 'keep.txt'))).toBe(true);+ expect(await registered(path)).toBe(true);+ });++ it('lets Git protect a lock acquired after the final safety read', async () => {+ const path = await addWorktree();+ injected.gitFails = async args => {+ if (args[0] === 'worktree' && args[1] === 'remove') await execGit(['worktree', 'lock', path], repo);+ return false;+ };+ const outcome = await forceRemoveWorktreeDir(repo, path, { verifyRemoval: async () => null });+ expect(outcome).toMatchObject({ removed: false, reason: 'worktree-locked' });+ expect(existsSync(path)).toBe(true);expect(await registered(path)).toBe(true);});it('never reads an unverifiable registration as success', async () => {const path = await addWorktree();- // Git removal works, but the follow-up verification cannot read the registry.+ // An unreadable registry is not authority to remove a checkout.injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'list';const outcome = await forceRemoveWorktreeDir(repo, path);- expect(existsSync(path)).toBe(false);- expect(outcome).toMatchObject({ removed: false, directory: 'absent', registration: 'unknown' });+ expect(existsSync(path)).toBe(true);+ expect(outcome).toMatchObject({ removed: false, directory: 'present', registration: 'unknown' });expect(outcome.warning).toMatch(/registration unverified/);});it('never throws, and bounds the error excerpt carried in the warning', async () => {const path = await addWorktree();injected.gitFails = (args) => args[0] === 'worktree';- injected.rmFails = true;const outcome = await forceRemoveWorktreeDir(repo, path);expect(outcome.removed).toBe(false);expect(outcome.warning.length).toBeLessThan(600);@@ -160,16 +164,15 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {expect(console.log).not.toHaveBeenCalled();});- it("log:'all' gates the rm + prune sub-failure logs, and `subject` names them", async () => {+ it("log:'all' gates the prune failure log, and `subject` names them", async () => {const path = await addWorktree();+ await rm(path, { recursive: true, force: true });injected.gitFails = (args) => args[0] === 'worktree' && (args[1] === 'remove' || args[1] === 'prune');- injected.rmFails = true;- await forceRemoveWorktreeDir(repo, path, { label: 'L' });+ await forceRemoveWorktreeDir(repo, path, { label: 'L', verifyRemoval: async () => null });expect(console.log).toHaveBeenCalledTimes(1); // default log:'remove' → only the remove lineconsole.log.mockClear();- await forceRemoveWorktreeDir(repo, path, { label: 'L', log: 'all', subject: 'agent-42' });- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Manual rm failed for worktree agent-42'));+ await forceRemoveWorktreeDir(repo, path, { label: 'L', log: 'all', subject: 'agent-42', verifyRemoval: async () => null });expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Worktree prune failed for agent-42'));});});diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 7bc98b5072..9b6b6b8b74 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -9,7 +9,7 @@* and the branch cleaned up.*/-import { claimBranchAdmission } from '../lib/claimContinuation.js';+import { claimBranchAdmission, claimCheckoutOwnerReason } from '../lib/claimContinuation.js';import { existsSync, realpathSync } from 'fs';import { lstat, readlink, readdir, rm, stat, symlink, unlink } from 'fs/promises';import { dirname, isAbsolute, join, resolve } from 'path';@@ -23,6 +23,7 @@ import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';import { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';import { ensureInstanceId } from './instanceIdentity.js';+import { withClaimOwnershipLock, readClaimOwnershipAgents } from './cosClaimOwnership.js';export { isHumanClaimWorktree } from '../lib/worktreeOwnership.js';@@ -332,8 +333,8 @@ function removalOutcome(worktreePath, { directory, registration }, failure = nul/*** Remove a worktree directory robustly: try `git worktree remove --force`, and- * if git refuses (locked, already-gone, broken admin files), fall back to a- * plain recursive `rm` + `git worktree prune` to clear git's stale bookkeeping.+ * if git refuses, preserve surviving contents and only prune an absent tree.+ * Git's lock-aware remove is the only operation allowed to delete a checkout.* Never throws — cleanup is best-effort and must never throw into a* completion/reap path — but it DOES report what it achieved: after every* attempt it re-reads the exact directory and its Git registration, and@@ -352,34 +353,60 @@ function removalOutcome(worktreePath, { directory, registration }, failure = nul* cleanup (background paths that must not spam on the common case).* @param {'remove'|'all'} [opts.log='remove'] - how much to log when `label` is* set: `'remove'` logs only the `worktree remove` failure (the operator-- * facing signal); `'all'` also logs the rm + prune sub-failures. Ignored when+ * facing signal); `'all'` also logs a prune failure. Ignored when* `label` is absent (nothing logs). The two flags the four callers needed —* "label + log everything" and "label + log remove only" and "silent" — are* the three states here; there was never a "log without a label" caller.- * @param {string} [opts.subject] - identifier embedded in the rm/prune- * sub-failure messages (only used when `log:'all'`). Defaults to+ * @param {string} [opts.subject] - identifier embedded in prune+ * failure messages (only used when `log:'all'`). Defaults to* `worktreePath`; the agent-cleanup callers pass their agent id so the* message wording stays byte-identical to the pre-extraction logs an operator* may grep for (e.g. `… for worktree <agentId>`).+ * @param {(holder: object|null) => Promise<string|null>} [opts.verifyRemoval] -+ * caller's fresh ownership/content gate, run before Git removal and rechecked+ * after a refusal to report the current hold.+ * Callers that share claim ownership hold its lock through this operation.* @returns {Promise<{removed: boolean, directory: string, registration: string, warning: string|null}>}* `warning` is set exactly when `removed` is false.*/-export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log = 'remove', subject = worktreePath } = {}) {+export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log = 'remove', subject = worktreePath, verifyRemoval } = {}) {const logAll = label && log === 'all';let lastFailure = null;- await execGit(['worktree', 'remove', worktreePath, '--force'], repo).catch(async (err) => {+ let heldReason = null;+ 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;+ if (holder?.locked) return 'worktree-locked';+ if (!verifyRemoval) return null;+ const reason = await verifyRemoval(holder).catch(() => 'worktree-ownership-unreadable');+ if (reason) return reason;+ // Ownership/content checks await I/O. Refresh their registration afterward;+ // 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;+ if (current?.locked) return 'worktree-locked';+ if (current?.branch !== holder?.branch || current?.head !== holder?.head) return 'worktree-holder-changed';+ return null;+ };+ heldReason = await check();+ if (!heldReason) await execGit(['worktree', 'remove', worktreePath, '--force'], repo).catch(async (err) => {lastFailure = errorExcerpt(err);if (label) console.log(`⚠️ ${label}: ${err.message}`);- await rm(worktreePath, { recursive: true, force: true }).catch((rmErr) => {- lastFailure = errorExcerpt(rmErr);- if (logAll) console.log(`⚠️ Manual rm failed for worktree ${subject}: ${rmErr.message}`);- });+ heldReason = await check();+ if (heldReason) return;+ // A refusal is not authority to erase a surviving checkout. A raw rm could+ // bypass a lock acquired after our last read, even with a caller guard.+ const directory = await lstat(worktreePath).then(() => 'present', err => err.code === 'ENOENT' ? 'absent' : 'unknown');+ if (directory !== 'absent') { heldReason = 'worktree-removal-refused'; return; }await execGit(['worktree', 'prune'], repo).catch((pruneErr) => {lastFailure = errorExcerpt(pruneErr);if (logAll) console.log(`⚠️ Worktree prune failed for ${subject}: ${pruneErr.message}`);});});- const outcome = removalOutcome(worktreePath, await probeWorktreeRemoval(repo, worktreePath), lastFailure);+ const outcome = removalOutcome(worktreePath, await probeWorktreeRemoval(repo, worktreePath), heldReason || lastFailure);+ if (heldReason) outcome.reason = heldReason;if (!outcome.removed && label) console.warn(`⚠️ ${outcome.warning}`);return outcome;}@@ -465,6 +492,21 @@ export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {};}+/** A proven-absent directory is empty; an existing tree must identify itself.+ * Git can otherwise walk out of a broken linked checkout and report its parent+ * clean. null means unknown, including unreadable directories or status errors.+ */+export async function readWorktreeStatus(worktreePath) {+ const present = await lstat(worktreePath).then(() => true,+ err => err.code === 'ENOENT' || err.code === 'ENOTDIR' ? false : null);+ if (present === false) return '';+ if (present === null) return null;+ const top = await execGit(['rev-parse', '--show-toplevel'], worktreePath).then(r => r.stdout.trim()).catch(() => null);+ if (!top || !pathsEqual(top, worktreePath)) return null;+ const status = await execGit(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], worktreePath, { ignoreExitCode: true }).catch(() => null);+ return status?.exitCode === 0 ? status.stdout : null;+}+/*** Compare two filesystem paths for equality, resolving symlinks (e.g. macOS* /var → /private/var) and Windows short-name aliases. Native realpath resolves@@ -1126,27 +1168,17 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// Verify the worktree still points to the correct repo before trusting git status.// If the .git file is missing (e.g., worktree was partially cleaned up), git walks up// the directory tree and may find a parent repo (e.g., PortOS) instead of the app repo.- // In that case, git status would report the parent repo's dirty files, causing us to- // incorrectly preserve the worktree.+ // In that case, even a successful git status describes the wrong checkout and+ // cannot prove this directory has no unique work.const detectedToplevel = await execGit(['rev-parse', '--show-toplevel'], worktreePath).then(r => r.stdout.trim()).catch(() => null);// Compare realpath-resolved forms so symlinks (e.g. macOS /var → /private/var)// or normalization differences don't false-positive as a broken worktree.if (detectedToplevel && !pathsEqual(detectedToplevel, worktreePath)) {- console.log(`🌳 Worktree ${agentId} resolves to ${detectedToplevel} instead of ${worktreePath} — broken worktree, removing`);- const rmFailure = await rm(worktreePath, { recursive: true, force: true }).then(() => null, rmErr => {- console.log(`⚠️ Failed to remove broken worktree ${agentId}: ${rmErr.message}`);- return rmErr;- });- if (rmFailure) {- warnings.push(`Worktree cleanup incomplete for ${worktreePath} (broken checkout still present): ${errorExcerpt(rmFailure)} — retryable`);- return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };- }- await cleanupWorktreeBranch(sourceWorkspace, branchName, {- preserveBranchWithCommits: options.preserveBranchWithCommits || options.merge, warnings,- });- return { merged: false, removed: true, uncommittedSaved: false, warnings };+ warnings.push('Worktree preserved — broken checkout identity prevents verifying its contents');+ console.warn(`⚠️ Worktree ${agentId} has a broken checkout identity; preserving its directory and branch`);+ return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };}// Safety check: abort removal when uncommitted changes are detected.@@ -1587,6 +1619,7 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)*/export async function reapMergedWorktrees(sourceWorkspace, {activeAgentIds = new Set(),+ claimOwners,excludeBranches = null,includeClaudeTrees = true,includeUnmanagedTrees = false,@@ -1594,6 +1627,11 @@ export async function reapMergedWorktrees(sourceWorkspace, {dryRun = false} = {}) {const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');+ const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');+ // Every entry point (scheduled, reconcile, operator cleanup) needs a trusted+ // registry. loadState/getAgents may default a corrupt file to empty state.+ const readOwners = claimOwners === undefined ? readClaimOwnershipAgents+ : async () => claimOwners?.readAgents ? claimOwners.readAgents().catch(() => null) : claimOwners?.agents;const defaultBranch = knownDefaultBranch || await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';const target = await resolveMergeTarget(sourceWorkspace, defaultBranch);@@ -1645,14 +1683,9 @@ export async function reapMergedWorktrees(sourceWorkspace, {// uncommitted fresh-from-main worktree may be an active agent that has not// made its first commit yet.//- // A registration git already calls prunable has no working tree left to be- // dirty, so it reads as clean rather than status-failed — otherwise `git- // status` fails in the missing directory and the branch stays pinned behind a- // worktree that no longer exists. `existsSync` covers the same state on a git- // too old to report `prunable` in `worktree list --porcelain`.- const status = wt.prunable || !existsSync(wt.path)- ? ''- : await execGit(['status', '--porcelain'], wt.path).then(r => r.stdout).catch(() => null);+ // Only a proven-absent directory is empty. A prunable registration may+ // instead be an existing checkout with a broken .git pointer and unique work.+ const status = await readWorktreeStatus(wt.path);if (status === null) { hold('status-failed'); continue; }if (!classifyWorktreeDirt(status).clean) { hold('uncommitted'); continue; }@@ -1660,26 +1693,43 @@ export async function reapMergedWorktrees(sourceWorkspace, {const hasMergeEvidence = await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false);if (!hasMergeEvidence) { hold('unmerged'); continue; }- if (dryRun) { reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false }); continue; }-- // Remove the worktree, then force-delete the branch (-D because squash-merged- // branches aren't recognized by -d, and we've proven the work is in default).- const removal = await forceRemoveWorktreeDir(sourceWorkspace, wt.path, {- label: `worktree remove failed for ${wt.path}, manual cleanup`,- });- // A checkout that survived is not a reap: it is held (not counted) with the- // retryable warning, and the branch is left alone — it is still checked out.- if (!removal.removed) {- skipped.push({ path: wt.path, branch: branchName, reason: 'remove-failed', warning: removal.warning });- continue;- }- // Reported per entry: the tree is gone, but a caller that- // presents this as "branch deleted" would otherwise be lying on a failure.- const branchDeleted = await execGit(['branch', '-D', branchName], sourceWorkspace).then(() => true).catch(err => {- console.log(`⚠️ branch delete failed for ${branchName}: ${err.message}`);- return false;+ // The early reconcile pass must see the SAME registered owners and branch+ // reservations as later retirement. Keep binding excluded until removal and+ // branch deletion settle, and re-read after a Git refusal too.+ await withClaimOwnershipLock(async () => {+ const verifyRemoval = async (holder) => {+ if (!holder || holder.branch !== wt.branch) return 'worktree-holder-changed';+ const agents = await readOwners();+ const ownerReason = claimCheckoutOwnerReason({ branchName, holderPath: wt.path, sourceWorkspace, agents });+ if (ownerReason) return ownerReason;+ const policyHold = await readBranchCompletionHold({ repoPath: sourceWorkspace, branch: branchName, retirement: true });+ if (policyHold) return policyHold;+ const reason = worktreeOwnershipReason({ path: wt.path, locked: holder.locked, activeAgentIds, roots: managedRoots, requireKnownLiveness: true });+ if (reason) return reason;+ const freshStatus = await readWorktreeStatus(wt.path);+ if (freshStatus === null) return 'worktree-status-unavailable';+ if (!classifyWorktreeDirt(freshStatus).clean) return 'worktree-dirty';+ return await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false) ? null : 'unmerged';+ };+ if (dryRun) {+ const reason = await verifyRemoval(wt);+ if (reason) hold(reason);+ else reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false });+ return;+ }+ const removal = await forceRemoveWorktreeDir(sourceWorkspace, wt.path, {+ label: `worktree remove failed for ${wt.path}`, verifyRemoval,+ });+ 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 });});- reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted });}if (reaped.length > 0) {diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 2fe726f12a..47a652ce41 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -874,14 +874,15 @@ describe('removeWorktree identity, dirt and branch preservation', () => {});});- it('removes a broken tree resolving to the parent without trusting its dirty status', async () => {+ it('preserves a broken tree resolving to the parent without trusting its dirty status', async () => {scriptGit({ detectedToplevel: '/repo', porcelain: ' M src/parent-work.js' });const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x');- expect(result).toEqual({ merged: false, removed: true, uncommittedSaved: false, warnings: [] });- expect(rm).toHaveBeenCalledWith(join(PATHS.worktrees, 'agent-x'), { recursive: true, force: true });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ 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] === 'status')).toBe(false);expect(execGitMock.mock.calls.some(([args]) => args[0] === 'worktree')).toBe(false);});@@ -1013,23 +1014,23 @@ describe('removeWorktree identity, dirt and branch preservation', () => {merge: false, preserveBranchWithCommits: true,});- expect(result.removed).toBe(true);- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(evidence === true);+ expect(result.removed).toBe(checkout === 'missing');+ expect(calledWith(['branch', '-D', '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 () => {const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: true });- expect(result).toMatchObject({ merged: false, removed: true });+ expect(result).toMatchObject({ merged: false, removed: checkout === 'missing' });expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);expect(result.warnings.join(' ')).toMatch(/preserved/);});- it('keeps explicit no-preservation cleanup behavior', async () => {+ it('only honors explicit branch disposal when the checkout is proven absent', async () => {await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });- expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(checkout === 'missing');expect(hasBranchMergeEvidenceMock).not.toHaveBeenCalled();});diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.jsindex 07d88c7119..c9d4f0fa81 100644--- a/server/services/worktreeReap.test.js+++ b/server/services/worktreeReap.test.js@@ -10,7 +10,7 @@* 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 } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';import { mkdtemp, rm, writeFile, mkdir, chmod } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';@@ -24,6 +24,8 @@ import {} from '../lib/gitTestRepo.js';import { hasBranchMergeEvidence } from './git.js';import { reapMergedWorktrees } from './worktreeManager.js';+vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: async () => null }));+vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: {} }) }));/*** Why `wantedPath` was skipped, matched separator-insensitively — `skipped[].path`@@ -281,8 +283,10 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {}expect(result.reaped.map(r => r.branch)).not.toContain('stuck-br');- expect(skipReason(result, path)).toBe('remove-failed');- expect(result.skipped.find(entry => entry.reason === 'remove-failed').warning).toMatch(/cleanup incomplete/);+ // Git removed its registration before failing to remove the directory.+ // The fallback cannot prove the surviving directory is still our holder.+ expect(skipReason(result, path)).toBe('worktree-holder-changed');+ expect(result.skipped.find(entry => entry.path === path).warning).toMatch(/cleanup incomplete/);expect(existsSync(path)).toBe(true);const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');expect(branches).toContain('stuck-br');