worktrees

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package worktrees lists the git worktrees of the user's local clones and removes them safely.

It covers every git repository directly under the clone root (the same scan clone resolution uses), so worktrees left by sessions started elsewhere show up too. Removal is deliberately narrow:

  • Remove runs `git worktree remove` without --force, so git itself refuses a worktree with uncommitted changes or a lock;
  • ForceRemove passes a single --force and only for an unlocked worktree with uncommitted changes, so a locked worktree (usually a live agent session) is never removed;
  • Unlock releases only a lock the coding agent wrote for a session that has certainly ended, never a lock set by hand or one whose session may still run;
  • the main worktree is never removed.

A worktree the agent made for a pull request or issue (pr-<n> or issue-<n> under the clone's .claude/worktrees) is linked to that item, and GitHub says whether it is done. GitHub decides when a worktree is finished; git alone decides whether removing it is safe. CleanUp, CleanUpFinished, and the automatic Sweep remove a worktree only when its item is merged or closed, it has no uncommitted changes, every commit it has is on GitHub, and no session runs in it. Then they also delete the agent's own worktree-<name> branch, and only while it still points at the commit checked. No other branch is ever deleted, and nothing on GitHub is touched.

Every git command runs as an argv `git -C <dir> ...` from a short allowlist, never through a shell.

Index

Constants

View Source
const (
	// StageInUse is a worktree a running agent session holds.
	StageInUse = "in-use"

	// StageActive is a worktree whose pull request or issue is still open.
	StageActive = "active"

	// StageFinished is a worktree whose item is done and that CleanUp removes without
	// losing anything.
	StageFinished = "finished"

	// StageNeedsReview is a worktree whose item is done but that holds uncommitted
	// changes or commits that are not on GitHub, or whose state could not be read.
	StageNeedsReview = "needs-review"
)

Stages of a worktree's pull request or issue, as Worktree.Stage reports them.

View Source
const (
	ItemOpen   = "open"
	ItemMerged = "merged"
	ItemClosed = "closed"
)

Item states, as LinkedItem.State reports them.

View Source
const DefaultSweepInterval = 5 * time.Minute

DefaultSweepInterval is how often a Sweeper sweeps. A sweep runs git only in clones that have agent worktrees, and asks GitHub once, for one point, only when there are any.

Variables

View Source
var (
	// ErrMainWorktree is returned for the main worktree, which is never removed.
	ErrMainWorktree = errors.New("the main worktree cannot be removed")

	// ErrLocked is returned for a locked worktree, which is never removed: a running
	// session usually holds the lock.
	ErrLocked = errors.New("the worktree is locked, usually by a running session; unlock it with git worktree unlock first")

	// ErrNotLocked is returned when unlocking a worktree that has no lock.
	ErrNotLocked = errors.New("the worktree is not locked")

	// ErrHandLock is returned for a lock that no agent session wrote; only the user who
	// set it should release it.
	ErrHandLock = errors.New("the worktree was locked by hand, not by an agent session; unlock it yourself with git worktree unlock")

	// ErrSessionRunning is returned for an agent lock whose session may still be running.
	ErrSessionRunning = errors.New("the agent session that locked the worktree may still be running")

	// ErrChanged is returned when a worktree's commit or lock changed since it was checked.
	ErrChanged = errors.New("the worktree changed since it was checked; refresh and try again")

	// ErrNotFinished is returned by CleanUp for a worktree that is not finished.
	ErrNotFinished = errors.New("the worktree is not finished")

	// ErrCleanUpFailed is returned by CleanUp when a step of the removal was refused.
	ErrCleanUpFailed = errors.New("the worktree could not be cleaned up")

	// ErrBranchInUse is returned when a branch to delete is checked out in a worktree.
	ErrBranchInUse = errors.New("the branch is checked out in a worktree")

	// ErrGitHubUnavailable is returned when GitHub could not say which worktrees are
	// finished.
	ErrGitHubUnavailable = errors.New("GitHub could not be asked which worktrees are finished")

	// ErrNotAWorktree is returned for a path that is not a linked worktree of the
	// repository.
	ErrNotAWorktree = errors.New("not a linked worktree of this repository")

	// ErrNotDirty is returned when force removal is asked for a worktree without
	// uncommitted changes.
	ErrNotDirty = errors.New("the worktree has no uncommitted changes; use Remove instead")

	// ErrPrunable is returned when force removal is asked for a worktree whose directory
	// is gone.
	ErrPrunable = errors.New("the worktree's directory is gone; prune the repository instead")

	// ErrOutsideCloneRoot is returned for a repository that is not directly under the
	// clone root.
	ErrOutsideCloneRoot = errors.New("not a repository under the clone root")

	// ErrRemovalRefused is matched by every RefusedError.
	ErrRemovalRefused = errors.New("git refused to remove the worktree")
)
View Source
var ErrGitCommandNotAllowed = errors.New("git command not allowed")

ErrGitCommandNotAllowed is returned for a git command outside the allowlist; it is never run.

View Source
var ErrMalformedPorcelain = errors.New("malformed git worktree list output")

ErrMalformedPorcelain is returned when `git worktree list --porcelain -z` output does not have the documented shape.

Functions

func ParseClaudeLock

func ParseClaudeLock(reason string) (pid int, ok bool)

ParseClaudeLock returns the PID recorded in a lock reason written by the coding agent. ok is false for any other reason, including an empty one.

Types

type Cleanup

type Cleanup struct {
	// ID identifies the record.
	ID int64 `json:"id"`

	// CleanedAt is when the worktree was removed, in RFC 3339.
	CleanedAt string `json:"cleanedAt"`

	// Automatic reports a cleanup by the sweep rather than by the user.
	Automatic bool `json:"automatic"`

	// Repo is the clone's directory name.
	Repo string `json:"repo"`

	// Worktree is the worktree's directory name, e.g. "pr-184".
	Worktree string `json:"worktree"`

	// DisplayPath was the worktree's path relative to home with ~.
	DisplayPath string `json:"displayPath"`

	// DeletedBranch is the branch deleted with it, or "" when it was kept.
	DeletedBranch string `json:"deletedBranch"`

	// Head is the commit it had checked out, which is on GitHub.
	Head string `json:"head"`

	// Item is the pull request or issue it was for, or nil.
	Item *LinkedItem `json:"item"`
}

Cleanup is one worktree the app cleaned up, as the Worktrees view's history shows it.

type Clock

type Clock interface {
	Now() time.Time
}

Clock tells the time.

type Config

type Config struct {
	// Settings supplies the clone root.
	Settings SettingsReader

	// Git runs git argv; it also reads remotes during the clone-root scan.
	Git Runner

	// Finder resolves the git binary up front, so a missing git fails with a clear
	// error. Without it, Git resolves "git" itself.
	Finder Finder

	// Home is the user's home directory; it expands a ~ clone root and shortens paths.
	Home string

	// Clock stamps snapshots. It defaults to the system clock.
	Clock Clock

	// GitHub reads the state of the items worktrees are linked to. Without it no
	// worktree is linked, so none is ever finished.
	GitHub GitHub

	// Launches holds the worktrees the app launched sessions in.
	Launches Launches

	// History records each cleanup, for the view's list of recent ones.
	History History

	// Notifier is told when a sweep changed something.
	Notifier Notifier

	// Logger receives sweep failures. It defaults to slog.Default().
	Logger *slog.Logger
}

Config holds a Service's dependencies. Settings and Git are required; the rest are optional.

type Entry

type Entry struct {
	// Path is the worktree's directory as git reports it.
	Path string

	// HEAD is the commit the worktree has checked out; empty for a bare repository.
	HEAD string

	// Branch is the checked-out branch without its refs/heads/ prefix; empty when the
	// worktree is detached or bare.
	Branch string

	// Detached reports a detached HEAD.
	Detached bool

	// Bare reports the bare repository itself rather than a working tree.
	Bare bool

	// Locked reports a worktree protected by `git worktree lock`.
	Locked bool

	// LockReason is the reason given to `git worktree lock`, if any.
	LockReason string

	// Prunable reports a worktree git can prune, usually because its directory is gone.
	Prunable bool

	// PrunableReason is git's explanation for Prunable.
	PrunableReason string

	// Main reports the main worktree (or bare repository), which git always lists first.
	Main bool
}

Entry is one worktree as `git worktree list --porcelain -z` describes it.

func ParsePorcelain

func ParsePorcelain(data []byte) ([]Entry, error)

ParsePorcelain parses `git worktree list --porcelain -z` output. Every attribute ends with a NUL and an empty attribute ends an entry. Attributes it does not know are ignored, so newer git versions keep working. The first entry is the main worktree.

type Finder

type Finder interface {
	Find(name string) (string, error)
}

Finder resolves a program name to an executable's absolute path. execpath.Finder implements it.

type GitHub

type GitHub interface {
	ItemStates(ctx context.Context, refs []github.ItemRef) (map[github.ItemRef]github.ItemState, error)
}

GitHub reads the current state of pull requests and issues. A GitHub CLI token and a github.Client implement it in the app.

type History

type History interface {
	Record(ctx context.Context, c cleanuplog.Cleanup) error
	Recent(ctx context.Context, limit int) ([]cleanuplog.Cleanup, error)
	Clear(ctx context.Context) error
}

History records the worktrees the app cleaned up. *cleanuplog.Store implements it.

type Launches

type Launches interface {
	List(ctx context.Context) ([]launchlog.Launch, error)
	Forget(ctx context.Context, clonePath, worktree string) error
}

Launches reads and prunes the record of the worktrees the app launched sessions in. *launchlog.Store implements it.

type LinkedItem

type LinkedItem struct {
	// Kind is "pr" or "issue".
	Kind string `json:"kind"`

	// Owner and Name are the item's repository.
	Owner string `json:"owner"`
	Name  string `json:"name"`

	// Number is the item's number.
	Number int `json:"number"`

	Title string `json:"title"`
	URL   string `json:"url"`

	// State is ItemOpen, ItemMerged, or ItemClosed.
	State string `json:"state"`

	// ClosedAt is when the item was merged or closed, in RFC 3339, or "" while open.
	ClosedAt string `json:"closedAt"`

	// HeadOID is a pull request's head commit, or "".
	HeadOID string `json:"headOid"`

	// Launched reports a worktree the app launched the session in, which the automatic
	// cleanup looks after. Others are linked by their name alone.
	Launched bool `json:"launched"`
}

LinkedItem is the pull request or issue a worktree was made for, as GitHub reports it now.

type Notifier

type Notifier interface {
	WorktreesUpdated()
}

Notifier is told when an automatic sweep removed a worktree or changed how many need the user's attention.

type RefusedError

type RefusedError struct {
	// DisplayPath is the worktree's path relative to home with ~.
	DisplayPath string

	// Reason is why git refused.
	Reason string
}

RefusedError is git's refusal to remove a worktree, with a short reason such as "has uncommitted changes". It matches ErrRemovalRefused.

func (*RefusedError) Error

func (e *RefusedError) Error() string

Error describes the refusal.

func (*RefusedError) Is

func (e *RefusedError) Is(target error) bool

Is reports whether target is ErrRemovalRefused.

type RemoveResult

type RemoveResult struct {
	// RepoPath is the clone the worktree belongs to.
	RepoPath string `json:"repoPath"`

	// Path is the worktree's directory.
	Path string `json:"path"`

	// DisplayPath is Path relative to home with ~.
	DisplayPath string `json:"displayPath"`

	// Removed reports whether the worktree was removed.
	Removed bool `json:"removed"`

	// DeletedBranch is the branch deleted with the worktree, or "".
	DeletedBranch string `json:"deletedBranch"`

	// Item names the pull request or issue a cleaned-up worktree was for, e.g.
	// "acme-org/example-repo#184", or is "".
	Item string `json:"item"`

	// Reason explains why it was not removed, or why its branch was kept, or is "".
	Reason string `json:"reason"`
}

RemoveResult is the outcome of removing one worktree in a bulk removal.

type Repo

type Repo struct {
	// Path is the clone's directory under the clone root; pass it back to the removal
	// and prune calls.
	Path string `json:"path"`

	// DisplayPath is Path relative to home with ~.
	DisplayPath string `json:"displayPath"`

	// Name is the clone directory's name.
	Name string `json:"name"`

	// HasStale reports worktree entries whose directories are gone, which Prune clears.
	HasStale bool `json:"hasStale"`

	// Error explains why the repository's worktrees could not be listed, or is "".
	Error string `json:"error"`

	// Worktrees lists the main worktree first, then the linked ones in git's order.
	Worktrees []Worktree `json:"worktrees"`
}

Repo is one clone under the clone root and its worktrees.

type Runner

type Runner interface {
	Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error)
}

