Documentation
¶
Overview ¶
Package worktrees makes the worktrees coding sessions run in, keeps track of them, lists the git worktrees of the user's local clones, and removes them safely.
The app makes one worktree per pull request or issue per clone, shared by every coding agent, in a hidden directory beside the clone (see ManagedRoot), on the item's own branch (worktree-pr-<n> or worktree-issue-<n>). A Maker makes or resumes it for a launch, and records it (see the worklog package). Every listing and sweep checks the records against git: a record whose worktree is gone is dropped, one whose worktree moved follows it, and a worktree on an item's branch with no record is recorded. Worktrees Claude Code made under a clone's .claude/worktrees before the app made them itself are found the same way and resumed where they are.
Listing covers every git repository in the user's repository locations, directly inside the clone root or a folder location, or a clone location itself (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;
- a worktree a running process works in, whatever agent or tool it is, is never removed (see the procs package);
- Unlock releases only a lock Claude Code 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 made for a pull request or issue 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 its 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. Only create.go fetches and adds worktrees; nothing changes a clone's own checkout.
Index ¶
- Constants
- Variables
- func ManagedPath(clone, name string) string
- func ManagedRoot(clone string) string
- type Action
- type AgentProcesses
- type Branch
- type BranchKey
- type BranchKind
- type BranchPick
- type BranchQuery
- type BranchResult
- type Cleanup
- type Config
- type EnsureRequest
- type Ensured
- type Entry
- type GitHub
- type Guard
- type History
- type InUseError
- type ItemState
- type ItemStatus
- type LinkedItem
- type Maker
- type MergedBranch
- type MergedPR
- type MergedPullRequest
- type Pick
- type Records
- type RefusedError
- type RemoveResult
- type Repo
- type RunFolder
- type RunFolders
- type Service
- func (s *Service) CleanUp(ctx context.Context, repoPath, path string, branches []string) (RemoveResult, error)
- func (s *Service) CleanUpFinished(ctx context.Context, picks []Pick) ([]RemoveResult, error)
- func (s *Service) ClearCleanups(ctx context.Context) error
- func (s *Service) DeleteBranches(ctx context.Context, picks []BranchPick) ([]BranchResult, error)
- func (s *Service) ForceRemove(ctx context.Context, repoPath, path string, branches []string) (RemoveResult, error)
- func (s *Service) LastSweep() SweepReport
- func (s *Service) List(ctx context.Context) (Snapshot, error)
- func (s *Service) MergedBranches(ctx context.Context) ([]MergedBranch, error)
- func (s *Service) Prune(ctx context.Context, repoPath string) error
- func (s *Service) RecentCleanups(ctx context.Context) ([]Cleanup, error)
- func (s *Service) Remove(ctx context.Context, repoPath, path string, branches []string) (RemoveResult, error)
- func (s *Service) RemoveAllClean(ctx context.Context, picks []Pick) ([]RemoveResult, error)
- func (s *Service) Sweep(ctx context.Context) SweepReport
- func (s *Service) Unlock(ctx context.Context, repoPath, path string) error
- type Session
- type SettingsReader
- type Snapshot
- type Stage
- type SweepReport
- type SweepSettings
- type Sweeper
- type Worktree
Constants ¶
const DefaultSweepInterval = 5 * time.Minute
DefaultSweepInterval is how often a Sweeper sweeps. A sweep runs git only in clones that have worktrees the app or Claude Code made, or records, and asks GitHub once, for one point, only when there are any.
Variables ¶
var ( // ErrInvalidRequest is returned for an EnsureRequest that cannot name a worktree. ErrInvalidRequest = errors.New("invalid worktree request") // ErrPathTaken is returned when something that is not a worktree is where the item's // worktree goes. ErrPathTaken = errors.New("something else is where the worktree goes") // ErrNoDefaultBranch is returned when the default branch of the item's repository // cannot be found. ErrNoDefaultBranch = errors.New("the repository's default branch could not be found") // ErrHeadMoved is returned when a pull request's head fetched for its new worktree is // not the commit whose files the launch checked. ErrHeadMoved = errors.New("the pull request's head moved after its files were checked") )
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") // ErrInUse is returned for a worktree a running process works in, which is never // removed (see InUseError). ErrInUse = errors.New("a session is running in the worktree") // ErrSessionsUnknown is returned when the automatic cleanup or a force removal cannot // tell whether a session runs in a worktree, so it leaves it. ErrSessionsUnknown = errors.New("can't tell whether a session is running in the worktree") // 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") // ErrBranchProtected is returned for a branch the user protects, or a remote's // default branch, which is never deleted. ErrBranchProtected = errors.New("the branch is protected") // ErrBranchGone is returned for a branch to delete that no longer exists. ErrBranchGone = errors.New("the branch is already gone") // ErrBranchMoved is returned for a branch to delete that moved since it was checked. ErrBranchMoved = errors.New("the branch moved since it was checked; check again") // 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 isn't a clone the repository // locations hold: directly inside the clone root or a folder location, or a clone // location itself. A location removed in Settings leaves its clones outside until it is // added again. ErrOutsideCloneRoot = errors.New("not a clone in your repository locations; check Settings → Repositories") // ErrRemovalRefused is matched by every RefusedError. ErrRemovalRefused = errors.New("git refused to remove the worktree") )
var ErrGitCommandNotAllowed = errors.New("git command not allowed")
ErrGitCommandNotAllowed is returned for a git command outside the allowlist; it is never run.
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 ManagedPath ¶ added in v0.2.0
ManagedPath returns where the app makes the worktree named name (pr-<n> or issue-<n>) of a clone.
func ManagedRoot ¶ added in v0.2.0
ManagedRoot returns where the app makes a clone's worktrees: a hidden directory beside the clone, <parent>/.<slug>/worktrees/<clone's name>, so for a clone under the clone root, ~/projects/.<slug>/worktrees/example-repo. Keeping worktrees out of the clone keeps a session's tools (and the agent's own instructions) from finding them inside it, needs no ignore rule in the clone, and the clone scans skip hidden directories.
Types ¶
type Action ¶ added in v0.2.0
type Action string
Action is what Ensure does, or would do, to give an item a worktree.
const ( // ActionResume reuses the item's worktree, where the app made or last found it. ActionResume Action = "resume" // ActionAdopt takes over a worktree found on the item's branch somewhere else, such // as one Claude Code made under the clone's .claude/worktrees, and records it. ActionAdopt Action = "adopt" // ActionAttach makes a worktree on the item's branch, which is left from an earlier // worktree, keeping every commit on it. ActionAttach Action = "attach" // ActionCreate fetches the pull request's head, or the default branch for an issue, // and makes a worktree on a new branch from it. ActionCreate Action = "create" )
Ensure's actions.
type AgentProcesses ¶ added in v0.2.0
type AgentProcesses interface {
// AgentProcesses returns the coding agent of each followed session's process, by PID.
AgentProcesses(ctx context.Context) (map[int]agent.ID, error)
}
AgentProcesses names the processes of the agent sessions the app follows. The app adapts the sessions ledger to it.
type Branch ¶ added in v0.2.0
type Branch struct {
// Name is the branch, as in feature-x.
Name string `json:"name"`
// Head is the commit it points at; it is deleted only while it still does.
Head string `json:"head"`
// Kind is why it is offered.
Kind BranchKind `json:"kind"`
// Deletable reports that nothing on it would be lost, every commit on it being on
// GitHub, and that nothing protects it.
Deletable bool `json:"deletable"`
// Reason says why it may not go, or is "".
Reason string `json:"reason"`
}
Branch is a local branch the app offers to delete.
type BranchKey ¶ added in v0.2.0
BranchKey names a repository's branch in the answer to MergedPullRequests: the repository's Key and the branch.
type BranchKind ¶ added in v0.2.0
type BranchKind string
BranchKind is why the app offers to delete a branch.
const ( // BranchOwn is a worktree's own worktree-<name> branch. BranchOwn BranchKind = "own" // BranchPullRequest is a pull request's own branch, checked out in its worktree. BranchPullRequest BranchKind = "pullRequest" // BranchMerged is a clone's branch whose pull request merged. BranchMerged BranchKind = "merged" )
Why the app offers to delete a branch.
type BranchPick ¶ added in v0.2.0
type BranchPick struct {
RepoPath string `json:"repoPath"`
Name string `json:"name"`
Head string `json:"head"`
}
BranchPick is one branch the user ticked to delete: its clone, its name, and the commit it pointed at when it was offered.
type BranchQuery ¶ added in v0.2.0
BranchQuery asks which of a repository's branch names were the head of a merged pull request.
type BranchResult ¶ added in v0.2.0
type BranchResult struct {
// RepoPath is the clone, and DisplayRepo it with ~ for the home directory.
RepoPath string `json:"repoPath"`
DisplayRepo string `json:"displayRepo"`
Name string `json:"name"`
// Head is the commit it pointed at, which restores it: git branch <name> <head>.
Head string `json:"head"`
// Deleted reports whether it was deleted, and Reason why not, or is "".
Deleted bool `json:"deleted"`
Reason string `json:"reason"`
}
BranchResult is the outcome of deleting one branch.
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 Config ¶
type Config struct {
// Settings supplies the repository locations and whether the sweep cleans up on its own.
Settings SettingsReader
// Git runs git argv; it also reads remotes during the clone-root scan.
Git execpath.Runner
// Finder resolves the git binary up front, so a missing git fails with a clear
// error. Without it, Git resolves "git" itself.
Finder execpath.Finder
// Guard works out what the commands worktree creation runs that reach a remote (its
// fetches and its ls-remote) or write a worktree's files (git worktree add) run with:
// gitread's guards, which refuse a clone whose own git config holds a setting outside
// their allowlist, so none runs a program the clone's own config names. They run the
// same git as every other command here, with the guard's environment, which holds their
// settings, through GitWith. Core gives every Service one; without it, as in tests that
// script git, they run as every other command here does.
Guard Guard
// GitWith runs git argv with the whole environment env, as a guarded command needs: the
// same runner as Git but for the environment. It defaults to an execpath.Exec with env.
GitWith func(env []string) execpath.Runner
// Home is the user's home directory; it expands a ~ clone root and shortens paths.
Home string
// Reader bounds how long a read of one of the other repository locations may take, so
// one that hangs is skipped rather than holding a listing, a sweep, or a launch's
// worktree. Optional: without it they are read directly.
Reader *localrepos.Reader
// Clock stamps snapshots. It defaults to the system clock.
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
// Records holds the worktrees the app made or found for pull requests and issues.
Records Records
// Procs lists the running processes, to tell the worktrees a session works in.
// Without it no worktree counts as in use by a process; a lock Claude Code holds
// still counts.
Procs procs.Lister
// History records each cleanup, for the view's list of recent ones.
History History
// Agents names the processes of the agent sessions the app follows, so the view says
// "Claude" rather than the name of Claude Code's program. Optional.
Agents AgentProcesses
// Runs names the folders the app's own runs work in, which count as in use: nothing
// removes a worktree an agent's run works in, an orphan after a quit included.
// Optional.
Runs RunFolders
// Events hears an event.WorktreesUpdated when a sweep removed a worktree or changed
// how many need the user's attention, and an event.WorktreesProgress as the window's
// listing goes.
Events event.Sink
// Clones is the app's one set of clone locks, which every job that changes a clone
// takes, so a worktree is never made or removed while a run is using its clone. It
// defaults to a set of the Service's own.
Clones *clonelock.Set
// Logger receives sweep failures and, at Debug, why GitHub could not say which pull
// requests and issues the worktrees belong to. Without it they are not logged.
Logger *slog.Logger
}
Config holds a Service's dependencies. Settings and Git are required; the rest are optional.
type EnsureRequest ¶ added in v0.2.0
type EnsureRequest struct {
// Clone is the clone's absolute directory.
Clone string
// Remote is the clone's remote for the item's repository, such as "origin", or
// "upstream" in a fork's clone; "" is origin.
Remote string
// Owner and Name are the item's repository.
Owner string
Name string
// Kind and Number are the item.
Kind item.Kind
Number int
// DefaultBranch is the repository's default branch as GitHub reports it, or "". An
// issue's worktree starts from it.
DefaultBranch string
// Base is the branch a pull request merges into, or "". Ensure fetches it into its
// remote-tracking ref, so the worktree has it fresh to rebase onto, merge, or compare
// with; a fetch that fails only says so (see fetchBase).
Base string
// Head is the pull request's head commit whose files the launch checked, or "" when
// it checked none. A pull request's worktree made now must start there (see
// verifyHead).
Head string
}
EnsureRequest asks for an item's worktree in a clone.
type Ensured ¶ added in v0.2.0
type Ensured struct {
// Path is the worktree's directory.
Path string
// Branch is the branch it has, or will have, checked out.
Branch string
// Action is what was done, or would be.
Action Action
// Base names what a created worktree starts from: "the pull request's head" or the
// remote's default branch, such as "origin/main"; "" for the other actions.
Base string
// Head is the commit the worktree has checked out, or "" before it is made.
Head string
// Dirty is how many files have uncommitted changes in an existing worktree, or -1
// when that could not be read; 0 for one not made yet.
Dirty int
// Notice says what Ensure could not do as asked but worked around, such as starting
// from the last fetched default branch when the fetch failed, or "".
Notice string
}
Ensured is an item's worktree, as Ensure found or made it, or Plan says it would.
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 ¶
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 GitHub ¶
type GitHub interface {
// ItemStates returns the state of each item in refs that GitHub knows, keyed by the
// ref's Key.
ItemStates(ctx context.Context, refs []item.Ref) (map[string]ItemState, error)
// MergedPullRequests returns the merged pull requests whose head branch had each
// name asked about, newest first, keyed by BranchKey. A name none had is left out.
MergedPullRequests(ctx context.Context, queries []BranchQuery) (map[BranchKey][]MergedPR, error)
}
GitHub reads the current state of pull requests and issues. The app adapts the GitHub client to it, with the GitHub CLI's token.
type Guard ¶ added in v0.2.0
type Guard interface {
RemoteSetupFor(ctx context.Context, dir, remote string) (gitread.Setup, error)
CheckoutSetup(ctx context.Context, dir string) (gitread.Setup, error)
LocalSetup(ctx context.Context, dir string) (gitread.Local, error)
ReadEnv() []string
}
Guard works out what a git command that reaches the clone's remote, or writes a worktree's files, runs with, one in a clone or a worktree that could run one of the clone's programs, as a status or a removal, and the environment a read runs with: gitread's RemoteSetupFor, CheckoutSetup, LocalSetup, and ReadEnv, *gitread.Git.
type History ¶
type History interface {
RecordCleanup(ctx context.Context, c worklog.Cleanup) error
RecentCleanups(ctx context.Context, limit int) ([]worklog.Cleanup, error)
ClearCleanups(ctx context.Context) error
}
History records the worktrees the app cleaned up. *worklog.Store implements it.
type InUseError ¶ added in v0.2.0
type InUseError struct {
// Sessions are the processes, by PID.
Sessions []Session
}
InUseError is returned for a worktree running processes work in. It matches ErrInUse.
func (*InUseError) Error ¶ added in v0.2.0
func (e *InUseError) Error() string
Error names the processes, as in "a session is running in the worktree: codex (pid 4242)".
func (*InUseError) Is ¶ added in v0.2.0
func (e *InUseError) Is(target error) bool
Is makes an InUseError match ErrInUse.
type ItemState ¶ added in v0.2.0
type ItemState struct {
// PullRequest reports a pull request; false is an issue.
PullRequest bool
Title string
URL string
// State is ItemOpen, ItemMerged, or ItemClosed; any other value reads as ItemOpen.
State ItemStatus
// ClosedAt is when the item was merged or closed, or zero while it is open.
ClosedAt time.Time
// HeadOID is a pull request's head commit SHA; "" for an issue.
HeadOID string
// HeadRef is a pull request's head branch; "" for an issue.
HeadRef string
}
ItemState is what GitHub says about a pull request or issue as of now.
type ItemStatus ¶ added in v0.2.0
type ItemStatus string
ItemStatus is whether a pull request or issue is open, merged, or closed.
const ( ItemOpen ItemStatus = "open" ItemMerged ItemStatus = "merged" ItemClosed ItemStatus = "closed" )
Item states, as LinkedItem.State reports them.
type LinkedItem ¶
type LinkedItem struct {
Kind item.Kind `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 ItemStatus `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"`
// HeadRef is a pull request's head branch, as in feature-x, or "".
HeadRef string `json:"headRef"`
// Launched reports a worktree the app launched a session in, which the automatic
// cleanup looks after. Others are linked by their name or branch alone.
Launched bool `json:"launched"`
}
LinkedItem is the pull request or issue a worktree was made for, as GitHub reports it now.
type Maker ¶ added in v0.2.0
type Maker struct {
// contains filtered or unexported fields
}
Maker finds and makes the worktrees launches start in: one per item per clone, shared by every agent, under the clone's managed root (see ManagedRoot), and recorded. It is kept apart from Service, every exported method of which the window binds.
func (*Maker) Ensure ¶ added in v0.2.0
Ensure returns the item's worktree, making it when it has none, in this order:
- the worktree the item's record names, while git still has it registered there;
- a worktree with the item's branch (worktree-pr-<n> or worktree-issue-<n>) checked out anywhere, such as one Claude Code made under the clone's .claude/worktrees, which is adopted;
- a worktree added on the item's branch, left from an earlier worktree, keeping every commit on it and never moving it;
- for a pull request, its head fetched from the item's remote into the item's branch, and a worktree added on it;
- for an issue, the repository's default branch fetched, and a worktree added on a new item's branch from it.
Entries whose directories are gone are pruned first. When the worktree's directory is taken by something git does not know, git's entries are pruned and the add is tried once more; it never deletes anything. The worktree is recorded with its item. Calls for one item share one run, and one clone's git work runs one call at a time. While a run (a release, checks, a script) is using the clone, Ensure fails at once, naming it.
type MergedBranch ¶ added in v0.2.0
type MergedBranch struct {
// RepoPath is the clone, and DisplayRepo it with ~ for the home directory.
RepoPath string `json:"repoPath"`
DisplayRepo string `json:"displayRepo"`
// Branch is the branch, of kind BranchMerged.
Branch Branch `json:"branch"`
// PullRequest is the merged pull request it was the head of.
PullRequest MergedPullRequest `json:"pullRequest"`
// Unpushed counts the commits on it that are neither in its pull request nor on
// GitHub, when they alone keep it (-1 when they couldn't be counted), and is 0
// otherwise. The window offers such a branch only once the user asks, and deletes it
// only once they confirm they don't need those commits: DeleteBranches deletes a pick
// at the commit offered whatever it holds, and its result names that commit, which
// brings the branch back until git prunes it.
Unpushed int `json:"unpushed"`
}
MergedBranch is a clone's local branch whose pull request merged.
type MergedPR ¶ added in v0.2.0
type MergedPR struct {
Number int
Title string
URL string
MergedAt time.Time
// HeadOID is the commit its head branch was at, which GitHub keeps.
HeadOID string
}
MergedPR is a merged pull request a branch was the head of.
type MergedPullRequest ¶ added in v0.2.0
type MergedPullRequest struct {
// Repo names its repository, as in acme-org/example-repo.
Repo string `json:"repo"`
Number int `json:"number"`
Title string `json:"title"`
URL string `json:"url"`
// MergedAt is when it merged, in RFC 3339.
MergedAt string `json:"mergedAt"`
}
MergedPullRequest is a merged pull request, as the cleanup of merged branches shows it.
type Pick ¶ added in v0.2.0
type Pick struct {
RepoPath string `json:"repoPath"`
Path string `json:"path"`
Branches []string `json:"branches"`
}
Pick is one worktree a bulk removal or cleanup takes, as the user ticked it: its clone, its directory, and the branches to delete with it.
type Records ¶ added in v0.2.0
type Records interface {
Worktrees(ctx context.Context) ([]worklog.Record, error)
Record(ctx context.Context, r worklog.Record) error
Forget(ctx context.Context, clonePath, worktree string) error
}
Records reads, writes, and prunes the record of the worktrees the app made or found for pull requests and issues. *worklog.Store implements it.
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) 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"`
// DeletedBranches are the branches deleted with the worktree.
DeletedBranches []string `json:"deletedBranches"`
// 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; 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 in the repository locations and its worktrees.
type RunFolder ¶ added in v0.4.0
type RunFolder struct {
// Dir is the folder, and PID the run's program, or 0 while it starts.
Dir string
PID int
// Agent is the agent it runs, and By names it: "⚡ Fix checks".
Agent agent.ID
By string
}
RunFolder is a folder one of the app's own runs works in now.
type RunFolders ¶ added in v0.4.0
RunFolders names the folders the app's own runs work in now: an agent's background run, one from before the app restarted included, which the process list leaves out (the app's own children, and an orphan whose parent is the process manager). Core adapts the runs.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service lists and removes worktrees of the clones in the repository locations.
func NewService ¶
NewService returns a worktrees Service over cfg.
func (*Service) CleanUp ¶
func (s *Service) CleanUp(ctx context.Context, repoPath, path string, branches []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, by its lock or as a running process. 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 the branches named, of those it offers, as Remove does.
func (*Service) CleanUpFinished ¶
CleanUpFinished cleans up the finished worktrees picked, one at a time, each with the branches picked for it, and reports each outcome. Each is checked against a fresh listing, GitHub included, and again just before it is removed: one no longer finished is left, with why.
func (*Service) ClearCleanups ¶
ClearCleanups forgets the cleanups RecentCleanups lists. It removes nothing else.
func (*Service) DeleteBranches ¶ added in v0.2.0
func (s *Service) DeleteBranches(ctx context.Context, picks []BranchPick) ([]BranchResult, error)
DeleteBranches deletes the branches the user ticked in the cleanup of merged branches, each checked again first: the repository locations must hold its clone, the user must not protect it, it must not be a remote's default branch or checked out in any worktree, and it must still point at the commit it was offered at. A branch with commits that aren't on GitHub (MergedBranch.Unpushed) is among the picks only once the user confirmed they don't need them; pinned to the commit offered, it loses nothing they weren't shown. Each clone is read once and its branches deleted in turn, a few clones at a time. It reports each outcome, in the order picked, with the commit that restores a deleted branch.
func (*Service) ForceRemove ¶
func (s *Service) ForceRemove(ctx context.Context, repoPath, path string, branches []string) (RemoveResult, error)
ForceRemove removes one unlocked linked worktree that has uncommitted changes, discarding them, with a single --force, and the branches named as Remove does. Locked worktrees, and ones a running process works in, are refused even here, so a running session's worktree is never pulled out from under it; so is every worktree when the running processes cannot be listed, since nothing else would stop it then.
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 ¶
List scans the repository locations 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. It tells the window how far it has got as it goes (event.WorktreesProgress).
git runs only in the clones worth listing (see worthListing): those whose git folder registers a linked worktree, can't be found, or can't be read, and those a record names. A clone with none of these runs no git at all, so one with no worktrees whose git folder is there but which git can't read shows no error.
func (*Service) MergedBranches ¶ added in v0.2.0
func (s *Service) MergedBranches(ctx context.Context) ([]MergedBranch, error)
MergedBranches lists the local branches of every clone in the repository locations whose pull request merged on GitHub: each branch that was the head branch of a merged pull request in one of the clone's GitHub repositories, and each worktree-pr-<n> branch whose pull request merged. Branches the user protects and each remote's default branch are left out. Each says whether it may go: its commits are all on GitHub (it is at the merged head, behind it, or pushed), and no worktree has it checked out. It asks GitHub once per fifty branch names, only for clones with a branch to ask about, and changes nothing.
func (*Service) Prune ¶
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 ¶
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, branches []string) (RemoveResult, error)
Remove removes one linked worktree without --force, and with it the branches named, of those it offers (see Worktree.Branches): each goes only when nothing on it would be lost and nothing protects it, and only while it still points at the commit assessed. The repository must be a clone in the repository locations and path one of its linked worktrees, which is assessed again first. The main worktree, a locked one, and one a session works in are refused before git runs, and git itself refuses one with uncommitted changes, which comes back as a RefusedError. The result names the branches deleted, and says why any other one named was kept.
func (*Service) RemoveAllClean ¶
RemoveAllClean removes the clean, unlocked, linked worktrees picked, one at a time, each with the branches picked for it as Remove does, and reports each outcome. Each is checked against a fresh listing first: one that is no longer clean and removable is left, with why, 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 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), and that no running process works in; when the processes cannot be listed, it cleans up none. It never lists every clone: it looks only in clones with worktrees the app or Claude Code made, or with records, so it is cheap to run on a timer. It also checks the records against git (see reconcile), and counts the linked worktrees of every clone from their git directories, again without running git. The report is kept for LastSweep, and an event.WorktreesUpdated is emitted when a worktree was removed or either count changed.
type Session ¶ added in v0.2.0
type Session struct {
// PID is the process's ID.
PID int `json:"pid"`
// Command is its program's name, such as "codex", as the OS reports it. Claude Code's
// program is named after its version, such as "2.1.319".
Command string `json:"command"`
// Agent is the coding agent when the process is a session the app follows, or "". A
// followed session stands for the processes folded with it, such as the user's shell
// it runs in.
Agent agent.ID `json:"agent"`
// By names the app's own run working there, as "⚡ Fix checks", or is "" for any other
// process: an agent Autopilot runs in the background, which the process list leaves
// out, as it leaves out the app's children and an orphan after a quit.
By string `json:"by"`
}
Session is a running process that works in a worktree. The processes it started there, such as a helper that keeps the Mac awake, are folded into it.
type SettingsReader ¶
type SettingsReader interface {
Get(ctx context.Context) (SweepSettings, error)
}
SettingsReader reads the sweep settings as they are now, so every listing and sweep sees the user's latest choices. The app adapts the settings service to it.
type Snapshot ¶
type Snapshot struct {
// Roots are the repository locations, the clone root first, shown relative to home
// with ~.
Roots []string `json:"roots"`
// Unread are the other locations the listing couldn't read, as on a drive that is
// unplugged, with ~. Their clones aren't listed.
Unread []string `json:"unread"`
// 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"`
// SessionsUnknown reports that the running processes could not be listed, so no
// worktree shows a session, and the automatic cleanup removes none.
SessionsUnknown bool `json:"sessionsUnknown"`
// ListedAt is when the snapshot was taken, in RFC 3339.
ListedAt string `json:"listedAt"`
}
Snapshot is every repository in the repository locations that has linked worktrees, as the Worktrees view shows it. Every field is a plain value.
type Stage ¶ added in v0.2.0
type Stage string
Stage is where a worktree stands with its pull request or issue.
const ( // StageNone is a worktree with no item, or one locked by hand. StageNone Stage = "" // StageInUse is a worktree a running process works in, or a running agent session // holds by its lock. StageInUse Stage = "in-use" // StageActive is a worktree whose pull request or issue is still open. StageActive Stage = "active" // StageFinished is a worktree whose item is done and that CleanUp removes without // losing anything. StageFinished Stage = "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 Stage = "needs-review" )
Stages of a worktree's pull request or issue, as Worktree.Stage reports them.
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 in the repository locations 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 SweepSettings ¶ added in v0.2.0
type SweepSettings struct {
// CloneRoot is the directory whose children are the clones, as entered, e.g.
// "~/projects".
CloneRoot string
// CloneLocations are the user's other repository locations, as stored.
CloneLocations []localrepos.Location
// AutoCleanup lets the automatic sweep clean up a finished worktree once its pull
// request merges or its issue closes.
AutoCleanup bool
// Branches are the user's rules for deleting branches: the automatic sweep follows
// them, and nothing ever deletes a branch they protect.
Branches branchrules.Rules
}
SweepSettings is the part of the user's preferences the worktree service reads. Every field is a plain value.
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 ¶
NewSweeper returns a Sweeper over svc that sweeps as often as every says, the user's setting, or every DefaultSweepInterval when nil.
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, nor the commit
// the app made the worktree at, fetched from GitHub (worklog.Record.FetchedHead), 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 and the commit it was made at, 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.
Stage Stage `json:"stage"`
// OwnBranch reports that the checked-out branch is the worktree's own
// worktree-<name> branch, which CleanUp deletes with it.
OwnBranch bool `json:"ownBranch"`
// Managed reports a worktree the app looks after: one it made (under the clone's
// managed root), one Claude Code made under the clone's .claude/worktrees, or one the
// app recorded.
Managed bool `json:"managed"`
// Legacy reports a worktree Claude Code made under the clone's .claude/worktrees.
Legacy bool `json:"legacy"`
// Agent is the agent of the latest session the app launched there, or "".
Agent agent.ID `json:"agent"`
// LastLaunchedAt is when that session started, in RFC 3339, or "".
LastLaunchedAt string `json:"lastLaunchedAt"`
// Launches counts the sessions the app launched there.
Launches int `json:"launches"`
// InUse lists the running processes that work in the worktree.
InUse []Session `json:"inUse"`
// 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"`
// Branches are the local branches a removal of the worktree can take with it: its own
// worktree-<name> branch, and its pull request's own branch when the worktree has that
// checked out. Each says whether it may go; which do is the user's choice.
Branches []Branch `json:"branches"`
// Error explains why the worktree's status could not be read, or is "".
Error string `json:"error"`
// contains filtered or unexported fields
}
Worktree is one row of the Worktrees view.