worktree

package
v0.9.32 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package worktree manages git worktrees for term-llm sessions.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDirty              = errors.New("worktree has uncommitted changes")
	ErrExists             = errors.New("worktree already exists")
	ErrConflict           = errors.New("merge back has conflicts")
	ErrRootDirty          = errors.New("root checkout has uncommitted changes")
	ErrMergeCleanupFailed = errors.New("merge succeeded but worktree cleanup failed")
)

Functions

func CheckoutRoot added in v0.0.398

func CheckoutRoot(dir string) (string, error)

CheckoutRoot returns the canonical root of the specific checkout containing dir.

func Diff

func Diff(dir string) (string, error)

Diff returns a bounded unified diff from the recorded base, including untracked files. Callers that can be abandoned should use DiffContext.

func InUseByDir added in v0.0.326

func InUseByDir(ctx context.Context, store session.Store, dirs []string) (map[string][]InUseSession, error)

InUseByDir returns active, non-archived sessions grouped by requested worktree directory.

func IsGitRepo

func IsGitRepo(dir string) bool

IsGitRepo reports whether dir is inside a git working tree.

func IsGitRepoContext added in v0.0.404

func IsGitRepoContext(ctx context.Context, dir string) bool

IsGitRepoContext is IsGitRepo with caller-controlled cancellation.

func MainRepoRoot

func MainRepoRoot(dir string) (string, error)

MainRepoRoot returns the canonical main checkout root for any worktree in the repo.

func MainRepoRootContext added in v0.0.404

func MainRepoRootContext(ctx context.Context, dir string) (string, error)

MainRepoRootContext is MainRepoRoot with caller-controlled cancellation.

func ManagedRoot

func ManagedRoot(repoRoot string) (string, error)

ManagedRoot returns the bucket for managed worktrees for repoRoot.

func ManagedRootBase

func ManagedRootBase() (string, error)

ManagedRootBase returns the global worktree data directory.

func MergeBackAndCleanup added in v0.0.323

func MergeBackAndCleanup(ctx context.Context, dir string, opts MergeOptions, store session.Store, excludeSessionID string) (MergeResult, CleanupResult, error)

MergeBackAndCleanup merges a worktree into root and removes it when no other sessions are bound to it. The excluded session is normally the caller's own session, which will be rebound to root after cleanup.

func Promote

func Promote(ctx context.Context, dir, branch string) error

Promote creates a branch at the worktree HEAD and checks it out.

func PromoteToRootAndCleanup added in v0.9.1

func PromoteToRootAndCleanup(ctx context.Context, dir, branch string, opts PromoteOptions, store session.Store, excludeSessionID string) (PromoteResult, CleanupResult, error)

PromoteToRootAndCleanup promotes a worktree to a root branch and removes the source when no other active sessions remain bound to it. The excluded session is normally the caller, which will continue from the root checkout.

func Remove

func Remove(ctx context.Context, dir string, opts RemoveOptions) error

Remove removes a managed worktree and prunes git's worktree metadata.

func TouchLastBound

func TouchLastBound(dir string) error

TouchLastBound records that a session bound this worktree now.

Types

type AssistedMergeOptions

type AssistedMergeOptions struct {
	Message string
}

AssistedMergeOptions configures StartAssistedMerge.

type AssistedMergeResult

type AssistedMergeResult struct {
	RootDir            string   `json:"root_dir,omitempty"`
	WorktreeDir        string   `json:"worktree_dir,omitempty"`
	WorktreeName       string   `json:"worktree_name,omitempty"`
	PreviousRootRef    string   `json:"previous_root_ref,omitempty"`
	PreviousRootBranch string   `json:"previous_root_branch,omitempty"`
	Base               string   `json:"base,omitempty"`
	RootHead           string   `json:"root_head,omitempty"`
	WorktreeHead       string   `json:"worktree_head,omitempty"`
	SnapshotCommit     string   `json:"snapshot_commit,omitempty"`
	ChangedFiles       []string `json:"changed_files,omitempty"`
	Conflicts          []string `json:"conflicts,omitempty"`
	RootStatus         string   `json:"root_status,omitempty"`
	Applied            bool     `json:"applied"`
	NeedsResolution    bool     `json:"needs_resolution"`
	Message            string   `json:"message,omitempty"`
}