Runner runs a program with arguments and returns what it wrote. Implementations run the argv directly, never through a shell; execpath.Runner is the app's.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service lists and removes worktrees of the clones under the clone root.

func NewService

func NewService(cfg Config) *Service

NewService returns a worktrees Service over cfg.

func (*Service) CleanUp

func (s *Service) CleanUp(ctx context.Context, repoPath, path string) (RemoveResult, error)

CleanUp removes one finished worktree: its pull request merged or its issue closed, it has no uncommitted changes, every commit it has is on GitHub, and no session runs in it. The worktree is assessed again first, GitHub included. It releases the lock of an agent session that has ended, removes the worktree without --force, and deletes its own worktree-<name> branch while that still points at the commit checked.

func (*Service) CleanUpFinished

func (s *Service) CleanUpFinished(ctx context.Context) ([]RemoveResult, error)

CleanUpFinished cleans up every finished worktree under the clone root, one at a time, and reports each outcome. Each is checked again just before it is removed.

func (*Service) ClearCleanups

func (s *Service) ClearCleanups(ctx context.Context) error

ClearCleanups forgets the cleanups RecentCleanups lists. It removes nothing else.

func (*Service) ForceRemove

func (s *Service) ForceRemove(ctx context.Context, repoPath, path string) error

ForceRemove removes one unlocked linked worktree that has uncommitted changes, discarding them, with a single --force. Locked worktrees are refused even here, so a running session's worktree is never pulled out from under it.

