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.

38.8 KB
Raw Blame
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, sep } 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'
import { ownProcessGroup } from './windows/noWindow.js'

const exec = promisify(execFile)

export class GitProjectError extends Error {
  constructor(readonly code: string, message: string) { super(message) }
}

const worktreeDiskFull = 'Not enough disk space to create the worktree. Free space on this machine, then retry.'
function diskFull(error: unknown): boolean {
  const failure = error as { code?: string; stderr?: string }
  return failure?.code === 'ENOSPC' || failure?.code === 'EDQUOT' ||
    /no space left on device|disk quota exceeded/i.test(failure?.stderr ?? '')
}

export function validGitPath(path: unknown): path is string {
  return typeof path === 'string' && isAbsolute(path) && path.length <= 4096 && !/[\x00-\x1f\x7f]/.test(path)
}

/** [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> {
  return (await exec('git', gitArgs(path, args), {
    timeout, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,
    env: gitEnv(base),
  })).stdout.replace(/\r?\n$/, '')
}
export 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. */
type Worktree = { path: string; ref: string | null; usable: boolean }
function parseWorktrees(output: string): Worktree[] {
  return output.split(/\n\s*\n/).flatMap(block => {
    const lines = block.split('\n')
    const path = lines.find(line => line.startsWith('worktree '))?.slice('worktree '.length)
    if (!path) return []
    return [{
      path,
      ref: lines.find(line => line.startsWith('branch '))?.slice('branch '.length) ?? null,
      usable: !lines.some(line => line === 'bare' || line.startsWith('prunable')),
    }]
  })
}
/** Whether `path` is a worktree Harness made in `root`'s worktrees folder: a linked worktree there whose branch carries
 *  Harness's `branch.<name>.harness` mark. A person's own checkout or worktree, anywhere, is not. */
export async function harnessMadeWorktree(path: string, root: string): Promise<boolean> {
  try {
    const [here, home] = await Promise.all([realpath(path), realpath(join(root, 'worktrees'))])
    if (dirname(here) === here || !here.startsWith(`${home}${sep}`) || !(await lstat(join(here, '.git'))).isFile()) return false
    const branch = (await git(here, ['branch', '--show-current'])).trim()
    return !!branch && (await git(here, ['config', '--get', `branch.${branch}.${HARNESS_BRANCH_KEY}`])).trim() !== ''
  } catch { return false }
}

/** `branch.<name>.harness` in the repository's config marks a branch Harness made: `placeholder` while
 *  its name waits for the session's, `created` once it has one or was named at Start. */
export const HARNESS_BRANCH_KEY = 'harness'
async function harnessBranches(path: string): Promise<Set<string>> {
  const out = await git(path, ['config', '--get-regexp', `^branch\\..*\\.${HARNESS_BRANCH_KEY}$`]).catch(() => '')
  return new Set(out.split('\n').flatMap(line => {
    const key = line.split(' ')[0] ?? ''
    return key.startsWith('branch.') && key.endsWith(`.${HARNESS_BRANCH_KEY}`) ? [key.slice(7, -(HARNESS_BRANCH_KEY.length + 1))] : []
  }))
}
const worktrees = (path: string) => git(path, ['worktree', 'list', '--porcelain']).then(parseWorktrees, () => [])
const real = (path: string) => realpath(path).catch(() => normalize(path))
const isDirectory = (path: string) => stat(path).then(info => info.isDirectory(), () => false)

/** Whether `path` or a folder above it holds `.git`: a directory, or the file a linked worktree has.
 *  Checked before any `git` runs in a folder that may not be a checkout: on a Mac without the Command
 *  Line Tools, `/usr/bin/git` is Apple's stub, and running it opens the "install the command line
 *  developer tools" dialog in front of whatever the person is doing (fresh macOS VM, 2026-10-08). */