AssistedMergeResult describes worktree changes prepared in the root checkout for LLM-assisted merge resolution.

func StartAssistedMerge

func StartAssistedMerge(ctx context.Context, dir string, opts AssistedMergeOptions) (AssistedMergeResult, error)

StartAssistedMerge applies the worktree snapshot directly to the current root checkout branch. It leaves conflicts in place there for LLM-assisted resolution, or leaves a clean application staged and uncommitted.

type CleanupResult added in v0.0.323

type CleanupResult struct {
	Removed bool           `json:"removed"`
	InUse   []InUseSession `json:"in_use,omitempty"`
}

CleanupResult describes post-merge worktree removal.

func CleanupAfterOperation added in v0.9.1

func CleanupAfterOperation(ctx context.Context, dir string, store session.Store, excludeSessionID string) (CleanupResult, error)

CleanupAfterOperation removes a managed worktree after merge or promotion when no active session remains bound to it.

type CreateOptions

type CreateOptions struct {
	Name         string
	Base         string
	Branch       string
	SetupScript  string
	SetupTimeout time.Duration
	CopyFiles    []string
	// MoveChanges transfers staged, unstaged, and untracked changes from the
	// main checkout into the new worktree, leaving the main checkout clean.
	MoveChanges bool
	ProgressFn  func(message string)
	Progress    chan<- Progress
}

CreateOptions configures Create.

type DiffResult added in v0.0.394

type DiffResult struct {
	Diff              string   `json:"diff"`
	Truncated         bool     `json:"truncated"`
	TruncationReasons []string `json:"truncation_reasons,omitempty"`
}

DiffResult contains bounded worktree diff output and any truncation metadata.

func DiffContext added in v0.0.394

func DiffContext(ctx context.Context, dir string) (DiffResult, error)

DiffContext returns a bounded unified diff and stops active Git commands when ctx is canceled. At most maxDiffUntrackedFiles are included.

func (DiffResult) DisplayDiff added in v0.0.394

func (r DiffResult) DisplayDiff() string

DisplayDiff returns the diff with a human-readable truncation notice.

type InUseSession