func (*Service) LastSweep

func (s *Service) LastSweep() SweepReport

LastSweep returns the latest sweep's report; its Seq is 0 before the first sweep.

func (*Service) List

func (s *Service) List(ctx context.Context) (Snapshot, error)

List scans the clone root and returns every repository that has linked worktrees, with the status of each worktree and the pull request or issue it was made for. A repository that git cannot read is listed with an error rather than hiding the rest. A clone that is itself a linked worktree of another clone is folded into that repository.

func (*Service) Prune

func (s *Service) Prune(ctx context.Context, repoPath string) error

Prune clears the repository's entries for worktrees whose directories are gone. It never touches a worktree that still exists or any branch.

func (*Service) RecentCleanups

func (s *Service) RecentCleanups(ctx context.Context) ([]Cleanup, error)

RecentCleanups returns the worktrees the app cleaned up most recently, newest first, whether the user asked or the automatic sweep did it.

func (*Service) Remove

func (s *Service) Remove(ctx context.Context, repoPath, path string) error

Remove removes one linked worktree without --force. The repository must be a clone under the clone root and path one of its linked worktrees; the main worktree and locked worktrees are refused before git runs, and git itself refuses a worktree with uncommitted changes, which comes back as a RefusedError.

func (*Service) RemoveAllClean