export async function insideGitCheckout(path: string): Promise<boolean> {
  // From the real path, as git walks it: a link to a repository's subfolder (`~/web` →
  // `~/mono/packages/web`) is inside that checkout although nothing above the link is.
  const start = await realpath(path).catch(() => path)
  for (let dir = start; ; dir = dirname(dir)) {
    const found = await stat(join(dir, '.git')).then(() => true, (error: NodeJS.ErrnoException) =>
      // Only "nothing there" rules a checkout out; anything else (EACCES, EIO) is left to git.
      error.code !== 'ENOENT' && error.code !== 'ENOTDIR')
    if (found) return true
    if (dirname(dir) === dir) return false
  }
}

/** The main checkout, when `root` is one of its linked worktrees. */
async function mainCheckout(root: string, trees: Worktree[]): Promise<string | null> {
  if (trees.length < 2 || !trees[0]!.usable) return null
  const here = await real(root)
  if (await real(trees[0]!.path) === here) return null
  for (const tree of trees.slice(1)) if (await real(tree.path) === here) return trees[0]!.path
  return null
}

const branchRefreshes = new Map<string, Promise<Map<string, string[] | null>>>()

/** Share a refresh across pickers/worktrees. Ask for names only: downloading
 *  objects is deferred until Start, and no repository files or refs change. */
async function refreshBranches(path: string): Promise<Map<string, string[] | null>> {
  const common = await git(path, ['rev-parse', '--git-common-dir'])
  const key = await real(isAbsolute(common) ? common : join(path, common))
  const pending = branchRefreshes.get(key)
  if (pending) return pending
  const refresh = (async () => {
    const remotes = (await git(path, ['remote'])).split('\n').filter(Boolean)
    return new Map(await Promise.all(remotes.map(async remote => {
      const names = await git(path, ['ls-remote', '--heads', '--', remote], 8_000)
        .then(output => output.split('\n').flatMap(line => {
          const ref = line.split('\t')[1]
          return ref?.startsWith('refs/heads/') ? [ref.slice('refs/heads/'.length)] : []
        }), () => null)
      return [remote, names] as const
    })))
  })()
  branchRefreshes.set(key, refresh)
  try { return await refresh } finally { branchRefreshes.delete(key) }
}

/** Cached choices are immediate. A picker can separately request a bounded
 *  remote refresh, including branches excluded by a single-branch clone. */
/**
 * Reads a repository's shape for the New Harness form. `knownRoots` widens the browsable home with
 * the workspaces agents are already running in; leaving it out still fences to the home folder, so a
 * caller can never accidentally ask this to run git anywhere on the machine.
 *
 * `path` is resolved before anything runs: git would follow a symlink out of the allowed folders
 * whatever the name said, so the containment is measured on the real path and git is pointed at it.
 */