type InUseSession struct {
	ID        string    `json:"id"`
	Number    int64     `json:"number,omitempty"`
	Name      string    `json:"name,omitempty"`
	Title     string    `json:"title,omitempty"`
	Status    string    `json:"status,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

InUseSession describes a session bound to a worktree.

func InUse

func InUse(ctx context.Context, store session.Store, dir string) ([]InUseSession, error)

InUse returns active, non-archived sessions currently bound to dir when the store exposes worktree summaries.

type MergeOptions

type MergeOptions struct {
	AllowDirty bool
	Commit     bool
	Message    string
}

MergeOptions configures MergeBack.

type MergeResult

type MergeResult struct {
	Applied              bool     `json:"applied"`
	Committed            bool     `json:"committed"`
	SnapshotCommit       string   `json:"snapshot_commit,omitempty"`
	Conflicts            []string `json:"conflicts,omitempty"`
	Message              string   `json:"message,omitempty"`
	WorktreeDir          string   `json:"worktree_dir,omitempty"`
	RootDir              string   `json:"root_dir,omitempty"`
	WorktreeName         string   `json:"worktree_name,omitempty"`
	Base                 string   `json:"base,omitempty"`
	WorktreeHead         string   `json:"worktree_head,omitempty"`
	RootHead             string   `json:"root_head,omitempty"`
	RootStatus           string   `json:"root_status,omitempty"`
	ChangedFiles         []string `json:"changed_files,omitempty"`
	ConflictReset        bool     `json:"conflict_reset,omitempty"`
	ConflictCleanupError string   `json:"conflict_cleanup_error,omitempty"`
}

MergeResult describes the result of MergeBack.

func MergeBack

func MergeBack(ctx context.Context, dir string, opts MergeOptions) (MergeResult, error)

MergeBack snapshots the worktree and cherry-picks it into the root checkout staged and uncommitted by default.

type Progress

type Progress struct {
	Message string `json:"message"`
}

Progress is emitted by long-running worktree operations.

type PromoteOptions

type PromoteOptions struct {
	Message string
}

PromoteOptions configures PromoteToRoot.

type PromoteResult

type PromoteResult struct {
	RootDir                     string   `json:"root_dir,omitempty"`
	WorktreeDir                 string   `json:"worktree_dir,omitempty"`
	WorktreeName                string   `json:"worktree_name,omitempty"`
	Branch                      string   `json:"branch,omitempty"`
	PreviousRootRef             string   `json:"previous_root_ref,omitempty"`
	PreviousRootBranch          string   `json:"previous_root_branch,omitempty"`
	WorktreeHead                string   `json:"worktree_head,omitempty"`
	SnapshotCommit              string   `json:"snapshot_commit,omitempty"`
	ChangedFiles                []string `json:"changed_files,omitempty"`
	RootStatus                  string   `json:"root_status,omitempty"`
	Applied                     bool     `json:"applied"`
	OriginalWorktreeStillExists bool     `json:"original_worktree_still_exists"`
}

PromoteResult describes the result of PromoteToRoot.

func PromoteToRoot

func PromoteToRoot(ctx context.Context, dir, branch string, opts PromoteOptions) (PromoteResult, error)

PromoteToRoot creates a branch from the worktree HEAD, checks it out in the root checkout, and applies dirty worktree changes there staged and uncommitted. The original linked worktree is left in place.

type RemoveOptions

type RemoveOptions struct {
	Force        bool
	DeleteBranch bool
}

RemoveOptions configures Remove.

type Status

type Status string

Status describes where a worktree is in its lifecycle.

const (
	StatusCreating Status = "creating"
	StatusReady    Status = "ready"
	StatusFailed   Status = "failed"
)

type Worktree

type Worktree struct {
	Name                    string    `json:"name"`
	Dir                     string    `json:"dir"`
	RepoRoot                string    `json:"repo_root,omitempty"`
	Branch                  string    `json:"branch,omitempty"`
	Base                    string    `json:"base"` // full base SHA
	Detached                bool      `json:"detached"`
	Status                  Status    `json:"status"`
	DirtyFiles              int       `json:"dirty_files"`
	HeadSHA                 string    `json:"head_sha"`
	Upstream                string    `json:"upstream,omitempty"`
	UpstreamAvailable       bool      `json:"upstream_available"`
	Ahead                   int       `json:"ahead"`
	Behind                  int       `json:"behind"`
	Diverged                bool      `json:"diverged"`
	MainAhead               int       `json:"main_ahead"`
	MainBehind              int       `json:"main_behind"`
	MainDivergenceAvailable bool      `json:"main_divergence_available"`
	MetadataError           string    `json:"metadata_error,omitempty"`
	CreatedAt               time.Time `json:"created_at,omitempty"`
	LastBoundAt             time.Time `json:"last_bound_at,omitempty"`
	Orphaned                bool      `json:"orphaned,omitempty"`
}

Worktree describes a managed git worktree.

func Create

func Create(ctx context.Context, repoRoot string, opts CreateOptions) (*Worktree, error)

Create creates a managed worktree. Detached HEAD is used unless Branch is set.

func DescribeCheckout added in v0.9.0

func DescribeCheckout(dir string) (Worktree, error)

DescribeCheckout returns HEAD, branch, upstream, divergence, and dirty detail for any checkout, including the repository root.

func Get

func Get(dir string) (*Worktree, error)

Get describes a worktree by directory.

func List

func List(repoRoot string) ([]Worktree, error)

List returns managed worktrees for the repository, excluding the main checkout.

func ListAll

func ListAll() ([]Worktree, error)

ListAll scans all managed buckets using metadata. Orphaned buckets are marked.

Directories

Path Synopsis
Package recovery contains the user-facing worktree promotion recovery flow shared by interactive clients.
Package recovery contains the user-facing worktree promotion recovery flow shared by interactive clients.

Jump to

Keyboard shortcuts

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