func (s *Service) RemoveAllClean(ctx context.Context) ([]RemoveResult, error)

RemoveAllClean removes every clean, unlocked, linked worktree whose directory still exists, one at a time, and reports each outcome. Each removal is re-checked against the repository first, and git refuses any worktree that changed in the meantime.

func (*Service) Sweep

func (s *Service) Sweep(ctx context.Context) SweepReport

Sweep checks the worktrees the agent made for pull requests and issues and, when automatic cleanup is on, cleans up each finished one whose pull request merged or whose issue closed (see autoCleanable for which count). It never lists every clone: it looks only in clones with an agent worktree directory or a recorded launch, so it is cheap to run on a timer. It also drops the launch records of worktrees that are gone, and counts the linked worktrees of every clone from their git directories, again without running git. The report is kept for LastSweep, and the notifier is told when a worktree was removed or either count changed.

func (*Service) Unlock

func (s *Service) Unlock(ctx context.Context, repoPath, path string) error

Unlock releases a lock the coding agent wrote for a session that has certainly ended, so the worktree can be removed. A lock set by hand, or one whose session may still be running, is refused, and the lock is read again just before it is released.

type SettingsReader

type SettingsReader interface {
	Get(ctx context.Context) (settings.Settings, error)
}

SettingsReader reads the user's preferences; the clone root comes from them. *settings.Service implements it.

