{"record":{"id":"dbf81e063a97a761","repo":"coleam00/Archon","slug":"cannot-adopt-worktree-at-worktreepath-expect","errorCode":null,"errorMessage":"Cannot adopt worktree at '${worktreePath}': expected branch '${exactTaskBranch}', found '${actualBranch ?? 'detached HEAD'}'.","messagePattern":"Cannot adopt worktree at '(.+?)': expected branch '(.+?)', found '(.+?)'\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/isolation/src/providers/worktree.ts","lineNumber":684,"sourceCode":"        await verifyWorktreeOwnership(toWorktreePath(worktreePath), request.canonicalRepoPath);\n      } catch (err) {\n        getLog().warn(\n          {\n            worktreePath,\n            branchName,\n            codebaseId: request.codebaseId,\n            canonicalRepoPath: request.canonicalRepoPath,\n            err: (err as Error).message,\n          },\n          'worktree.adoption_refused_cross_checkout'\n        );\n        throw err;\n      }\n\n      if (exactTaskBranch) {\n        const actualBranch = await getCurrentBranchStrict(toWorktreePath(worktreePath));\n        if (actualBranch !== exactTaskBranch) {\n          throw new Error(\n            `Cannot adopt worktree at '${worktreePath}': expected branch ` +\n              `'${exactTaskBranch}', found '${actualBranch ?? 'detached HEAD'}'.`\n          );\n        }\n      }\n\n      getLog().info({ worktreePath, branchName }, 'worktree_adopted');\n      return this.buildAdoptedEnvironment(worktreePath, branchName, request);\n    }\n\n    // Exact-branch requests also search Git's registered worktrees because an\n    // external tool may have created the checkout at a non-Archon path.\n    const exactBranch = isPRIsolationRequest(request) ? request.prBranch : exactTaskBranch;\n    if (exactBranch) {\n      const existingByBranch = exactTaskBranch\n        ? ((await listWorktrees(request.canonicalRepoPath)).find(\n            worktree => worktree.branch === exactTaskBranch\n          )?.path ?? null)","sourceCodeStart":666,"sourceCodeEnd":702,"githubUrl":"https://github.com/coleam00/Archon/blob/0773b9745896ef0612e709c80845a0f7db315b19/packages/isolation/src/providers/worktree.ts#L666-L702","documentation":"When adopting an existing worktree for a task that requested an existing branch (taskBranch.kind === 'existing'), findExisting verifies the worktree's current checked-out branch with getCurrentBranchStrict. If it differs from the requested branch — including a detached HEAD — adoption is refused to avoid working against the wrong branch.","triggerScenarios":"WorktreeProvider.create with workflowType 'task' and taskBranch {kind:'existing', branch:X} finds an existing worktree at the expected path (or registered by branch), but `git branch --show-current` in that worktree returns Y !== X, or returns empty (detached HEAD).","commonSituations":"Someone manually checked out a different branch or committed in detached-HEAD state inside the shared worktree; a previous run left the worktree on another branch; a second task reusing the same worktree path expects a different existing branch.","solutions":["In the worktree, run `git checkout <expected-branch>` to match the requested task branch, then rerun","If the worktree is stale or wrong, remove it (`git worktree remove <path>`) so Archon creates a fresh one on the correct branch","If the worktree legitimately holds another task's branch, let that task's run finish or choose a different existing branch","Check `git status` / `git log` in the worktree to understand who moved HEAD before discarding anything"],"exampleFix":"# before (inside the worktree)\ngit checkout experimental\n# after\ngit checkout expected-task-branch","handlingStrategy":"try-catch","validationCode":"import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nconst execFileAsync = promisify(execFile);\nexport async function worktreeBranchMatches(worktreePath: string, expected: string): Promise<boolean> {\n  const { stdout } = await execFileAsync('git', ['-C', worktreePath, 'branch', '--show-current']);\n  return stdout.trim() === expected;\n}","typeGuard":null,"tryCatchPattern":"try {\n  const env = await provider.create(request);\n} catch (e) {\n  const msg = (e as Error).message;\n  if (msg.includes('Cannot adopt worktree')) {\n    // Inspect/reset the worktree, or remove it so a fresh one is created\n    const path = msg.match(/at '([^']+)'/)?.[1];\n    console.error(`Worktree ${path} is on the wrong branch; checkout the expected branch or remove it.`);\n  }\n  throw e;\n}","preventionTips":["Don't manually switch branches inside Archon-managed worktrees","Before reusing an existing task branch, check its worktree's current branch","Clean up finished task worktrees so stale checkouts aren't re-adopted","Avoid committing while in detached-HEAD state in shared worktrees"],"tags":["git","worktree","branch-mismatch","adoption"],"backgroundTag":"worktree-branch-mismatch","analyzedSha":"0773b9745896ef0612e709c80845a0f7db315b19","analyzedAt":"2026-09-01T02:28:07.064Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}