Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): a slow worktree checkout is used, a failed one is cleaned up, and git's reason is logged (#1837)

0xken15909aeeb40f52
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index 85e7bfe62..1c3347044 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -474,6 +474,162 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
})
})
+ describe('a worktree whose git is slow or fails', () => {
+ const harnesses = () => join(root, 'harnesses')
+ const listed = () => git('worktree', 'list', '--porcelain')
+ /** A file checked out through the `name` filter, whose smudge command is [smudge]. Set after the
+ * commit: `git add` needs no filter. */
+ const filtered = async (name: string, smudge: string) => {
+ await writeFile(join(repo, '.gitattributes'), `filtered filter=${name}\n`)
+ await writeFile(join(repo, 'filtered'), 'content\n')
+ await git('add', '.')
+ await git('commit', '-m', 'filtered file')
+ await git('config', `filter.${name}.smudge`, smudge)
+ await git('config', `filter.${name}.required`, 'true')
+ }
+ afterEach(() => { vi.restoreAllMocks() })
+
+ it('uses a checkout that finished although git was still running at the timeout, and stops what git left running', async () => {
+ // git checked everything out and is in its post-checkout hook when the time runs out.
+ const hooks = join(root, 'hooks')
+ await mkdir(hooks)
+ const pidFile = join(root, 'hook.pid')
+ await writeFile(join(hooks, 'post-checkout'), `#!/bin/sh\necho $$ > '${pidFile}'\nexec sleep 60\n`, { mode: 0o755 })
+ await git('config', 'core.hooksPath', hooks)
+ const path = await prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'slow', worktreeTimeout: 1_500 })
+ expect(path).toBe(join(worktrees(), 'slow'))
+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')
+ expect(await current(path)).toBe('slow')
+ expect(await git('config', '--get', 'branch.slow.harness')).toBe('created')
+ // Unlocked: git marks a worktree locked while it is being made.
+ const real = await realpath(path)
+ const entry = (await listed()).split(/\n\s*\n/).find(block => block.includes(`worktree ${real}`))
+ expect(entry).toBeDefined()
+ expect(entry).not.toContain('locked')
+ const hookPid = Number((await readFile(pidFile, 'utf8')).trim())
+ expect(() => process.kill(hookPid, 0)).toThrow()
+ }, 20_000)
+
+ it('removes the partial folder and its new branch when the checkout is cut off at the timeout', async () => {
+ await filtered('slow', 'sleep 60; cat')
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'cut', worktreeTimeout: 1_500 }))
+ .rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ await expect(readFile(join(worktrees(), 'cut', 'src', 'value'))).rejects.toThrow()
+ await expect(realpath(join(worktrees(), 'cut'))).rejects.toThrow()
+ expect(await git('branch', '--list', 'cut')).toBe('')
+ expect(await listed()).not.toContain('cut')
+ }, 20_000)
+
+ it('says why git failed, without credentials, and leaves no partial folder or new branch', async () => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await filtered('broken', "echo 'cannot reach https://robot:[email protected]/lfs' >&2; exit 1")
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'broken' }))
+ .rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ const lines = said.mock.calls.map(call => call.join(' ')).filter(line => line.startsWith('[worktree]'))
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toContain('exit 128')
+ expect(lines[0]).toContain('cannot reach https://')
+ expect(lines[0]).not.toContain('s3cret-token')
+ await expect(realpath(join(worktrees(), 'broken'))).rejects.toThrow()
+ expect(await git('branch', '--list', 'broken')).toBe('')
+ expect(await listed()).not.toContain('broken')
+ // The next start finds the name free.
+ await git('config', '--unset', 'filter.broken.required')
+ await git('config', 'filter.broken.smudge', 'cat')
+ expect(await prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'broken' })).toBe(join(worktrees(), 'broken'))
+ })
+
+ it('leaves a registration that existed before the failed start, even one for the same folder', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ // An earlier worktree at the folder this start picks, whose folder was deleted without `git worktree remove`.
+ await git('worktree', 'add', '-b', 'earlier', '--', join(worktrees(), 'again'), 'main')
+ await rm(join(worktrees(), 'again'), { recursive: true, force: true })
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'again' }))
+ .rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ expect(await listed()).toContain('branch refs/heads/earlier')
+ expect(await git('branch', '--list', 'again')).toBe('')
+ })
+
+ it('never deletes a branch a person made at their own commit after the first check and before the add', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ // git, as the daemon runs it, with the person's own `git branch mine feature` landing just after the name was checked.
+ const realGit = (await exec('sh', ['-c', 'command -v git'])).stdout.trim()
+ const bin = join(root, 'bin'), made = join(root, 'person-made-it')
+ await mkdir(bin)
+ await writeFile(join(bin, 'git'), `#!/bin/sh\nfor arg in "$@"; do if [ "$arg" = check-ref-format ] && [ ! -e '${made}' ]; then\n`
+ + ` : > '${made}'; '${realGit}' -C '${repo}' branch mine feature\nfi; done\nexec '${realGit}' "$@"\n`, { mode: 0o755 })
+ vi.stubEnv('PATH', `${bin}:${process.env.PATH}`)
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'mine' })).rejects.toMatchObject({ code: 'BRANCH_EXISTS' })
+ expect(await git('rev-parse', 'mine')).toBe(await git('rev-parse', 'feature'))
+ await expect(realpath(join(worktrees(), 'mine'))).rejects.toThrow()
+ expect(await listed()).not.toContain('worktrees/project with spaces/mine')
+ })
+
+ it('logs none of a stateless GitHub token git printed', async () => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const payload = 'eyJpc3MiOiIxMjM0NTYifQ', signature = `${'s'.repeat(470)}-x_y`
+ await filtered('leaky', `echo 'remote refused (token "ghs_123456_eyJhbGciOiJSUzI1NiJ9.${payload}.${signature}"), retry.' >&2; exit 1`)
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'leaky' })).rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ const line = said.mock.calls.map(call => call.join(' ')).find(text => text.startsWith('[worktree]'))!
+ expect(line).toContain('remote refused (token "')
+ expect(line).not.toContain('ghs_123456_')
+ expect(line).not.toContain(payload)
+ expect(line).not.toContain('ssssssss')
+ expect(line).not.toContain('-x_y')
+ })
+
+ describe('on Windows, where taskkill cannot stop what git started', () => {
+ const platform = process.platform
+ beforeEach(async () => {
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true })
+ const bin = join(root, 'bin')
+ await mkdir(bin)
+ await writeFile(join(bin, 'taskkill'), '#!/bin/sh\necho \'ERROR: The process with PID 1 could not be terminated.\' >&2\nexit 1\n', { mode: 0o755 })
+ vi.stubEnv('PATH', `${bin}:${process.env.PATH}`)
+ })
+ afterEach(() => { Object.defineProperty(process, 'platform', { value: platform, configurable: true }) })
+ /** git checks out and exits; its post-checkout hook leaves a process behind, holding git's stderr, that ends after
+ * [seconds] by touching `ended`. */
+ const leftBehind = async (seconds: number) => {
+ const hooks = join(root, 'hooks')
+ await mkdir(hooks)
+ await writeFile(join(hooks, 'post-checkout'), `#!/bin/sh\n(sleep ${seconds}; : > '${join(root, 'ended')}') &\nexit 0\n`, { mode: 0o755 })
+ await git('config', 'core.hooksPath', hooks)
+ }
+
+ it('waits for what git left running to end before it looks at the checkout, and says taskkill failed', async () => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await leftBehind(2)
+ const path = await prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'outlived', worktreeTimeout: 1_500 })
+ expect(await readFile(join(root, 'ended'), 'utf8')).toBe('')
+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')
+ expect(said.mock.calls.map(call => call.join(' ')).join('\n')).toMatch(/\[worktree\] could not stop git.*could not be terminated/)
+ }, 20_000)
+
+ it('removes nothing while something git started may still be writing', async () => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await leftBehind(8)
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'still-running', worktreeTimeout: 1_500 }))
+ .rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ await expect(readFile(join(root, 'ended'))).rejects.toThrow()
+ expect(await readFile(join(worktrees(), 'still-running', 'src', 'value'), 'utf8')).toBe('main')
+ expect(said.mock.calls.map(call => call.join(' ')).join('\n')).toMatch(/\[worktree\] .*still running.*left as it is/)
+ }, 20_000)
+ })
+
+ it('never deletes a branch that existed before the failed start', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ await filtered('broken', 'exit 1')
+ await git('branch', 'topic', 'main')
+ const before = await git('rev-parse', 'topic')
+ await expect(prepareGitProject(repo, { root: harnesses(), worktree: true, branchName: 'topic', existingBranch: true }))
+ .rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
+ expect(await git('rev-parse', 'topic')).toBe(before)
+ await expect(realpath(join(worktrees(), 'topic'))).rejects.toThrow()
+ expect(await listed()).not.toContain('topic')
+ })
+ })
+
it('copies ignored files named in .worktreeinclude into new worktrees', async () => {
await writeFile(join(repo, '.gitignore'), '.env\n*.log\nlocal/\n')
await writeFile(join(repo, '.worktreeinclude'), '.env\nlocal/\n')
@@ -608,19 +764,23 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
.rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })
})
- it('keeps a worktree created before a checkout hook fails so the user can recover it', async () => {
+ it('removes a worktree whose checkout hook fails, so a retry starts clean, and logs what the hook said', async () => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
const hooks = join(root, 'hooks')
await mkdir(hooks)
- await writeFile(join(hooks, 'post-checkout'), '#!/bin/sh\nexit 1\n', { mode: 0o755 })
+ await writeFile(join(hooks, 'post-checkout'), '#!/bin/sh\necho "hook refused" >&2\nexit 1\n', { mode: 0o755 })
await git('config', 'core.hooksPath', hooks)
+ const before = await git('for-each-ref', '--format=%(refname)', 'refs/heads')
await expect(prepare('worktree')).rejects.toMatchObject({ code: 'WORKTREE_FAILED' })
- const linked = (await git('worktree', 'list', '--porcelain')).split('\n')
- .find(line => line.startsWith('worktree ') && line.includes('/worktrees/'))!.slice(9)
- expect(await readFile(join(linked, 'src', 'value'), 'utf8')).toBe('feature')
+ expect(await git('worktree', 'list', '--porcelain')).not.toContain('/worktrees/')
+ expect(await git('for-each-ref', '--format=%(refname)', 'refs/heads')).toBe(before)
+ expect(said.mock.calls.map(call => call.join(' ')).join('\n')).toMatch(/\[worktree\] git worktree add failed \(exit 1\).*hook refused/)
expect(await git('branch', '--show-current')).toBe('main')
+ said.mockRestore()
})
it.each(['No space left on device', 'Disk quota exceeded'])('explains worktree disk exhaustion: %s', async (message) => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
const hooks = join(root, 'hooks')
await mkdir(hooks)
await writeFile(join(hooks, 'post-checkout'), `#!/bin/sh\necho 'private-file: ${message}' >&2\nexit 1\n`, { mode: 0o755 })
@@ -629,5 +789,6 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
code: 'WORKTREE_FAILED',
message: 'Not enough disk space to create the worktree. Free space on this machine, then retry.',
})
+ said.mockRestore()
})
})
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index 7e0dad93b..4b3a11d2a 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -1,9 +1,10 @@
-import { execFile } from 'node:child_process'
-import { cp, lstat, mkdir, realpath, stat, writeFile } from 'node:fs/promises'
+import { execFile, spawn } from 'node:child_process'
+import { cp, lstat, mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { basename, dirname, isAbsolute, join, normalize } from 'node:path'
import { promisify } from 'node:util'
import { placeholderBranch, plausibleBranchName, worktreeFolderName } from './agentNames.js'
+import { redactSecretsInText } from './logBundle.js'
import { withinRoots } from './pathContainment.js'
const exec = promisify(execFile)
@@ -26,15 +27,19 @@ export function validGitPath(path: unknown): path is string {
/** [base]: the environment git starts from, the daemon's own unless a caller gives the one it must use instead
* (lib/swarmGitHub.ts `swarmGitPrepareEnv`). */
async function git(path: string, args: string[], timeout = 4000, base: NodeJS.ProcessEnv = process.env): Promise<string> {
- const env = { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }
- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]
- // core.fsmonitor names a program git runs on status/diff; a repository's own config must not choose
- // one for the daemon (same guard as projectPreview.ts).
- return (await exec('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', path, ...args], {
+ return (await exec('git', gitArgs(path, args), {
timeout, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,
- env,
+ env: gitEnv(base),
})).stdout.replace(/\r?\n$/, '')
}
+function gitEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ const env = { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]
+ return env
+}
+// core.fsmonitor names a program git runs on status/diff; a repository's own config must not choose
+// one for the daemon (same guard as projectPreview.ts).
+const gitArgs = (path: string, args: string[]) => ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', path, ...args]
/** `git worktree list --porcelain`, main checkout first. A bare repository has no files and a
* prunable entry lost its folder, so neither is somewhere to work. */
@@ -235,6 +240,8 @@ export type GitProjectOptions = {
/** `branchName` was made up (`brave-otter`): the session's name replaces it once there is one. */
placeholder?: boolean
pick?: (n: number) => number
+ /** How long `git worktree add` may run, in ms: `WORKTREE_ADD_TIMEOUT` unless a test gives a shorter one. */
+ worktreeTimeout?: number
}
/** Worktree on: a new worktree under `<root>/worktrees/<repository>`, on `branchName` — created from
@@ -366,18 +373,41 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
await git(source, ['config', '--add', key, remote.refspec])
}
}
- await git(source, existing
- ? ['worktree', 'add', '--', destination, branch]
- // A remote branch checked out under its own name tracks it; a new branch from one must not,
- // or it would push onto the base.
- : remote && remote.branch === branch
- ? ['worktree', 'add', '--track', '-b', branch, '--', destination, options.ref!]
- : ['worktree', 'add', '--no-track', '-b', branch, '--', destination, head], 120_000)
} catch (error) {
- // Keep any partial checkout and branch available for recovery.
if (diskFull(error)) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)
throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)
}
+ // A remote branch checked out under its own name tracks it; a new branch from one must not, or it would push onto the base.
+ const tracks = !existing && remote?.branch === branch
+ // The new branch is made here, before the worktree, by a ref update that refuses one existing by now: a branch a person made
+ // after the check above is never taken for this start's (review of #1837). A failed start deletes exactly the ref it made.
+ const made = existing ? null : { branch, head, tracks }
+ if (made) {
+ const created = await git(source, ['update-ref', '-m', `branch: Created from ${tracks ? options.ref : head}`, `refs/heads/${branch}`, head, ''])
+ .then(() => true, () => false)
+ if (!created) {
+ await rm(destination, { recursive: true, force: true })
+ throw new GitProjectError('BRANCH_EXISTS', `A branch named ${branch} already exists. Choose another name.`)
+ }
+ }
+ const admin = await worktreeAdmin(source)
+ const registered = new Set(await readdir(admin).catch(() => [] as string[]))
+ const upstream = tracks ? await git(source, ['branch', `--set-upstream-to=${options.ref}`, branch]).then(() => true, () => false) : true
+ const added: WorktreeAdd = upstream
+ ? await worktreeAdd(source, ['worktree', 'add', '--', destination, branch], options.worktreeTimeout ?? WORKTREE_ADD_TIMEOUT)
+ : { ok: false, reason: 'could not track its remote branch', stderr: '', timedOut: false, diskFull: false, running: false }
+ if (!added.ok && added.running) {
+ // Deleting the folder under a process still writing it would only race it; the next start takes another folder.
+ console.error(`[worktree] git worktree add failed (${added.reason}) at ${destination}; something git started is still running, so the folder and branch are left as it is: ${gitReason(added.stderr)}`)
+ throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)
+ }
+ if (!added.ok && !(added.timedOut && await finishedCheckout(source, destination, branch))) {
+ console.error(`[worktree] git worktree add failed (${added.reason}) at ${destination}: ${gitReason(added.stderr)}`)
+ // A retry starts clean. The folder is this start's own (reserved above), and so is the branch it made.
+ await removePartialWorktree(source, destination, made, admin, registered)
+ if (added.diskFull) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)
+ throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)
+ }
// Harness made this branch: its cleanup may remove it, and a made-up name gives way to the session's.
if (!existing) {
await git(source, ['config', `branch.${branch}.${HARNESS_BRANCH_KEY}`, placeholder ? 'placeholder' : 'created']).catch(() => '')
@@ -386,6 +416,115 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
return inside(destination)
}
+/** Ten minutes for `git worktree add`. 120 s failed 2 of 4 Swarm starts on a busy Mac Studio (2026-10-27): the
+ * checkout of the whole repository was still writing when the time ran out. */
+export const WORKTREE_ADD_TIMEOUT = 10 * 60_000
+
+/** `running`: something git started still held its stderr when this stopped waiting, so it may still be writing the folder. */
+type WorktreeAddFailure = { ok: false; reason: string; stderr: string; timedOut: boolean; diskFull: boolean; running: boolean }
+type WorktreeAdd = { ok: true } | WorktreeAddFailure
+
+/** `git worktree add`, in a process group of its own. git checks the files out in a child (`git reset --hard`)
+ * and runs hooks and filters below that: killing only git at the timeout left the child writing the folder after
+ * the start had given up, and the worktree registered as locked "initializing" with its branch (2026-10-27). At
+ * the timeout the whole group is killed (on Windows, git's process tree), and the result waits until no process
+ * holds git's stderr any more: until then something git started may still be writing the folder. If that takes
+ * as long again as the timeout (at most a minute), the result says it is `running`. */
+function worktreeAdd(source: string, args: string[], timeout: number): Promise<WorktreeAdd> {
+ return new Promise(resolve => {
+ let stderr = '', timedOut = false, settled = false, waited: NodeJS.Timeout | undefined
+ const done = (result: WorktreeAdd) => { if (!settled) { settled = true; clearTimeout(timer); clearTimeout(waited); resolve(result) } }
+ const failed = (reason: string, running = false): WorktreeAddFailure => ({ ok: false, reason, stderr, timedOut, diskFull: diskFull({ stderr }), running })
+ const late = () => `timed out after ${Math.round(timeout / 1000)} s`
+ const child = spawn('git', gitArgs(source, args), {
+ env: gitEnv(process.env), stdio: ['ignore', 'ignore', 'pipe'], detached: process.platform !== 'win32', windowsHide: true,
+ })
+ child.stderr.on('data', (chunk: Buffer) => { if (stderr.length < 64 * 1024) stderr += chunk.toString() })
+ const timer = setTimeout(() => {
+ timedOut = true
+ void stopTree(child.pid).then(problem => { if (problem) console.error(`[worktree] could not stop git and what it started: ${gitReason(problem)}`) })
+ waited = setTimeout(() => done(failed(late(), true)), Math.min(timeout, 60_000))
+ }, timeout)
+ child.once('error', error => done({ ...failed((error as NodeJS.ErrnoException).code ?? 'could not run git'), diskFull: diskFull(error) }))
+ child.once('close', (code, signal) => done(timedOut ? failed(late())
+ : code === 0 ? { ok: true } : failed(code === null ? `signal ${signal}` : `exit ${code}`)))
+ })
+}
+
+/** Kills [pid] and everything it started: its process group, or on Windows its tree. Null when that was done, else why
+ * not. On Windows `taskkill /T` finds only what still descends from a live git, so a failure here is reported and
+ * `worktreeAdd` still waits for git's stderr to close before anything is read or removed. */
+function stopTree(pid: number | undefined): Promise<string | null> {
+ if (pid === undefined) return Promise.resolve(null)
+ if (process.platform !== 'win32') {
+ try { process.kill(-pid, 'SIGKILL'); return Promise.resolve(null) } catch (error) {
+ return Promise.resolve((error as NodeJS.ErrnoException).code === 'ESRCH' ? null : String((error as Error).message))
+ }
+ }
+ return new Promise(resolve => {
+ let output = ''
+ const taskkill = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
+ taskkill.stdout.on('data', (chunk: Buffer) => { output += chunk.toString() })
+ taskkill.stderr.on('data', (chunk: Buffer) => { output += chunk.toString() })
+ taskkill.once('error', error => resolve(`taskkill: ${error.message}`))
+ taskkill.once('close', code => resolve(code === 0 ? null : `taskkill exit ${code}: ${output.trim() || 'no output'}`))
+ })
+}
+
+/** Whether git, stopped at the timeout, had already checked the worktree out: registered on its branch, every
+ * tracked file as the branch has it (the index is written after the files). Then it is used, unlocked. */
+async function finishedCheckout(source: string, destination: string, branch: string): Promise<boolean> {
+ const here = await real(destination)
+ let registered = false
+ for (const tree of await worktrees(source)) registered ||= tree.ref === `refs/heads/${branch}` && await real(tree.path) === here
+ if (!registered) return false
+ const changed = await git(destination, ['status', '--porcelain', '--untracked-files=no'], 120_000).catch(() => null)
+ if (changed !== '') return false
+ await git(source, ['worktree', 'unlock', '--', destination]).catch(() => '')
+ return true
+}
+
+/** `<common git dir>/worktrees`, where git registers each linked worktree in a folder of its own. */
+async function worktreeAdmin(source: string): Promise<string> {
+ const common = await git(source, ['rev-parse', '--git-common-dir']).catch(() => '')
+ return join(isAbsolute(common) ? common : join(source, common), 'worktrees')
+}
+
+/** Removes what a failed `worktree add` left: its registration (locked or not), the folder, and `branch` when this
+ * start made it. A registration in [registered] was there before and stays, whatever folder it names. `git branch
+ * -D` refuses a branch any other worktree has checked out. */
+async function removePartialWorktree(source: string, destination: string, made: { branch: string; head: string; tracks: boolean } | null,
+ admin: string, registered: Set<string>): Promise<void> {
+ const here = await real(destination)
+ try {
+ for (const entry of await readdir(admin).catch(() => [] as string[])) {
+ if (registered.has(entry)) continue
+ const gitdir = (await readFile(join(admin, entry, 'gitdir'), 'utf8').catch(() => '')).trim()
+ if (gitdir && await real(dirname(gitdir)) === here) await rm(join(admin, entry), { recursive: true, force: true })
+ }
+ await rm(destination, { recursive: true, force: true })
+ // Only while it is still where this start put it: a ref update with its old value is a compare-and-delete.
+ if (made && await git(source, ['update-ref', '-d', `refs/heads/${made.branch}`, made.head]).then(() => true, () => false) && made.tracks) {
+ for (const key of ['remote', 'merge']) await git(source, ['config', '--unset', `branch.${made.branch}.${key}`]).catch(() => '')
+ }
+ } catch (error) {
+ console.error(`[worktree] could not remove the partial worktree at ${destination}: ${error instanceof Error ? error.message : String(error)}`)
+ }
+}
+
+/** git's last words, short and without credentials: a remote URL's user and password, GitHub tokens (the stateless
+ * `ghs_APPID_` and a JWT before the older forms, which would stop at its first dot), JWTs, and the shared denylist. */
+function gitReason(stderr: string): string {
+ const lines = stderr.split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-3).join(' / ')
+ return redactSecretsInText((lines || 'no output')
+ // A bounded scheme: an unbounded one made a run of `ab-ab-…` quadratic (lib/agentHandoff.ts).
+ .replace(/([a-z][a-z0-9+.-]{0,31}:\/\/)[^\s/@]+@/gi, '$1<redacted>@')
+ .replace(/\bghs_\d+_[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,}){2}/g, '<redacted>')
+ .replace(/\b(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]+/g, '<redacted>')
+ .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, '<redacted>'))
+ .slice(0, 500)
+}
+
/** `.worktreeinclude` (gitignore syntax) in the repository names ignored files a new worktree needs
* and Git will not bring: `.env`, local config. Only files both listed and ignored are copied, never
* over one the checkout has. A copy that fails leaves the worktree as Git made it. */