type Snapshot

type Snapshot struct {
	// Root is the clone root, shown relative to home with ~.
	Root string `json:"root"`

	// Repos are the repositories with linked worktrees (or that could not be listed),
	// sorted by path.
	Repos []Repo `json:"repos"`

	// CleanCount is how many worktrees "Remove all clean" would remove.
	CleanCount int `json:"cleanCount"`

	// FinishedCount is how many worktrees "Clean up finished" would remove.
	FinishedCount int `json:"finishedCount"`

	// ReviewCount is how many worktrees are done on GitHub but hold work that is not.
	ReviewCount int `json:"reviewCount"`

	// WorktreeCount is how many linked worktrees the snapshot lists, the main worktrees
	// aside.
	WorktreeCount int `json:"worktreeCount"`

	// LinkError explains why the pull requests and issues could not be read from GitHub,
	// or is "". The worktrees are listed without their items then.
	LinkError string `json:"linkError"`

	// ListedAt is when the snapshot was taken, in RFC 3339.
	ListedAt string `json:"listedAt"`
}

Snapshot is every repository under the clone root that has linked worktrees, as the Worktrees view shows it. Every field is a plain value.

type SweepReport

type SweepReport struct {
	// Seq numbers the sweeps since the app started, from 1; 0 means none has run yet.
	Seq int `json:"seq"`

	// At is when the sweep finished, in RFC 3339, or "".
	At string `json:"at"`

	// Enabled reports whether automatic cleanup was on.
	Enabled bool `json:"enabled"`

	// Cleaned lists the worktrees the sweep removed.
	Cleaned []RemoveResult `json:"cleaned"`

	// Failed lists the worktrees it tried to remove and could not, with why.
	Failed []RemoveResult `json:"failed"`

	// Leftover is how many worktrees are done on GitHub but still on disk and not in use,
	// so the user may want to look at them.
	Leftover int `json:"leftover"`

	// WorktreeCount is how many linked worktrees the clones under the clone root have
	// once the sweep is done, as a listing's Snapshot.WorktreeCount would count them. It
	// is read from each clone's git directory, without running git.
	WorktreeCount int `json:"worktreeCount"`

	// Error explains why the sweep could not run, or is "".
	Error string `json:"error"`
}

SweepReport is what the latest automatic sweep found and did.

type Sweeper

