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: attach review-loop follow-ups for default-branch PRs (release PRs) detached instead of looping on worktree-busy (#12855)
[._.]/ Adam Eivyb9023e3a47be
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 7a082ea95b..f12e6b4ae7 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -573,12 +573,13 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfodiscardWorktree,claimFlow,noChangeSuccess,+ headIsDefaultBranch: worktreeInfo.headIsDefaultBranch === true,}): '';const worktreeSection = worktreeInfo ? `## Git Worktree ContextYou are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.-- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}+- **Branch**: \`${worktreeInfo.branchName}\`${worktreeBranchSuffix(worktreeInfo, isWorktreeOnExistingBranch)}- **Worktree Path**: \`${worktreeInfo.worktreePath}\`${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}@@ -695,6 +696,20 @@ function resolveTaskMetadataFlags(task, worktreeInfo) {};}+/**+ * The follow-up's task metadata plus what only workspace prep knows: the PR head is+ * the default branch, so the checkout is detached and nothing may be pushed to it.+ */+function reviewLoopPromptMetadata(task, worktreeInfo) {+ const metadata = task.metadata || {};+ return worktreeInfo?.headIsDefaultBranch === true ? { ...metadata, headIsDefaultBranch: true } : metadata;+}++function worktreeBranchSuffix(worktreeInfo, isWorktreeOnExistingBranch) {+ if (worktreeInfo.detached === true) return ' *(detached at the PR head — do not commit to or push this branch)*';+ return isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : '';+}+/** Load independent developer context concurrently, unless this is a content-only task. */async function loadDeveloperContext(task, config, workspaceDir, skipDevContext) {if (skipDevContext) {@@ -784,7 +799,7 @@ After your task completes, the system will spawn a follow-up agent that runs the// localAgentLoopBody (the CLI-reviewer recipe) was already preloaded at the// top of buildAgentPrompt under the same reviewLoopFollowUp guard — reuse it// rather than re-reading the lib a second time.- reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody, localAgentLoopBody });+ reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(reviewLoopPromptMetadata(task, worktreeInfo), { verbose: true, rprBody, localAgentLoopBody });if (!isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)) reviewLoopFollowUpSection += '\n\n' + buildMergeAdmissionSection(agentId);if (isTui) {const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);@@ -1161,7 +1176,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t})),[COMPLETION_MODES.READ_ONLY]: () => contractSections.push(buildReadOnlyCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),[COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => {- contractSections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));+ contractSections.push(buildReviewLoopFollowUpSection(reviewLoopPromptMetadata(task, worktreeInfo), { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));if (!isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)) contractSections.push(buildMergeAdmissionSection(agentId));if (!isTui) return;const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;@@ -1227,11 +1242,11 @@ function buildLightTaskContextSections({if (worktreeInfo) {sections.push(['## Git Worktree',- `- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}`,+ `- **Branch**: \`${worktreeInfo.branchName}\`${worktreeBranchSuffix(worktreeInfo, isWorktreeOnExistingBranch)}`,`- **Path**: \`${worktreeInfo.worktreePath}\``,worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,'',- worktreeCommitGuidance({ isTui, mode, canTypeSlashCommands, rendersInlinePrLifecycle, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),+ worktreeCommitGuidance({ isTui, mode, canTypeSlashCommands, rendersInlinePrLifecycle, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess, headIsDefaultBranch: worktreeInfo.headIsDefaultBranch === true }),[COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(mode)? 'Follow the bundled workflow branch instructions while preserving unrelated work.': 'Do NOT manually switch branches or modify the worktree configuration.',diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 827c19d0cf..f200320494 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -545,6 +545,39 @@ describe('generic own-PR delivery merges inside repository admission (#11435)',});});+describe('review-loop follow-up on a PR whose head is the default branch (#12855)', () => {+ const metadata = {+ reviewLoopFollowUp: true,+ reviewLoopReviewers: [],+ reviewLoopMergeOnly: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'main',+ reviewLoopPRNumber: 9,+ reviewLoopPROwner: 'o',+ reviewLoopPRRepo: 'r',+ sourceTaskId: 'task-src-release',+ };+ const detached = { branchName: 'main', worktreePath: '/tmp/wt', existingBranch: true, detached: true, headIsDefaultBranch: true };+ const build = (light, worktreeInfo) => light+ ? buildLightContextPrompt(makeTask({ metadata }), '/repo', worktreeInfo, { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId: 'agent-1' })+ : buildAgentPrompt(makeTask({ metadata }), {}, '/repo', worktreeInfo, { providerType: 'api', agentId: 'agent-1' });++ it.each([true, false])('forbids pushing to the head branch and routes a fix through a new PR on the %s light/full path', async (light) => {+ const prompt = await build(light, detached);+ expect(prompt).toContain('NEVER push to the head branch');+ expect(prompt).toContain('open its own PR against the default branch');+ expect(prompt).toContain('DETACHED at the PR head commit');+ // The ordinary existing-branch instruction would tell the agent to push review fixes to `main`.+ expect(prompt).not.toContain('Commit and **push** any review-fix commits to this branch');+ });++ it.each([true, false])('keeps the push-to-branch contract for an ordinary PR branch on the %s light/full path', async (light) => {+ const prompt = await build(light, { branchName: 'main', worktreePath: '/tmp/wt', existingBranch: true });+ expect(prompt).not.toContain('NEVER push to the head branch');+ expect(prompt).not.toContain('DETACHED at the PR head commit');+ });+});+describe('claim-flow completion handoff', () => {it.each([true, false])('honors leave-open on the %s light/full claim path', async (light) => {const task = makeTask({ metadata: { analysisType: 'claim-issue', claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'leave-open' } });diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 7a855769dc..1554d8405d 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -26,7 +26,7 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';* the inline code did.*/-import { basename, join } from 'path';+import { basename, join, resolve } from 'path';import { existsSync } from 'fs';import { execGit } from '../lib/execGit.js';import { emitLog } from './cosEvents.js';@@ -122,6 +122,9 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,});if (!Array.isArray(agents)) return { refused: 'ownership-unreadable' };const worktrees = await listWorktrees(workspacePath).catch(() => null);+ // A branch the primary checkout holds is never adopted, released or waited out:+ // `createWorktree` attaches detached at its head instead.+ if (worktrees?.some(wt => resolve(wt.path) === resolve(workspacePath) && wt.branch?.replace(/^refs\/heads\//, '') === branchName)) return null;const admission = claimBranchAdmission({branchName, preferredPath: allowLiveClaim ? preferredPath : null,agentId, sourceWorkspace: workspacePath, agents, worktrees,diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 9f99108429..7888fb322c 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -751,6 +751,24 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktreexpect(updateTask).not.toHaveBeenCalled();});+ // A release PR's head is the default branch, which the primary checkout holds. That+ // checkout is never adopted or released; the worktree comes up detached on the first+ // attempt rather than pausing on `worktree-busy` for a holder that never leaves (#12855).+ it('never offers the primary checkout for adoption and starts the follow-up without a cooldown', async () => {+ listWorktrees.mockResolvedValue([{ path: PATHS.root, branch: 'refs/heads/main', head: 'a'.repeat(40) }]);+ const detached = { worktreePath: '/mock/worktrees/agent-new', branchName: 'main', baseBranch: null, existingBranch: true, detached: true, headIsDefaultBranch: true };+ createWorktree.mockReset();+ createWorktree.mockResolvedValue(detached);++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask({ reviewLoopPRBranch: 'main' }) });++ expect(findAdoptableWorktreeForBranch).not.toHaveBeenCalled();+ expect(adoptWorktree).not.toHaveBeenCalled();+ expect(createWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), 'sys-rl-1', expect.objectContaining({ existingBranch: 'main' }));+ expect(r).toMatchObject({ outcome: 'ready', worktreeInfo: detached });+ expect(updateTask).not.toHaveBeenCalled();+ });+it('checks a recovered head before adoption and consumes only its initial-launch pin before registration', async () => {const target = { version: 1, repoPath: PATHS.root, branch: 'cos/task-x/agent-y', headSha: 'a'.repeat(40) };const task = followUpTask({ cleanupReviewTarget: target });diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex fcc4e118c1..1fde30f12b 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -12,7 +12,7 @@ import { shellQuote } from '../../lib/shellQuote.js';import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib/prDisposition.js';import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';-import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, reviewPolicyToLoopMetadata, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';+import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, reviewPolicyToLoopMetadata, DEFAULT_BRANCH_HEAD_GUIDANCE, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';import { localApiBaseUrl } from '../../lib/networkExposure.js';import { agentApiCurl } from '../../lib/agentApiToken.js';@@ -720,13 +720,14 @@ export function buildAutoMergeCommitStep(baseBranch = null) {* `canTypeSlashCommands` alone (no separate `isTui` re-check) tells the two* apart from their non-slashdo equivalents.*/-export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false, noChangeSuccess = false }) {+export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false, noChangeSuccess = false, headIsDefaultBranch = false }) {if (mode === COMPLETION_MODES.AUDIT_FLOW) return AUDIT_FLOW_GUIDANCE;if (mode === COMPLETION_MODES.RECONCILE_FLOW) return RECONCILE_FLOW_GUIDANCE;if (mode === COMPLETION_MODES.CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY_GUIDANCE;if (mode === COMPLETION_MODES.RELEASE_FLOW) return RELEASE_FLOW_GUIDANCE;if (discardWorktree) return DISCARD_WORKTREE_NOTE;if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';+ if (headIsDefaultBranch) return DEFAULT_BRANCH_HEAD_GUIDANCE;if (isTui) return withNoChangeAuditGuidance('Commit your changes to this branch — see **Completion Workflow** below.', noChangeSuccess);if (isWorktreeOnExistingBranch) {return withNoChangeAuditGuidance('Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.', noChangeSuccess);diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex fa5ea1beef..2ea06e85d0 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -751,7 +751,8 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const leaveOpen = isTruthyMeta(metadata.reviewLoopLeaveOpen);const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';- const forkNote = buildForkBranchInstructions(prBranch, metadata.forkHead);+ const forkNote = buildForkBranchInstructions(prBranch, metadata.forkHead)+ + buildDefaultBranchHeadInstructions(prBranch, isTruthyMeta(metadata.headIsDefaultBranch));const prNumber = metadata.reviewLoopPRNumber ?? '';const prOwner = metadata.reviewLoopPROwner ?? '';const prRepo = metadata.reviewLoopPRRepo ?? '';@@ -1276,6 +1277,18 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '].join('\n');}+/**+ * The checkout is detached at the reviewed head because the PR's head branch IS the+ * default branch (a release PR). Review fixes pushed straight to it would skip the+ * normal PR flow, so the only way to change that head is a new branch and PR.+ */+export const DEFAULT_BRANCH_HEAD_GUIDANCE = 'This checkout is DETACHED at the PR head commit because the PR\'s head branch is the repository\'s default branch. Do NOT commit to it and NEVER push to the head branch. Read, test and gate the exact reviewed commit; if a fix is required, cut a new branch from it, push that branch and open its own PR against the default branch.';++export function buildDefaultBranchHeadInstructions(branch, headIsDefaultBranch) {+ if (!headIsDefaultBranch || !branch) return '';+ return `Head branch \`${branch}\` is the default branch: ${DEFAULT_BRANCH_HEAD_GUIDANCE} A release PR is otherwise gated on CI and merged as-is, so the merge steps below still apply to the PR itself.\n\n`;+}+/** Explicit pushes preserve fork destinations without changing repository-wide Git defaults. */export function buildForkBranchInstructions(branch, forkHead) {const fork = normalizeForkHead(forkHead);diff --git a/server/services/worktreeManager.defaultHead.test.js b/server/services/worktreeManager.defaultHead.test.jsnew file mode 100644index 0000000000..2b42f816be--- /dev/null+++ b/server/services/worktreeManager.defaultHead.test.js@@ -0,0 +1,120 @@+// Real git: a review-loop follow-up for a PR whose head branch is the default+// branch (a release PR, main -> release) must get a worktree on its first+// attempt. `git worktree add main` is refused while the primary checkout holds+// it, so the follow-up attaches DETACHED at the reviewed commit instead.+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { existsSync } from 'fs';+import { writeFile } from 'fs/promises';+import { join } from 'path';+import { mockPathsDataRoot, mockTestIdentity } from '../lib/mockPathsDataRoot.js';+import { destroyGitSandbox, makeGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { execGit } from '../lib/execGit.js';++const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-worktree-defaulthead-' });+vi.mock('../lib/fileUtils.js', async importOriginal => makeProxy(await importOriginal()));+vi.mock('./instanceIdentity.js', () => mockTestIdentity());+const { PATHS } = await import('../lib/fileUtils.js');+const { createWorktree, removeWorktree, PINNED_HEAD_MOVED } = await import('./worktreeManager.js');+afterAll(cleanup);++const FEATURE = 'contributor/fix-thing';+const git = async (args, cwd) => (await execGit(args, cwd)).stdout.trim();++async function commitOnto(cwd, file) {+ await writeFile(join(cwd, file), `${file}\n`);+ await execGit(['add', file], cwd);+ await execGit(['commit', '-m', file], cwd);+ return git(['rev-parse', 'HEAD'], cwd);+}++describe.skipIf(SKIP_HEAVY_INTEGRATION)('createWorktree for a PR whose head branch the primary checkout holds', () => {+ let sandbox;+ beforeEach(async () => {+ if (sandbox) await destroyGitSandbox(sandbox.scratch);+ sandbox = await makeGitSandbox({ origin: true, prefix: 'portos-defaulthead-' });+ });+ afterAll(async () => { if (sandbox) await destroyGitSandbox(sandbox.scratch); });++ it('detaches at the default-branch head on the first attempt and leaves the primary checkout alone', async () => {+ const head = await commitOnto(sandbox.repo, 'release-notes.txt');+ await execGit(['push', 'origin', 'main'], sandbox.repo);++ const info = await createWorktree('agent-release', sandbox.repo, 'task-release', { existingBranch: 'main' });++ expect(info).toMatchObject({ detached: true, headIsDefaultBranch: true, headSha: head, existingBranch: true });+ expect(await git(['rev-parse', 'HEAD'], info.worktreePath)).toBe(head);+ // Detached: `git push` has no branch to default to.+ expect((await execGit(['symbolic-ref', '-q', 'HEAD'], info.worktreePath, { ignoreExitCode: true })).exitCode).not.toBe(0);+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], sandbox.repo)).toBe('main');+ });++ it('pins the detached head to the reviewed commit and refuses once the default branch moved', async () => {+ const reviewed = await commitOnto(sandbox.repo, 'reviewed.txt');+ await execGit(['push', 'origin', 'main'], sandbox.repo);++ const info = await createWorktree('agent-pinned', sandbox.repo, 'task-pinned', { existingBranch: 'main', expectedHeadSha: reviewed });+ expect(info).toMatchObject({ detached: true, headIsDefaultBranch: true, headSha: reviewed });+ expect(await git(['rev-parse', 'HEAD'], info.worktreePath)).toBe(reviewed);++ await commitOnto(sandbox.repo, 'unreviewed.txt');+ await execGit(['push', 'origin', 'main'], sandbox.repo);+ await expect(createWorktree('agent-moved', sandbox.repo, 'task-moved', { existingBranch: 'main', expectedHeadSha: reviewed }))+ .rejects.toMatchObject({ code: PINNED_HEAD_MOVED });+ expect(existsSync(join(PATHS.worktrees, 'agent-moved'))).toBe(false);+ });++ it('detaches a non-default branch the primary checkout has checked out, without flagging it as the default', async () => {+ await execGit(['checkout', '-b', FEATURE], sandbox.repo);+ const head = await commitOnto(sandbox.repo, 'feature.txt');+ await execGit(['push', 'origin', FEATURE], sandbox.repo);++ const info = await createWorktree('agent-held', sandbox.repo, 'task-held', { existingBranch: FEATURE });++ expect(info).toMatchObject({ detached: true, headIsDefaultBranch: false, headSha: head });+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], sandbox.repo)).toBe(FEATURE);+ });++ it('still attaches an ordinary feature-branch PR by name', async () => {+ await execGit(['checkout', '-b', FEATURE], sandbox.repo);+ const head = await commitOnto(sandbox.repo, 'feature.txt');+ await execGit(['push', 'origin', FEATURE], sandbox.repo);+ await execGit(['checkout', 'main'], sandbox.repo);+ await execGit(['branch', '-D', FEATURE], sandbox.repo);++ const info = await createWorktree('agent-feature', sandbox.repo, 'task-feature', { existingBranch: FEATURE });++ expect(info.detached).toBeUndefined();+ expect(info.headIsDefaultBranch).toBeUndefined();+ expect(info.branchName).toBe(FEATURE);+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], info.worktreePath)).toBe(FEATURE);+ expect(await git(['rev-parse', 'HEAD'], info.worktreePath)).toBe(head);+ });++ describe('removeWorktree on the detached checkout', () => {+ it('retires a clean published checkout without touching the default branch ref or the primary checkout', async () => {+ await commitOnto(sandbox.repo, 'release-notes.txt');+ await execGit(['push', 'origin', 'main'], sandbox.repo);+ const mainBefore = await git(['rev-parse', 'refs/heads/main'], sandbox.repo);+ const info = await createWorktree('agent-clean', sandbox.repo, 'task-clean', { existingBranch: 'main' });++ const result = await removeWorktree('agent-clean', sandbox.repo, 'main', { merge: false });++ expect(result).toMatchObject({ removed: true });+ expect(existsSync(info.worktreePath)).toBe(false);+ expect(await git(['rev-parse', 'refs/heads/main'], sandbox.repo)).toBe(mainBefore);+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], sandbox.repo)).toBe('main');+ });++ it('keeps a checkout holding a commit no remote branch contains', async () => {+ await execGit(['push', 'origin', 'main'], sandbox.repo);+ const info = await createWorktree('agent-unpublished', sandbox.repo, 'task-unpublished', { existingBranch: 'main' });+ await commitOnto(info.worktreePath, 'stray-fix.txt');++ const result = await removeWorktree('agent-unpublished', sandbox.repo, 'main', { merge: false });++ expect(result.removed).toBe(false);+ expect(result.warnings.join(' ')).toContain('detached-head-unpublished');+ expect(existsSync(info.worktreePath)).toBe(true);+ });+ });+});diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex b2d91a3f86..9a0f51390c 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -787,8 +787,9 @@ function pinnedHeadMoved(branchName, pinnedHead, actual) {* names its destination so the tracking ref cannot stay stale under a narrow* refspec. The checkout uses the SHA, so a ref update after the check cannot* swap code in; an existing local branch must already name that exact commit.+ * `detach` checks the commit out with no branch at all (see `holdsCheckedOutBranch`).*/-async function attachPinnedHead(sourceWorkspace, worktreePath, branchName, remoteBranch, remote, pinnedHead, localExists) {+async function attachPinnedHead(sourceWorkspace, worktreePath, branchName, remoteBranch, remote, pinnedHead, localExists, { detach = false } = {}) {const listed = await execGit(['ls-remote', '--exit-code', remote, `refs/heads/${remoteBranch}`], sourceWorkspace, { ignoreExitCode: true });// `--exit-code` answers 2 for "no such ref"; anything else non-zero is a// transport failure, which proves nothing about the branch.@@ -802,7 +803,9 @@ async function attachPinnedHead(sourceWorkspace, worktreePath, branchName, remotconst fetched = (await execGit(['rev-parse', '--verify', `${trackingRef}^{commit}`], sourceWorkspace)).stdout.trim();if (fetched !== pinnedHead) throw pinnedHeadMoved(branchName, pinnedHead, fetched);- if (localExists) {+ if (detach) {+ await addWorktreeWithRetry(['worktree', 'add', '--detach', worktreePath, pinnedHead], sourceWorkspace);+ } else if (localExists) {const localHead = (await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace)).stdout.trim();if (localHead !== pinnedHead) {throw new Error(`Cannot attach worktree to ${branchName}: the local branch differs from the reviewed head; preserving it without reset`);@@ -816,6 +819,39 @@ async function attachPinnedHead(sourceWorkspace, worktreePath, branchName, remotif (attached !== pinnedHead) throw pinnedHeadMoved(branchName, pinnedHead, attached);}+/**+ * Is `branch` one a second worktree must never attach to by name: the repository's+ * default branch, or whatever the primary checkout has checked out? Git refuses the+ * second case outright, and the first is the branch a review fix must never be+ * pushed to without its own pull request (a release PR's head IS the default branch).+ */+async function holdsCheckedOutBranch(sourceWorkspace, branch, baseBranch) {+ const { getDefaultBranch } = await import('./git.js');+ const defaultBranch = baseBranch || await getDefaultBranch(sourceWorkspace, { allowRemote: false }).catch(() => null);+ if (branch === defaultBranch) return { held: true, isDefault: true };+ const current = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace, { ignoreExitCode: true }).catch(() => null))?.stdout?.trim();+ return { held: current === branch, isDefault: false };+}++/**+ * Detached worktree at the reviewed head of a branch the primary checkout owns.+ * The follow-up can read, test and gate that exact commit; with no branch checked+ * out there is nothing for `git push` to default to and nothing for another+ * worktree to collide with. Fork heads never come here: they attach under their+ * own `fork/<owner>/<branch>` name.+ */+async function attachDetachedHead(sourceWorkspace, worktreePath, branch, pinnedHead, fetchSucceeded) {+ if (pinnedHead) {+ await attachPinnedHead(sourceWorkspace, worktreePath, branch, branch, 'origin', pinnedHead, false, { detach: true });+ return pinnedHead;+ }+ const head = await execGit(['rev-parse', '--verify', `refs/remotes/origin/${branch}^{commit}`], sourceWorkspace, { ignoreExitCode: true })+ .then(r => (r.exitCode === 0 ? r.stdout.trim() : ''), () => '');+ if (!head) throw new Error(`Cannot attach worktree to ${branch}: origin/${branch} unavailable${fetchSucceeded ? '' : ' (fetch failed)'}`);+ await addWorktreeWithRetry(['worktree', 'add', '--detach', worktreePath, head], sourceWorkspace);+ return head;+}+/*** Create a git worktree for an agent.*@@ -838,7 +874,7 @@ async function attachPinnedHead(sourceWorkspace, worktreePath, branchName, remot* @param {object} options - Optional configuration* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)* @param {string} options.baseCommit - Exact server-owned source commit for a fresh Deep resume- * @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)+ * @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy). When it is the default branch or the primary checkout's own branch the worktree is DETACHED at the branch's reviewed head instead (`detached: true` in the result).* @param {string} options.resumeBranch - Exact preserved local branch from a retry, including pre-namespace fork branches* @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives for a fork PR; checked out as fork/<owner>/<branch>.* @param {string} options.expectedHeadSha - Attach only at the reviewed remote tip; existing local work is never reset.@@ -887,6 +923,22 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, optionsconst pinnedHead = options.expectedHeadSha === undefined ? null : requirePinnedHeadSha(options.expectedHeadSha);const forkHead = normalizeForkHead(options.forkHead);if (options.forkHead && !forkHead) throw new Error('Invalid fork head coordinates');+ const checkedOut = forkHead || options.resumeBranch+ ? { held: false, isDefault: false }+ : await holdsCheckedOutBranch(sourceWorkspace, remoteBranch, options.baseBranch);+ if (checkedOut.held) {+ const headSha = await attachDetachedHead(sourceWorkspace, worktreePath, remoteBranch, pinnedHead, fetchSucceeded);+ if (options.linkDependencies === false) {+ await unlinkWorktreeDependencies(sourceWorkspace, worktreePath);+ } else {+ await linkWorktreeDependencies(sourceWorkspace, worktreePath);+ }+ console.log(`🌳 Created detached worktree for ${agentId} at ${worktreePath} on ${remoteBranch}@${headSha.slice(0, 12)} (primary checkout holds the branch)`);+ return {+ worktreePath, branchName: remoteBranch, baseBranch: null, existingBranch: true, instanceId,+ detached: true, headSha, headIsDefaultBranch: checkedOut.isDefault,+ };+ }const branchName = options.resumeBranch || forkLocalBranch(remoteBranch, forkHead);const localExists = (await execGit(['branch', '--list', branchName], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();if (options.resumeBranch && !localExists) throw new Error(`Cannot resume missing local branch ${branchName}`);@@ -1497,15 +1549,29 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,if (!head || (expectedHead && head !== expectedHead)) return 'branch-head-changed-or-unavailable';return await hasBranchMergeEvidence(sourceWorkspace, head, mergeTarget).catch(() => false) ? null : 'merge-evidence-unavailable';};+ // A follow-up on a branch the primary checkout owns runs DETACHED (createWorktree):+ // there is no branch to protect, merge or delete, so only its commits matter.+ // Probed lazily: every early refusal above the archive step is a pure-status exit.+ let detachedProbe = null;+ const detachedCheckout = () => detachedProbe ||= listWorktrees(sourceWorkspace)+ .then(trees => trees.find(wt => canonicalPath(wt.path) === canonicalPath(worktreePath) && wt.detached && !wt.branch) || null, () => null);+ const detachedHold = async (head) => {+ const owner = await ownershipHold();+ if (owner) return owner;+ const contained = await execGit(['branch', '-r', '--contains', head], sourceWorkspace, { ignoreExitCode: true }).catch(() => null);+ return contained?.exitCode === 0 && contained.stdout.trim() ? null : 'detached-head-unpublished';+ };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 detached = Boolean(await detachedCheckout());+ if (!tree || (detached ? !tree.detached || tree.branch : tree.branch !== `refs/heads/${branchName}`)) throw new Error('worktree-holder-changed');const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');- const hold = await completionHold(tree.head);+ const checkHold = detached ? detachedHold : completionHold;+ const hold = await checkHold(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) };+ verify: async holder => await checkHold(tree.head) || await archive.verify(holder) };};// One archive between two critical sections. `admit` (under the lock, after the// owner re-read) returns a result to stop before fencing; `finish` runs under the@@ -1548,7 +1614,7 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,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 { result: held(protectedReason) };+ if (protectedReason && !await detachedCheckout()) return { result: held(protectedReason) };// A retirement archiving this checkout with the lock released owns it until removal.const owner = checkoutRetirementFenceReason(fence) || await ownershipHold();if (owner) return { result: held(owner) };@@ -1668,7 +1734,7 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,return retire({admit: async () => {- if (!options.merge) return null;+ if (!options.merge || await detachedCheckout()) return null;const currentBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'],sourceWorkspace@@ -1735,7 +1801,7 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,// Merge evidence and completion policy were checked before removal; the// branch helper checks them again before its leased local deletion.- if (await cleanupBranch(preservation.head)) console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);+ if (await detachedCheckout() || await cleanupBranch(preservation.head)) console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);return { merged, removed: true, uncommittedSaved: false, warnings };},});