scrum4me-mcp/src/git/worktree.ts
Janpeter Visser 2c85f4d239
feat(routing): cross-repo task routing + orphan-branch cleanup (#17)
Two related fixes for the agent-workflow defects exposed by the
2-May-2026 batch:

1. **Cross-repo task routing** (`task.repo_url` override).
   `resolveRepoRoot` now consults `task.repo_url` first; matches against
   per-repo env-var (`SCRUM4ME_REPO_ROOT_REPO_<name>`),
   `~/.scrum4me-agent-config.json` `repoRoots[<name>]`, and finally
   `~/Projects/<name>/.git`. Falls back to product-level resolution
   when null. Tasks tracked under one product but targeting another
   repo (e.g. MCP-server tasks under the main product's PBI) now work.
   `getFullJobContext` exposes `task.repo_url` to the agent.
   `attachWorktreeToJob` accepts and forwards it.

2. **Orphan-branch cleanup** in `createWorktreeForJob`.
   Previously a name-collision suffixed with a timestamp, leaving the
   agent on an unpredictable `feat/story-XXX-<ms>`-name. Worse, in the
   2-May batch the agent ended up reusing an orphan branch from an
   earlier story (`feat/story-x35n155c`) and pushed to a remote ref
   that did not exist, causing 'src refspec does not match any'.

   Now: detect orphan, attempt to remove its (stale) worktree if any,
   delete the local branch, and recreate with the predictable name.
   Timestamp-suffix is the last resort.

Vendor submodule bumped to pick up `Task.repo_url` from Scrum4Me #54.

Tests: 129/129 — `suffixes branch name with timestamp` updated to
`removes orphan branch and reuses the predictable name`.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 18:07:57 +02:00

155 lines
5.1 KiB
TypeScript

import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import * as path from 'node:path'
import * as os from 'node:os'
import * as fs from 'node:fs/promises'
const exec = promisify(execFile)
async function branchExists(repoRoot: string, name: string): Promise<boolean> {
try {
await exec('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`], { cwd: repoRoot })
return true
} catch {
return false
}
}
async function findWorktreeForBranch(
repoRoot: string,
branchName: string,
): Promise<string | null> {
try {
const { stdout } = await exec('git', ['worktree', 'list', '--porcelain'], { cwd: repoRoot })
// Porcelain blocks: worktree <path>\nHEAD <sha>\nbranch refs/heads/<name>\n\n
const blocks = stdout.split('\n\n').filter(Boolean)
for (const block of blocks) {
const lines = block.split('\n')
const wt = lines.find((l) => l.startsWith('worktree '))?.slice(9)
const br = lines.find((l) => l.startsWith('branch '))?.slice(7) // refs/heads/<name>
if (wt && br && br === `refs/heads/${branchName}`) return wt
}
return null
} catch {
return null
}
}
export async function createWorktreeForJob(opts: {
repoRoot: string
jobId: string
branchName: string
baseRef?: string
/**
* When true the branch is expected to exist already (sibling job created it).
* If a stale sibling worktree still occupies the branch, it is removed first
* — siblings are sequential, so this is safe.
*/
reuseBranch?: boolean
}): Promise<{ worktreePath: string; branchName: string }> {
const { repoRoot, jobId, baseRef = 'origin/main', reuseBranch = false } = opts
let { branchName } = opts
const parent =
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
path.join(os.homedir(), '.scrum4me-agent-worktrees')
await fs.mkdir(parent, { recursive: true })
const worktreePath = path.join(parent, jobId)
// Reject if worktree path already exists — caller must remove it first
try {
await fs.access(worktreePath)
throw new Error(
`Worktree path already exists: ${worktreePath}. Call removeWorktreeForJob first.`,
)
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
}
await exec('git', ['fetch', 'origin', '--prune'], { cwd: repoRoot })
if (reuseBranch) {
// Sibling task already created the branch; check it out into a fresh worktree.
// If the branch is still attached to a stale sibling worktree, drop that first.
const occupant = await findWorktreeForBranch(repoRoot, branchName)
if (occupant) {
await exec('git', ['worktree', 'remove', '--force', occupant], { cwd: repoRoot })
}
await exec('git', ['worktree', 'add', worktreePath, branchName], { cwd: repoRoot })
return { worktreePath, branchName }
}
// Fresh branch: if a local branch with this name already exists, it is an
// orphan from a prior failed run (the agent didn't push or branch was
// never tied to a worktree). Remove the orphan so the new worktree gets
// the predictable `feat/story-<id>`-name; this prevents the kind of
// 2-May-2026 failure where the agent inherited an unrelated suffix and
// pushed to a non-existent remote ref.
if (await branchExists(repoRoot, branchName)) {
const occupant = await findWorktreeForBranch(repoRoot, branchName)
if (occupant) {
// Branch is currently checked out elsewhere — likely a sibling worktree
// that should have been cleaned up. Remove it before reusing the name.
try {
await exec('git', ['worktree', 'remove', '--force', occupant], { cwd: repoRoot })
} catch {
// ignore — fall through to deletion below
}
}
try {
await exec('git', ['branch', '-D', branchName], { cwd: repoRoot })
console.warn(`[createWorktreeForJob] removed orphan branch ${branchName} before recreate`)
} catch {
// last resort: timestamp-suffix to avoid collision rather than fail
branchName = `${branchName}-${Date.now()}`
}
}
await exec('git', ['worktree', 'add', '-b', branchName, worktreePath, baseRef], {
cwd: repoRoot,
})
return { worktreePath, branchName }
}
export async function removeWorktreeForJob(opts: {
repoRoot: string
jobId: string
keepBranch?: boolean
}): Promise<{ removed: boolean }> {
const { repoRoot, jobId, keepBranch = false } = opts
const parent =
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
path.join(os.homedir(), '.scrum4me-agent-worktrees')
const worktreePath = path.join(parent, jobId)
try {
await fs.access(worktreePath)
} catch {
return { removed: false }
}
let branchName: string | undefined
if (!keepBranch) {
try {
const { stdout } = await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
cwd: worktreePath,
})
branchName = stdout.trim()
} catch {
// worktree HEAD unreadable — skip branch deletion
}
}
await exec('git', ['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot })
if (!keepBranch && branchName && (await branchExists(repoRoot, branchName))) {
await exec('git', ['branch', '-D', branchName], { cwd: repoRoot })
}
return { removed: true }
}