type Sweeper struct {
	// contains filtered or unexported fields
}

Sweeper runs a Service's sweeps on a timer. It is kept apart from Service, every exported method of which the window binds.

func NewSweeper

func NewSweeper(svc *Service) Sweeper

NewSweeper returns a Sweeper over svc.

func (Sweeper) Run

func (sw Sweeper) Run(ctx context.Context, interval time.Duration)

Run sweeps now and then every interval until ctx is canceled. A panicking sweep is logged and the next one still runs.

type Worktree

type Worktree struct {
	// Path is the worktree's directory as git reports it.
	Path string `json:"path"`

	// DisplayPath is Path relative to home with ~.
	DisplayPath string `json:"displayPath"`

	// Branch is the checked-out branch, or "" when detached.
	Branch string `json:"branch"`

	// Detached reports a detached HEAD.
	Detached bool `json:"detached"`

	// Main reports the repository's main worktree, which is never removable.
	Main bool `json:"main"`

	// Locked reports a `git worktree lock`; the agent locks a worktree while a session
	// runs in it.
	Locked bool `json:"locked"`

	// LockReason is the lock's reason, if any.
	LockReason string `json:"lockReason"`

	// AgentLock reports a lock the coding agent wrote for a session.
	AgentLock bool `json:"agentLock"`

	// StaleLock reports an agent lock whose session has certainly ended: its process is
	// gone, or the PID now belongs to a process that started later.
	StaleLock bool `json:"staleLock"`

	// CanUnlock reports a stale agent lock, which Unlock releases.
	CanUnlock bool `json:"canUnlock"`

	// Prunable reports an entry whose directory is gone.
	Prunable bool `json:"prunable"`

	// PrunableReason is git's explanation for Prunable.
	PrunableReason string `json:"prunableReason"`

	// Dirty reports uncommitted changes, counting untracked files.
	Dirty bool `json:"dirty"`

	// DirtyCount is the number of changed and untracked files.
	DirtyCount int `json:"dirtyCount"`

	// LastCommitUnix is the commit time of HEAD in Unix seconds, or 0 when unknown.
	LastCommitUnix int64 `json:"lastCommitUnix"`

	// Head is the commit the worktree has checked out.
	Head string `json:"head"`

	// Unpushed is how many commits on HEAD no remote-tracking branch has, or -1 when it
	// could not be counted (or was not, for the main worktree).
	Unpushed int `json:"unpushed"`

	// OnGitHub reports that every commit the worktree has is on GitHub: none is missing
	// from the remote-tracking branches, or HEAD is its pull request's head commit, which
	// GitHub keeps.
	OnGitHub bool `json:"onGitHub"`

	// Item is the pull request or issue the worktree was made for, or nil.
	Item *LinkedItem `json:"item"`

	// Stage is where the worktree stands (one of the Stage constants), or "" for a
	// worktree with no item or one locked by hand.
	Stage string `json:"stage"`

	// OwnBranch reports that the checked-out branch is the agent's worktree-<name> branch
	// for this worktree, which CleanUp deletes with it.
	OwnBranch bool `json:"ownBranch"`

	// ClaudeCreated reports a worktree under the repository's .claude/worktrees
	// directory, where the coding agent creates its worktrees.
	ClaudeCreated bool `json:"claudeCreated"`

	// CanRemove reports a clean, unlocked linked worktree that Remove accepts.
	CanRemove bool `json:"canRemove"`

	// CanForceRemove reports an unlocked linked worktree with uncommitted changes that
	// ForceRemove accepts after the user confirms.
	CanForceRemove bool `json:"canForceRemove"`

	// CanCleanUp reports a finished worktree that CleanUp removes, with its own branch.
	CanCleanUp bool `json:"canCleanUp"`

	// Error explains why the worktree's status could not be read, or is "".
	Error string `json:"error"`
}

Worktree is one row of the Worktrees view.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL