# How Archon's Worktree Isolation Provider Creates and Manages Git Worktrees

> Learn how Archon's worktree isolation provider deterministically names branches, creates git worktrees for workflow execution, and manages their lifecycle via the WorktreeProvider class in its TypeScript package.

- Repository: [Cole Medin/Archon](https://github.com/coleam00/Archon)
- Tags: how-to-guide
- Published: 2026-04-10

---

**Archon's worktree isolation provider generates deterministic branch names, creates dedicated git worktrees for each workflow execution, and manages lifecycle operations through the `WorktreeProvider` class in [`packages/isolation/src/providers/worktree.ts`](https://github.com/coleam00/Archon/blob/main/packages/isolation/src/providers/worktree.ts).**

Archon isolates every workflow execution—from issue fixes to PR reviews—in its own Git worktree to ensure clean, reproducible environments. The `WorktreeProvider` class implements the `IIsolationProvider` interface and orchestrates branch naming, worktree path resolution, synchronization, and cleanup across the coleam00/Archon codebase.

## Generating Deterministic Branch Names

The isolation process begins with `generateBranchName()` (lines 26‑44 in [`packages/isolation/src/providers/worktree.ts`](https://github.com/coleam00/Archon/blob/main/packages/isolation/src/providers/worktree.ts)), which constructs semantic branch names based on the `IsolationRequest.workflowType`. This produces identifiers like `archon/issue-42` for issue workflows or `archon/pr-123-review` for PR reviews, ensuring repeatable environments that correlate directly with platform threads.

## Resolving Worktree Paths

Once the branch name is established, `getWorktreePath()` (lines 66‑75) computes the filesystem location using Archon’s worktree-base layout. The provider supports two directory schemes:

- **Project-scoped**: `~/.archon/workspaces/{codebase}/worktrees/{branch}`
- **Legacy global**: `~/.archon/worktrees/{codebase}/{branch}`

The path resolution logic in [`packages/paths/src/archon-paths.ts`](https://github.com/coleam00/Archon/blob/main/packages/paths/src/archon-paths.ts) determines which base directory to use based on the repository configuration and `canonicalRepoPath`.

## Adoption vs. Creation Logic

Before creating new resources, `findExisting()` (lines 80‑106) checks for existing worktrees to prevent duplicates. For standard workflows, it verifies the expected path via `worktreeExists`. For PR requests, it also searches by the PR’s branch name using `findWorktreeByBranch`. When a match is found, `buildAdoptedEnvironment()` returns an `IsolatedEnvironment` marked with the `adopted` flag, bypassing creation entirely and saving disk space.

## Repository Synchronization

To eliminate drift, `syncWorkspaceBeforeCreate()` (lines 101‑124) runs `syncWorkspace()` to fetch the latest changes and optionally perform a hard-reset to the base branch. This guarantees the canonical repository is up-to-date before any new worktree is instantiated, preventing stale base states in isolated environments.

## Creating Worktrees for Issues and Tasks

For non-PR workflows, `createNewBranch()` (lines 73‑119 in the implementation details) generates a fresh branch from the base branch (or an explicit `fromBranch` for tasks) and adds the worktree. If the branch already exists, the provider either adopts it or throws a descriptive error for conflicting start points, ensuring deterministic states.

## Handling Pull Request Worktrees

The `createWorktree()` method (lines 130‑166) dispatches to PR-specific helpers when `workflowType` indicates a pull request:

- **Same-repo PRs**: `createFromSameRepoPR()` (lines 62‑80) fetches the existing branch and adds a worktree tracking it.
- **Fork PRs**: `createFromForkPR()` (lines 84‑104) fetches the pull request’s head and creates a synthetic `pr-N-review` branch. If stale branches conflict with the fetch, `createBranchWithStaleRetry()` automatically retries with cleanup.

Both approaches handle the `isForkPR` flag from the `IsolationRequest` to determine remote fetching logic.

## Copying Git-Ignored Configuration Files

After worktree creation, `copyConfiguredFiles()` (lines 56‑84 in [`packages/isolation/src/worktree-copy.ts`](https://github.com/coleam00/Archon/blob/main/packages/isolation/src/worktree-copy.ts)) copies critical git-ignored files into the new directory. By default, this includes the `.archon` directory; additional files specified in [`.archon/config.yaml`](https://github.com/coleam00/Archon/blob/main/.archon/config.yaml) under `copyFiles` are also transferred. Warnings are aggregated if the configuration fails to load, ensuring the workflow proceeds even with partial config errors.

## Cleanup and Health Monitoring

### Destroy Operations

The `destroy()` method (lines 8‑98) handles teardown through best-effort steps that collect warnings rather than masking original failures:

1. Removes the git worktree registration using `git worktree remove`
2. Cleans leftover directories manually if the git command leaves debris
3. Optionally deletes the local branch
4. Optionally deletes the remote branch on `origin`

All operations use `force` flags when specified to handle uncommitted changes.

### Orphan Handling

Before creation, `cleanOrphanDirectoryIfExists()` (lines 46‑68) removes stray directories that exist on disk but are not registered as worktrees. If a partial creation leaves a registered but corrupted worktree, `cleanOrphanWorktreeIfExists()` (lines 71‑88) deregisters it to prevent conflicts with subsequent runs.

### Health Checks

The `healthCheck()` method (lines 13‑15) proxies to `worktreeExists()` to verify the worktree directory remains present and accessible, typically called before operations to detect external deletions.

## Practical Implementation Examples

### Creating an Isolated Environment for an Issue

```typescript
import { WorktreeProvider } from '@archon/isolation';
import type { IsolationRequest } from '@archon/isolation/types';

const provider = new WorktreeProvider();

const request: IsolationRequest = {
  workflowType: 'issue',
  identifier: '42',
  canonicalRepoPath: '/home/user/.archon/workspaces/acme/widget',
  codebaseName: 'widget',
};

const env = await provider.create(request);
console.log('Worktree created at:', env.workingPath);
// Output: ~/.archon/workspaces/acme/widget/worktrees/archon/issue-42

```

This creates the branch `archon/issue-42`, adds the worktree, and copies `.archon` configuration files.

### Adopting an Existing PR Worktree

```typescript
const prRequest: IsolationRequest = {
  workflowType: 'pr',
  identifier: '123',
  isForkPR: false,
  prBranch: 'feature/login',
  canonicalRepoPath: '/home/user/.archon/workspaces/acme/widget',
  codebaseName: 'widget',
};

const env = await provider.create(prRequest);
console.log('Adopted existing:', env.adopted);

```

If `feature/login` already has a worktree, the provider returns the existing path with `adopted: true`.

### Cleaning Up After Workflow Completion

```typescript
const result = await provider.destroy(env.id, {
  branchName: env.branchName,
  canonicalRepoPath: '/home/user/.archon/workspaces/acme/widget',
  deleteRemoteBranch: true,
  force: true,
});

console.log('Cleanup warnings:', result.warnings);

```

This removes the worktree, prunes the branch locally, and deletes the remote branch on `origin`.

## Summary

Archon’s worktree isolation provider delivers a **deterministic, self-healing sandbox** for workflow execution:

- **Deterministic naming** correlates branches directly with issue numbers and PR identifiers
- **Smart adoption** prevents duplicate worktrees for the same branch, conserving disk space
- **Pre-creation sync** guarantees fresh base branches before any isolation occurs
- **Robust cleanup** includes orphan detection, stale branch retry logic, and best-effort destruction that preserves error context

All functionality is encapsulated in [`packages/isolation/src/providers/worktree.ts`](https://github.com/coleam00/Archon/blob/main/packages/isolation/src/providers/worktree.ts) with low-level git operations delegated to [`packages/git/src/worktree.ts`](https://github.com/coleam00/Archon/blob/main/packages/git/src/worktree.ts).

## Frequently Asked Questions

### How does Archon prevent duplicate worktrees for the same PR?

The `findExisting()` method checks both the expected filesystem path and, for PR workflows, searches by branch name using `findWorktreeByBranch`. When a match is detected, the provider returns an `IsolatedEnvironment` with `adopted: true` instead of creating a new worktree, ensuring only one worktree exists per branch.

### What happens if a worktree creation fails halfway through?

The provider implements `cleanOrphanDirectoryIfExists()` to remove stray directories and `cleanOrphanWorktreeIfExists()` to deregister partial git worktree entries before attempting creation. During destruction, `destroy()` operates as best-effort, collecting warnings for each failed cleanup step without throwing exceptions that would mask the original error.

### Where does Archon store worktrees by default?

By default, Archon uses a **project-scoped** layout under `~/.archon/workspaces/{codebase}/worktrees/` as resolved by [`packages/paths/src/archon-paths.ts`](https://github.com/coleam00/Archon/blob/main/packages/paths/src/archon-paths.ts). Legacy configurations may use the global `~/.archon/worktrees/{codebase}/` structure. The `getWorktreePath()` method handles both layouts transparently.

### Can Archon worktrees access configuration files ignored by git?

Yes. The `copyConfiguredFiles()` function (implemented in [`packages/isolation/src/worktree-copy.ts`](https://github.com/coleam00/Archon/blob/main/packages/isolation/src/worktree-copy.ts)) copies the `.archon` directory and any files specified in [`.archon/config.yaml`](https://github.com/coleam00/Archon/blob/main/.archon/config.yaml) into the new worktree after creation. This ensures environment variables and local settings are available in the isolated environment without polluting the git index.