export async function readGitProject(requested: string, options: { refresh?: boolean; knownRoots?: string[] } = {}) {
  if (!validGitPath(requested)) return { error: 'INVALID_PATH' }
  let path: string
  // A folder that is gone reads as "not a Git project", which is what running git in it used to
  // report (exit 128) — a deleted folder is not a malformed request.
  try { path = await realpath(requested) } catch { return { isGit: false, branches: [] } }
  // Same word and same roots as projectPreview's fence, so the two read alike.
  if (!(await withinRoots(path, [homedir(), ...(options.knownRoots ?? [])]))) return { error: 'FORBIDDEN' }
  // A folder with no `.git` in it or above it is not a Git project, and saying so needs no git. On a
  // Mac without the Command Line Tools, `/usr/bin/git` is Apple's installer stub: it exits 1 (not
  // git's 128), so every new harness in an existing folder failed with "Could not check Git" on a
  // fresh Mac (macOS VM, 2026-10-08). GIT_DIR and friends are cleared for `git` below, so this is the
  // same discovery git itself would make.
  if (!(await insideGitCheckout(path))) return { isGit: false, branches: [] }
  let root: string
  try { root = await git(path, ['rev-parse', '--show-toplevel']) }
  catch (error) {
    const failure = error as { code?: number | string; killed?: boolean }
    return !failure.killed && failure.code === 128 ? { isGit: false, branches: [] } : { error: 'GIT_UNAVAILABLE' }
  }
  try {
    const discovered = options.refresh ? await refreshBranches(path).catch(() => null) : undefined
    const [branch, refs, trees, originHead, marked] = await Promise.all([
      git(path, ['symbolic-ref', '--quiet', 'HEAD']).then(ref => ref.replace(/^refs\/heads\//, '')).catch(() => null),
      git(path, ['for-each-ref', '--format=%(refname)%09%(refname:short)%09%(symref)', 'refs/heads', 'refs/remotes']),
      worktrees(path),
      git(path, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']).catch(() => null),
      harnessBranches(path),
    ])
    const checkedOut = new Map(trees.flatMap(tree => tree.usable && tree.ref ? [[tree.ref, tree.path] as const] : []))
    const branches = refs.split('\n').filter(Boolean).flatMap(line => {
      const [ref, name, symbolic] = line.split('\t')
      if (!ref || !name || symbolic) return []
      const worktree = checkedOut.get(ref)
      const harness = !ref.startsWith('refs/remotes/') && (marked.has(name) || name.startsWith('harness/'))
      return [{ ref, name, remote: ref.startsWith('refs/remotes/'), ...(worktree ? { worktree } : {}), ...(harness ? { harness } : {}) }]
    })
    for (const [remote, names] of discovered ?? []) {
      if (names === null) continue // Offline: retain this remote's saved choices.
      const prefix = `refs/remotes/${remote}/`
      for (let i = branches.length - 1; i >= 0; i--) {
        if (branches[i]!.ref.startsWith(prefix)) branches.splice(i, 1)
      }
      branches.push(...names.map(name => ({ ref: `${prefix}${name}`, name: `${remote}/${name}`, remote: true })))
    }
    // Where new work starts by default: the remote's default branch, as a clone names it, else its
    // main or master.
    const known = new Set(branches.map(row => row.ref))
    const defaultRef = [originHead, 'refs/remotes/origin/main', 'refs/remotes/origin/master'].find(ref => ref && known.has(ref))
    const found = { isGit: true, root, branch, branches, ...(defaultRef ? { defaultRef } : {}),
      ...(discovered === undefined ? {} : { refreshed: discovered !== null && [...discovered.values()].every(names => names !== null) }) }
    // A worktree is a temporary folder. The launcher shows its repository.
    const main = await mainCheckout(root, trees)
    if (!main) return found
    const prefix = (await git(path, ['rev-parse', '--show-prefix']).catch(() => '')).replace(/\/$/, '')
    const mainFolder = prefix && await isDirectory(join(main, prefix)) ? join(main, prefix) : main
    const mainBranch = trees[0]!.ref?.replace(/^refs\/heads\//, '')
    return { ...found, mainFolder, ...(mainBranch ? { mainBranch } : {}) }
  } catch { return { error: 'GIT_UNAVAILABLE' } }
}

/** `refs/remotes/origin/fix/typo` → origin, fix/typo, and a refspec updating exactly that ref. */
export function remoteBranch(ref: string | undefined): { remote: string; branch: string; refspec: string } | null {
  const match = /^refs\/remotes\/([A-Za-z0-9._][A-Za-z0-9._-]*)\/([A-Za-z0-9._]\S*)$/.exec(ref ?? '')
  if (!match || match[2] === 'HEAD') return null
  return { remote: match[1]!, branch: match[2]!, refspec: `+refs/heads/${match[2]}:refs/remotes/${match[1]}/${match[2]}` }
}

/** The remote's default branch as the ref a clone keeps it in: `origin/HEAD`, else `origin/main` or
 *  `origin/master`, as `readGitProject` offers it. Null when the repository has no such ref. */
export async function originDefaultRef(path: string): Promise<string | null> {
  const head = await git(path, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']).catch(() => null)
  for (const ref of [head, 'refs/remotes/origin/main', 'refs/remotes/origin/master']) {
    if (ref && await git(path, ['show-ref', '--verify', '--quiet', '--', ref]).then(() => true, () => false)) return ref
  }
  return null
}

/**
 * Brings the branch a start names ([branchRef], `refs/remotes/origin/X`), or the remote's default branch when it names none
 * or a local one, up to date in [source], with [env]'s git setup instead of the daemon's: a Swarm host's fetch with the
 * Harness GitHub App's token (lib/swarmGitHub.ts `swarmGitPrepareEnv`), before the worktree starts from it. Offline, slow or
 * refused, the worktree starts from what is here; a repository with no `origin` default branch has nothing to fetch. A
 * project clone is single-branch (projectFolder.ts), so X is fetched here or not at all: the start that follows is offline. In a blob-less clone the files of that branch's tip come too, with the same [env], so the
 * offline worktree needs nothing fetched lazily (it may not: `prepareGitProject` `offline`). False when nothing was fetched;
 * files that could not come leave the branch fetched and the start to fail offline, never to use another login.
 */
export async function fetchStartBase(source: string, env: NodeJS.ProcessEnv, branchRef?: string): Promise<boolean> {
  if (!validGitPath(source) || !(await insideGitCheckout(source))) return false
  const remote = remoteBranch(branchRef) ?? remoteBranch(await originDefaultRef(source) ?? undefined)
  if (!remote) return false
  const fetched = await git(source, ['fetch', '--quiet', '--no-tags', remote.remote, remote.refspec], 60_000, env).then(() => true, () => false)
  if (fetched) await fetchMissingFiles(source, remote.remote, `refs/remotes/${remote.remote}/${remote.branch}`, env)
  return fetched
}

/** In a partial clone, fetches what [ref]'s tree lacks from [remote] in one request, as git's own lazy fetch would ask for it
 *  (promisor-remote.c), but with [env]. Listing what is missing fetches nothing. A clone that is not partial lacks nothing.
 *  A failure is logged: the offline worktree that follows then fails on the files it lacks. */
async function fetchMissingFiles(source: string, remote: string, ref: string, env: NodeJS.ProcessEnv): Promise<void> {
  if (await git(source, ['config', '--get', `remote.${remote}.promisor`]).catch(() => '') !== 'true') return
  const failed = (stderr: string) => console.warn(`[worktree] could not fetch the files of ${ref} for an offline start: ${gitReason(stderr)}`)
  const listing = await exec('git', gitArgs(source, ['rev-list', '--objects', '--missing=print', '--no-object-names', '--end-of-options', `${ref}^{tree}`]), {
    timeout: 120_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024, env: { ...gitEnv(env), GIT_NO_LAZY_FETCH: '1' },
  }).then(out => out.stdout, (error: { stderr?: string; message?: string }) => { failed(error.stderr || error.message || ''); return '' })
  const missing = listing.split('\n').filter(line => /^\?[0-9a-f]{40,64}$/.test(line)).map(line => line.slice(1))
  if (missing.length === 0) return
  await new Promise<void>(resolve => {
    const child = execFile('git', gitArgs(source, ['-c', 'fetch.negotiationAlgorithm=noop', 'fetch', '--quiet', '--no-tags', '--no-write-fetch-head',
      '--recurse-submodules=no', '--filter=blob:none', '--stdin', remote]), { timeout: 600_000, killSignal: 'SIGKILL', env: gitEnv(env) },
      (error, _stdout, stderr) => { if (error) failed(stderr || error.message); resolve() })
    // A git that exits before reading the whole list closes its input; that is its failure above, not another.
    child.stdin?.on('error', () => {})
    child.stdin?.end(missing.join('\n') + '\n')
  })
}

export type GitProjectOptions = {
  root: string
  worktree: boolean
  /** Worktree on: what a new branch starts from. Worktree off: the branch the folder is on. */
  ref?: string
  /** Worktree on, a new branch, no `ref`: start from the remote's default branch, fetched first, rather than
   *  from wherever `HEAD` is. A checkout nobody works in (a Swarm host's clone) stays where it was cloned, days
   *  behind. Only a Swarm start asks for it; a repository with no `origin` default branch starts from `HEAD`. */
  fromDefaultBranch?: boolean
  /** Fetch nothing: start from what the checkout already has. A Swarm start doing another person's work: its host
   *  fetched with the Harness GitHub App's token just before (`fetchStartBase`), and this machine's own git
   *  login must not be used for it. */
  offline?: boolean
  /** The worktree's branch: created from `ref`, or with `existingBranch` checked out as it is. */
  branchName?: string
  existingBranch?: boolean
  /** `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
 * `ref`, or with `existingBranch` an existing local branch checked out as it is. Without a name one
 * is made up (`harness/brave-otter`). A remote base is fetched first, briefly: so is the default branch
 * with `fromDefaultBranch`, when there is no `ref`.
 *
 * Worktree off: the folder on the local `ref`. A branch that already has a worktree opens there; any
 * other is switched to, only in a folder with nothing uncommitted. With `branchName` the folder moves
 * to that new branch, made where it is now, uncommitted changes and all. */
export async function prepareGitProject(source: string, options: GitProjectOptions): Promise<string> {
  if (!validGitPath(source) || (options.branchName !== undefined && !plausibleBranchName(options.branchName))
      || (options.existingBranch && !options.branchName)) {
    throw new GitProjectError('INVALID_PROJECT_SOURCE', 'Choose a Git project folder.')
  }
  const existing = options.existingBranch === true
  // A new branch for the folder itself: `ref` names it and does not exist.
  const creating = !options.worktree && !!options.branchName && !existing
  let root: string, head: string, prefix: string
  try {
    root = await git(source, ['rev-parse', '--show-toplevel'])
    // The default branch is only ever a remote one, so it is fetched like any other remote base below.
    const ref = options.ref ?? (options.fromDefaultBranch && options.worktree && !existing && !creating
      ? await originDefaultRef(source) ?? undefined : undefined)
    if (ref && !creating) {
      if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(ref)) throw new Error('Invalid branch')
      // A freshly discovered remote branch may not have been fetched yet.
      if (!(options.worktree && !existing && remoteBranch(ref))) {
        await git(source, ['show-ref', '--verify', '--hash', '--', ref])
      }
    }
    // New work starts from where its branch is now, not from the last fetch: a remote branch is
    // fetched; a local one is fetched against its upstream and the newer of the two taken, so nothing
    // only the local one has is lost. Offline, slow or refused, it starts from what is here.
    let start = existing ? `refs/heads/${options.branchName}` : creating ? 'HEAD' : ref ?? 'HEAD'
    const remote = options.worktree && !existing ? remoteBranch(ref) : null
    const upstream = options.worktree && !existing && !remote && ref
      ? await git(source, ['for-each-ref', '--format=%(upstream)', ref]).then(found => remoteBranch(found) ? found : null, () => null)
      : null
    const fetch = options.offline ? null : remote ?? remoteBranch(upstream ?? undefined)
    if (fetch) await git(source, ['fetch', '--quiet', '--no-tags', fetch.remote, fetch.refspec], 10_000).catch(() => '')
    // Behind or level with its upstream: the upstream is the newer.
    if (upstream && ref && await git(source, ['merge-base', '--is-ancestor', ref, upstream]).then(() => true, () => false)) {
      start = upstream
    }
    head = await git(source, ['rev-parse', '--verify', '--end-of-options', `${start}^{commit}`])
    prefix = await git(source, ['rev-parse', '--show-prefix'])
    if (prefix && await git(source, ['cat-file', '-t', `${head}:${prefix.replace(/\/$/, '')}`]) !== 'tree') throw new Error('Missing folder')
  } catch {
    throw new GitProjectError('GIT_PROJECT_UNAVAILABLE', 'Choose a Git project and branch with at least one commit. For a new folder, turn Worktree off.')
  }
  const inside = (folder: string) => prefix ? join(folder, prefix.replace(/\/$/, '')) : folder
  const trees = await worktrees(source)
  if (creating) {
    const name = options.branchName!
    if (await git(source, ['show-ref', '--verify', '--quiet', '--', `refs/heads/${name}`]).then(() => true, () => false)) {
      throw new GitProjectError('BRANCH_EXISTS', `A branch named ${name} already exists. Choose it instead.`)
    }
    try { await git(source, ['check-ref-format', '--branch', name]) }
    catch { throw new GitProjectError('INVALID_BRANCH', `${name} is not a valid branch name.`) }
    try { await git(source, ['switch', '-c', name]) }
    catch { throw new GitProjectError('BRANCH_SWITCH_FAILED', `Could not create ${name} here.`) }
    return source
  }
  if (!options.worktree) {
    if (!options.ref?.startsWith('refs/heads/')) throw new GitProjectError('INVALID_BRANCH', 'Choose a local branch, or turn Worktree on.')
    const current = await git(source, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => null)
    if (current === options.ref) return source
    // A branch that already has a worktree is worked on there: Git would refuse to check it out
    // twice, and the folder is not the person's concern.
    for (const tree of trees) {
      if (tree.usable && tree.ref === options.ref && await isDirectory(tree.path)) return inside(tree.path)
    }
    const status = await git(source, ['status', '--porcelain']).catch(() => null)
    if (status !== '') {
      throw new GitProjectError('BRANCH_SWITCH_FAILED', 'This folder has uncommitted changes. Commit or stash them before switching branches, or turn Worktree on.')
    }
    try {
      await git(source, ['switch', '--', options.ref.slice('refs/heads/'.length)], 120_000)
      return source
    } catch {
      throw new GitProjectError('BRANCH_SWITCH_FAILED', 'Could not switch branches. Commit or stash conflicting changes, or turn Worktree on.')
    }
  }
  // Grouped by repository, so the leaf only needs the branch.
  const repository = trees[0]?.usable ? basename(trees[0].path) : basename(root)
  const taken = new Set((await git(source, ['for-each-ref', '--format=%(refname)', 'refs/heads']).catch(() => '')).split('\n'))
  const placeholder = !options.branchName || options.placeholder === true
  let branch = options.branchName ?? placeholderBranch(taken, options.pick)
  // A name made up before the start (Desktop keeps its pick) may be taken by then; nobody chose it, so the next
  // free number is taken instead of refusing with BRANCH_EXISTS.
  if (placeholder && !existing) for (let suffix = 2, base = branch; taken.has(`refs/heads/${branch}`); suffix++) branch = `${base}-${suffix}`
  if (existing) {
    if (!taken.has(`refs/heads/${branch}`)) throw new GitProjectError('GIT_PROJECT_UNAVAILABLE', 'That branch is no longer available. Choose another branch.')
    if (trees.some(tree => tree.ref === `refs/heads/${branch}`)) {
      throw new GitProjectError('BRANCH_IN_USE', `${branch} is checked out in another worktree. Turn Worktree off to open it there.`)
    }
  } else {
    if (taken.has(`refs/heads/${branch}`)) throw new GitProjectError('BRANCH_EXISTS', `A branch named ${branch} already exists. Choose another name.`)
    try { await git(source, ['check-ref-format', '--branch', branch]) }
    catch { throw new GitProjectError('INVALID_BRANCH', `${branch} is not a valid branch name.`) }
  }
  let destination: string | undefined
  try {
    const home = join(options.root, 'worktrees')
    const parent = join(home, repository)
    await mkdir(parent, { recursive: true })
    // Spotlight would index every checkout again.
    if (process.platform === 'darwin') await writeFile(join(home, '.metadata_never_index'), '').catch(() => {})
    const leaf = worktreeFolderName(branch)
    // mkdir reserves the name atomically, so simultaneous starts never share a worktree.
    for (let attempt = 1; attempt <= 100 && !destination; attempt++) {
      const folder = join(parent, attempt === 1 ? leaf : `${leaf}-${attempt}`)
      try { await mkdir(folder); destination = folder }
      catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
    }
  } catch (error) {
    if (diskFull(error)) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)
    destination = undefined
  }
  if (!destination) throw new GitProjectError('WORKTREE_FAILED', 'Could not create a worktree folder. Check folder permissions, then retry.')
  const remote = remoteBranch(options.ref)
  try {
    if (!existing && remote?.branch === branch) {
      // A single-branch clone has no tracking rule for this newly discovered
      // branch. Add only the chosen branch when the person starts it.
      const key = `remote.${remote.remote}.fetch`
      const mappings = (await git(source, ['config', '--get-all', key]).catch(() => ''))
        .split('\n').map(ref => ref.replace(/^\+/, ''))
      if (!mappings.includes(remote.refspec.slice(1)) &&
          !mappings.includes(`refs/heads/*:refs/remotes/${remote.remote}/*`)) {
        await git(source, ['config', '--add', key, remote.refspec])
      }
    }
  } catch (error) {
    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
    // Offline means nothing fetched, a partial clone's missing files included: they would come with this machine's login.
    // GIT_NO_LAZY_FETCH is read from git 2.44 on; a protocol list naming no transport stops every git (review 1 of #2770).
    ? await worktreeAdd(source, ['worktree', 'add', '--', destination, branch], options.worktreeTimeout ?? WORKTREE_ADD_TIMEOUT,
      options.offline ? { GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: 'none' } : {})
    : { 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)
    // Offline in a blob-less clone: files `fetchStartBase` could not bring, which this start may not fetch itself.
    if (options.offline && /promisor remote|lazy fetching disabled/i.test(added.stderr)) {
      throw new GitProjectError('WORKTREE_FAILED', "This branch's files could not be fetched for the start. Check the connection, then retry.")
    }
    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(() => '')
  }
  await copyIncluded(root, destination)
  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, extraEnv: NodeJS.ProcessEnv = {}): 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), ...extraEnv }, stdio: ['ignore', 'ignore', 'pipe'], ...ownProcessGroup(),
    })
    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. */
export 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. */
async function copyIncluded(from: string, to: string): Promise<void> {
  const include = join(from, '.worktreeinclude')
  try {
    if (!(await stat(include)).isFile()) return
  } catch { return }
  const list = (exclude: string) => git(from, ['ls-files', '-z', '--others', '--ignored', '--directory', exclude])
    .then(out => out.split('\0').filter(Boolean), () => [] as string[])
  const [listed, ignored] = await Promise.all([list(`--exclude-from=${include}`), list('--exclude-standard')])
  const isIgnored = (entry: string) => ignored.some(path => path === entry || (path.endsWith('/') && entry.startsWith(path)))
  for (const entry of listed.filter(isIgnored).slice(0, 200)) {
    const relative = entry.replace(/\/$/, '')
    if (relative.split('/').includes('..')) continue
    const target = join(to, relative)
    try { await lstat(target); continue } catch { /* free */ }
    try {
      await mkdir(dirname(target), { recursive: true })
      await cp(join(from, relative), target, { recursive: true, errorOnExist: false, force: false, verbatimSymlinks: true, preserveTimestamps: true })
    } catch { /* the worktree stays as Git made it */ }
  }
}