worktree

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BranchKeptNoBranch            = "no_branch"
	BranchKeptAbsent              = "branch_absent"
	BranchKeptCheckoutPresent     = "checkout_present"
	BranchKeptRootCheckout        = "root_checkout_branch"
	BranchKeptDefaultBranch       = "default_branch"
	BranchKeptRegistrationPresent = "registration_present"
	BranchKeptCheckedOutElsewhere = "checked_out_elsewhere"
	BranchKeptNotFullyMerged      = "not_fully_merged"
	BranchKeptDeleteFailed        = "delete_failed"
)

Branch outcome reasons explain why an opted-in local branch deletion kept the branch.

View Source
const (
	EventPreCreate           = "worktree.pre_create"
	EventPreRemove           = "worktree.pre_remove"
	EventCreated             = "worktree.created"
	EventAdopted             = "worktree.adopted"
	EventRemoved             = "worktree.removed"
	EventMissing             = "worktree.missing"
	EventDismissed           = "worktree.dismissed"
	EventCreationCanceled    = "worktree.creation_canceled"
	EventCreationFailed      = "worktree.creation_failed"
	EventSetupFailed         = "worktree.setup_failed"
	EventStatusRefreshed     = "worktree.status_refreshed"
	EventBranchReclaimed     = "worktree.branch_reclaimed"
	EventExitActionStarted   = "worktree.exit_action_started"
	EventExitActionStep      = "worktree.exit_action_step"
	EventExitHookOutput      = "worktree.exit_hook_output"
	EventExitActionCompleted = "worktree.exit_action_completed"
	EventExitActionFailed    = "worktree.exit_action_failed"
	EventExitActionCanceled  = "worktree.exit_action_canceled"
)
View Source
const (
	EventTeardownOutput = "worktree.teardown_output"
	EventTeardownFailed = "worktree.teardown_failed"
)

Variables

View Source
var (
	ErrGitUnavailable         = errors.New("worktree_git_unavailable")
	ErrGitVersionUnsupported  = errors.New("worktree_git_version_unsupported")
	ErrWorkspaceNotGitBacked  = errors.New("workspace_not_git_backed")
	ErrNameTaken              = errors.New("worktree_name_taken")
	ErrPathExists             = errors.New("worktree_path_exists")
	ErrBranchHeld             = errors.New("branch_held_by_worktree")
	ErrBranchCheckedOutAtRoot = errors.New("branch_checked_out_at_root")
	ErrBaseRefNotFound        = errors.New("base_ref_not_found")
	ErrRepoHasNoCommits       = errors.New("repo_has_no_commits")
	ErrNotFound               = errors.New("worktree_not_found")
	ErrNotReady               = errors.New("worktree_not_ready")
	ErrPending                = errors.New("worktree_pending")
	ErrMissing                = errors.New("worktree_missing")
	ErrRefInvalid             = errors.New("worktree_ref_invalid")
	ErrAdoptionMainCheckout   = errors.New("adoption_main_checkout")
	ErrAdoptionForeignRepo    = errors.New("adoption_foreign_repository")
	ErrAdoptionUnreadable     = errors.New("adoption_unreadable")
	ErrDiscoveredRegistered   = errors.New("worktree_registered")
	ErrDiscoveredChanged      = errors.New("worktree_discovered_changed")
	ErrOperationInProgress    = errors.New("worktree_operation_in_progress")
	ErrSessionActive          = errors.New("worktree_session_active")
	ErrSessionBound           = errors.New("worktree_session_bound")
	ErrStatusUnreadable       = errors.New("worktree_status_unreadable")
	ErrDirtyRequiresForce     = errors.New("worktree_dirty_requires_force")
	ErrUnpushedRequiresForce  = errors.New("worktree_unpushed_requires_force")
	ErrSafetyCheckFailed      = errors.New("worktree_safety_check_failed")
	ErrRemovalFailed          = errors.New("worktree_removal_failed")
	// ErrCheckoutOrphaned names a checkout directory whose .git link is gone
	// while Git still registers it, usually after an interrupted removal.
	ErrCheckoutOrphaned      = errors.New("worktree_checkout_orphaned")
	ErrPerRunMaterialization = errors.New("per_run_materialization_failed")
	ErrConfigInvalid         = errors.New("worktree_config_invalid")
	ErrDeniedByHook          = errors.New("worktree_denied_by_hook")
	ErrNotPending            = errors.New("worktree_not_pending")
	ErrForgeUnavailable      = errors.New("forge_unavailable")
	ErrForge                 = errors.New("forge_error")
	ErrExitActionInvalid     = errors.New("worktree_exit_action_invalid")
)
View Source
var ErrDeliveryInventoryUnavailable = errors.New("managed delivery journal inventory unavailable")
View Source
var ErrOriginLookupFailed = errors.New("worktree: origin lookup failed")

NormalizeRepoKey strips transport and credentials; identity never contains secrets. ErrOriginLookupFailed means git never answered, which says nothing about the repository's origin.

Functions

func ForgeFailureCause

func ForgeFailureCause(err error) string

func GenerateName

func GenerateName(taken func(string) bool) string

func NewForgeFailure

func NewForgeFailure(kind error, cause string, err error) error

func NewID

func NewID() (string, error)

NewID returns a fresh worktree id for CreateOptions.ID.

func NormalizeRepoKey

func NormalizeRepoKey(remote string) (string, error)

func ParseUntrackedStatusV2

func ParseUntrackedStatusV2(output []byte) ([]string, error)

ParseUntrackedStatusV2 returns the exact untracked additions from a porcelain-v2 snapshot. Ignored records are deliberately absent from the result.

func ReclamationEligible

func ReclamationEligible(branch, recordedNamespace string, createdBranch bool) bool

func RunBranchName

func RunBranchName(namespace, taskSlug, runID string) string

func RunWorktreeName

func RunWorktreeName(taskSlug, runID string) string

RunWorktreeName returns the readable per-run name without its branch namespace.

func SanitizeName

func SanitizeName(value string) string

Types

type AgentActivity

type AgentActivity string
const (
	AgentActivityIdle    AgentActivity = "idle"
	AgentActivityRunning AgentActivity = "running"
)

type BoundSessionGuard

type BoundSessionGuard interface {
	HasUnarchivedSession(context.Context, string, string) (bool, error)
}

BoundSessionGuard reports whether any unarchived session, live or stopped, still binds a worktree. A keep-branch removal requires it: the checkout it removes must not be one another listed session still uses.

type BranchOutcome

type BranchOutcome struct {
	Name    string
	Deleted bool
	Reason  string
	Detail  string
}

BranchOutcome reports an opt-in local branch deletion that followed a cleanup. Kept branches carry a stable Reason; Detail holds bounded Git diagnostics.

type CapabilityDiagnostic

type CapabilityDiagnostic struct {
	Available bool
	Code      string
	Message   string
}

type CapabilityGate

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

func NewCapabilityGate

func NewCapabilityGate(runner GitRunner) *CapabilityGate

func NewCapabilityGateWithLookPath

func NewCapabilityGateWithLookPath(runner GitRunner, lookPath func(string) (string, error)) *CapabilityGate

func (*CapabilityGate) Check

type CatalogEvent

type CatalogEvent struct {
	Kind        CatalogEventKind
	WorkspaceID string
	WorktreeID  string
	Error       string
}

type CatalogEventKind

type CatalogEventKind string
const (
	CatalogEventUpserted CatalogEventKind = "upserted"
	CatalogEventDeleted  CatalogEventKind = "deleted"
	CatalogEventFailed   CatalogEventKind = "failed"
)

type CreateOptions

type CreateOptions struct {
	// ID assigns the new row's id; empty generates one. A caller that must find the
	// worktree after a daemon restart, such as a session move, records it first.
	ID             string
	ProfileID      string
	Name           string
	Branch         string
	BaseRef        string
	ExistingBranch string
	Path           string
	Origin         Origin
	RunID          string
	RunNamespace   string
}

type DerivedNames

type DerivedNames struct {
	Branch    string
	Directory string
}

func DeriveNames

func DeriveNames(value string) DerivedNames

type DetailedListing

type DetailedListing struct {
	Worktrees  []Inspection
	Discovered []DiscoveredWorktree
	Repo       RepoState
}

type DiscoveredWorktree

type DiscoveredWorktree struct {
	Name        string
	Branch      string
	Path        string
	Detached    bool
	Stale       bool
	Selectable  bool
	Unavailable bool
	Reason      string
}

type EventSink

type EventSink interface {
	PublishWorktreeEvent(context.Context, LifecycleEvent) error
}

type ExitAction

type ExitAction string
const (
	ExitActionDeliver    ExitAction = "deliver"
	ExitActionCommit     ExitAction = "commit"
	ExitActionCommitPush ExitAction = "commit_push"
	ExitActionPush       ExitAction = "push"
	ExitActionOpenPR     ExitAction = "open_pr"
	ExitActionViewPR     ExitAction = "view_pr"
)

type ExitActionPlan

type ExitActionPlan struct {
	Action        ExitAction `json:"action"`
	Label         string     `json:"label"`
	Enabled       bool       `json:"enabled"`
	BlockedReason string     `json:"blocked_reason,omitempty"`
	Publish       bool       `json:"publish,omitzero"`
	URL           string     `json:"url,omitempty"`
	PRNumber      int        `json:"pr_number,omitzero"`
}

type ExitActionRequest

type ExitActionRequest struct {
	DeliveryID    string     `json:"delivery_id,omitempty"`
	ExpectedHead  string     `json:"expected_head,omitempty"`
	IncludePaths  []string   `json:"include_paths,omitempty"`
	ExpectedScope string     `json:"expected_scope,omitempty"`
	Action        ExitAction `json:"action"`
	Message       string     `json:"message,omitempty"`
	Title         string     `json:"title,omitempty"`
	Body          string     `json:"body,omitempty"`
	Draft         bool       `json:"draft,omitzero"`
	Base          string     `json:"base,omitempty"`
}

type ExitActionResult

type ExitActionResult struct {
	OperationID string           `json:"op_id"`
	Action      ExitAction       `json:"action"`
	Steps       []ExitStepResult `json:"steps"`
	CTA         *ExitCTA         `json:"cta,omitzero"`
}

type ExitCTA

type ExitCTA struct {
	Action ExitAction `json:"action"`
	Label  string     `json:"label"`
	URL    string     `json:"url,omitempty"`
}

type ExitCleanupEvidence

type ExitCleanupEvidence struct {
	ForgeState string `json:"forge_state,omitempty"`
	Stale      bool   `json:"stale,omitzero"`
	Safe       bool   `json:"safe"`
	Source     string `json:"source,omitempty"`
	Summary    string `json:"summary,omitempty"`
	Blocker    string `json:"blocker,omitempty"`
	Downgraded bool   `json:"downgraded,omitzero"`
}

type ExitCommitScope

type ExitCommitScope struct {
	IncludePaths       []string `json:"include_paths,omitempty"`
	Fingerprint        string   `json:"fingerprint,omitempty"`
	Complete           bool     `json:"complete,omitzero"`
	ChangedFiles       int      `json:"changed_files"`
	Insertions         int      `json:"insertions"`
	Deletions          int      `json:"deletions"`
	UntrackedFiles     []string `json:"untracked_files"`
	UntrackedTotal     int      `json:"untracked_total"`
	UntrackedTruncated bool     `json:"untracked_truncated,omitzero"`
}

type ExitEventPayload

type ExitEventPayload struct {
	CommitScope *ExitCommitScope  `json:"commit_scope,omitzero"`
	OperationID string            `json:"op_id"`
	Action      ExitAction        `json:"action"`
	Phases      []ExitPhase       `json:"phases,omitempty"`
	Phase       ExitPhase         `json:"phase,omitempty"`
	State       string            `json:"state,omitempty"`
	Result      *ExitActionResult `json:"result,omitzero"`
	Message     string            `json:"message,omitempty"`
	Cause       string            `json:"cause,omitempty"`
	Stream      string            `json:"stream,omitempty"`
	Chunk       string            `json:"chunk,omitempty"`
}

type ExitOperation

type ExitOperation struct {
	RunID       string
	ID          string
	ProfileID   string
	WorkspaceID string
	WorktreeID  string
	Action      string
	State       string
	StartedAt   time.Time
	FinishedAt  *time.Time
}

type ExitPRPrefill

type ExitPRPrefill struct {
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
}

type ExitPhase

type ExitPhase string
const (
	ExitPhaseCommit ExitPhase = "commit"
	ExitPhasePush   ExitPhase = "push"
	ExitPhasePR     ExitPhase = "pr"
)

type ExitPlan

type ExitPlan struct {
	WorktreeID       string              `json:"worktree_id"`
	Primary          ExitAction          `json:"primary,omitempty"`
	Actions          []ExitActionPlan    `json:"actions"`
	GlobalPauseCause string              `json:"global_pause_cause,omitempty"`
	CommitScope      ExitCommitScope     `json:"commit_scope"`
	BrowserURL       string              `json:"browser_url,omitempty"`
	Forge            *ForgeCapabilities  `json:"forge,omitzero"`
	ForgeStatus      *ForgeStatus        `json:"forge_status,omitzero"`
	PRPrefill        *ExitPRPrefill      `json:"pr_prefill,omitzero"`
	Cleanup          ExitCleanupEvidence `json:"cleanup"`
	Base             string              `json:"base,omitempty"`
	RemoteURLs       []string            `json:"remote_urls,omitempty"`
}

type ExitStepResult

type ExitStepResult struct {
	IncludePaths []string  `json:"include_paths,omitempty"`
	Phase        ExitPhase `json:"phase"`
	State        string    `json:"state"`
	Reason       string    `json:"reason,omitempty"`
	Output       string    `json:"output,omitempty"`
	SHA          string    `json:"sha,omitempty"`
	Upstream     string    `json:"upstream,omitempty"`
	PRStatus     string    `json:"pr_status,omitempty"`
	PRNumber     int       `json:"pr_number,omitzero"`
	URL          string    `json:"url,omitempty"`
}

type ExitTerminalEventSink

type ExitTerminalEventSink interface {
	FinishExitOperationWithEvent(
		context.Context,
		string,
		string,
		string,
		string,
		time.Time,
		LifecycleEvent,
	) (bool, error)
}

ExitTerminalEventSink commits an exit operation's terminal state and replay event together. The production store implements this boundary transactionally.

type ForgeCapabilities

type ForgeCapabilities struct {
	Provider           string
	Winner             string
	RequestNoun        string
	OpenActionLabel    string
	ViewActionLabel    string
	SupportsDraft      bool
	CompareURLTemplate string
	CredentialSource   string
	DefaultBranch      string
	TemplatePaths      []string
}

type ForgeChecks

type ForgeChecks struct {
	State                   string
	Passed, Failed, Pending int
	FailedNames             []string
}

type ForgeFailure

type ForgeFailure struct {
	RetryAfter *time.Time
	// contains filtered or unexported fields
}

func (*ForgeFailure) Error

func (e *ForgeFailure) Error() string

func (*ForgeFailure) Unwrap

func (e *ForgeFailure) Unwrap() []error

type ForgePRRequest

type ForgePRRequest struct {
	WorkspaceID string
	WorktreeID  string
	RemoteURLs  []string
	Head        string
	HeadSHA     string
	Base        string
	Title       string
	Body        string
	Draft       bool
}

type ForgePRResult

type ForgePRResult struct {
	Status string
	Number int
	URL    string
}

type ForgeProvider

type ForgeProvider interface {
	Capabilities(context.Context, []string) (*ForgeCapabilities, error)
	Status(context.Context, ForgeStatusRequest) (*ForgeStatus, error)
	CreatePR(context.Context, ForgePRRequest) (*ForgePRResult, error)
}

type ForgeReview

type ForgeReview struct {
	ID, Author, State, Commit string
	IsBot                     bool
	SubmittedAt               *time.Time
}

ForgeReview is one submitted review; forge text in it is untrusted.

type ForgeReviewThread

type ForgeReviewThread struct{ ID, Commit string }

ForgeReviewThread is one unresolved thread and the commit it was opened on.

type ForgeReviews

type ForgeReviews struct {
	Items             []ForgeReview
	Threads           []ForgeReviewThread
	UnresolvedThreads int
	Truncated         bool
}

ForgeReviews is optional provider review activity; it is never cached, so only a live Refresh carries it.

type ForgeStatus

type ForgeStatus struct {
	Title   string
	Checks  *ForgeChecks
	Reviews *ForgeReviews
	// ReviewsUnavailable reports a failed review read, as opposed to a provider without reviews.
	ReviewsUnavailable bool
	ReviewDecision     string
	Mergeable          string
	UpdatedAt          *time.Time
	Selection          string
	WorktreeID         string
	Provider           string
	PRNumber           *int
	PRState            *string
	PRURL              string
	Head               string
	Base               string
	HeadSHA            string
	Draft              *bool
	Merged             *bool
	FetchedAt          *time.Time
}

func (ForgeStatus) IsStale

func (s ForgeStatus) IsStale(now time.Time, ttl time.Duration) bool

IsStale reports whether the cached forge snapshot is older than the consumer's freshness window. It never performs network I/O.

type ForgeStatusRequest

type ForgeStatusRequest struct {
	WorkspaceID string
	WorktreeID  string
	RemoteURLs  []string
	Branch      string
	Base        string
	HeadSHA     string
}

type GitIndexRunner

type GitIndexRunner interface {
	RunWithIndex(context.Context, string, string, ...string) ([]byte, []byte, error)
}

type GitInputRunner

type GitInputRunner interface {
	RunWithInput(context.Context, string, string, ...string) ([]byte, []byte, error)
}

type GitOutput

type GitOutput struct {
	Stream GitOutputStream
	Chunk  []byte
}

type GitOutputHandler

type GitOutputHandler func(GitOutput)

type GitOutputStream

type GitOutputStream string
const (
	GitOutputStdout GitOutputStream = "stdout"
	GitOutputStderr GitOutputStream = "stderr"
)

type GitRunner

type GitRunner interface {
	Run(context.Context, string, ...string) ([]byte, []byte, error)
}

type GitStatus

type GitStatus struct {
	Branch      string
	Upstream    string
	HeadSHA     string
	Detached    bool
	DirtyFiles  int
	HasUpstream bool
	Ahead       *int
	Behind      *int
}

func ParseStatusV2

func ParseStatusV2(output []byte) (GitStatus, error)

type GitTimeoutRunner

type GitTimeoutRunner interface {
	RunWithTimeout(context.Context, string, time.Duration, ...string) ([]byte, []byte, error)
}

GitTimeoutRunner runs one command under its own budget instead of the runner default, for operations whose duration scales with the checkout.

type GitWorktree

type GitWorktree struct {
	Path           string
	HeadSHA        string
	Branch         string
	Main           bool
	Detached       bool
	Bare           bool
	Locked         bool
	LockReason     string
	Prunable       bool
	PrunableReason string
}

func ParseWorktreeList

func ParseWorktreeList(output []byte) ([]GitWorktree, error)

type HookDispatcher

type HookDispatcher interface {
	DispatchWorktreeHook(context.Context, HookRequest) (HookVerdict, error)
}

type HookPreRemovePayload

type HookPreRemovePayload struct {
	Worktree   HookWorktree `json:"worktree"`
	Force      bool         `json:"force"`
	Risk       RemovalRisk  `json:"risk"`
	Discovered bool         `json:"discovered,omitempty"`
}

type HookRequest

type HookRequest struct {
	Event   string
	Payload any
}

type HookVerdict

type HookVerdict struct {
	Denied   bool
	HookName string
	Reason   string
}

type HookWorktree

type HookWorktree struct {
	ProfileID     string `json:"profile_id,omitempty"`
	WorktreeID    string `json:"worktree_id"`
	WorkspaceID   string `json:"workspace_id"`
	WorkspaceRoot string `json:"workspace_root,omitempty"`
	Name          string `json:"name"`
	Branch        string `json:"branch"`
	Path          string `json:"path"`
	Origin        Origin `json:"origin"`
	RunID         string `json:"run_id,omitempty"`
}

type Inspection

type Inspection struct {
	Worktree      Worktree
	Status        *Status
	ForgeStatus   *ForgeStatus
	Repo          RepoState
	AgentActivity AgentActivity
}

type LifecycleEvent

type LifecycleEvent struct {
	Name        string
	ProfileID   string
	WorkspaceID string
	WorktreeID  string
	RunID       string
	Payload     json.RawMessage
}

type Listing

type Listing struct {
	Worktrees  []Worktree
	Discovered []DiscoveredWorktree
	Repo       RepoState
}

type ManagedDeliverySessions

type ManagedDeliverySessions interface {
	AcquireDeliveryFence(context.Context, string, string, string) (func(), error)
	StopDeliverySession(context.Context, string) error
}

ManagedDeliverySessions is implemented by the runtime owner. The returned fence blocks new/resumed sessions until all Git and forge effects settle.

type Numstat

type Numstat struct {
	Files      map[string]struct{}
	Insertions int
	Deletions  int
}

func MergeNumstat

func MergeNumstat(values ...Numstat) Numstat

func ParseNumstat

func ParseNumstat(output []byte) (Numstat, error)

type Option

type Option func(*Service)

func WithCapabilityGate

func WithCapabilityGate(gate *CapabilityGate) Option

func WithClock

func WithClock(now func() time.Time) Option

func WithConfig

func WithConfig(value config.WorktreesConfig, resolvedRoot string) Option

func WithEvents

func WithEvents(sink EventSink) Option

func WithForge

func WithForge(provider ForgeProvider) Option

func WithHooks

func WithHooks(dispatcher HookDispatcher) Option

func WithIDGenerator

func WithIDGenerator(generator func(string) (string, error)) Option

func WithLogger

func WithLogger(logger *slog.Logger) Option

func WithManagedDeliverySessions

func WithManagedDeliverySessions(guard ManagedDeliverySessions) Option

func WithPullRequests

func WithPullRequests(service *PullRequestService) Option

func WithRepositoryLocks

func WithRepositoryLocks(locks *RepositoryLocks) Option

func WithSessionGuard

func WithSessionGuard(guard SessionGuard) Option

func WithWorkspaceResolver

func WithWorkspaceResolver(resolver WorkspaceResolver) Option

type Origin

type Origin string
const (
	OriginManual  Origin = "manual"
	OriginPerRun  Origin = "per_run"
	OriginAdopted Origin = "adopted"
)

type ParseError

type ParseError struct {
	Format string
	Record string
}

func (*ParseError) Error

func (e *ParseError) Error() string

type PendingPhase

type PendingPhase string
const (
	PhaseNone     PendingPhase = ""
	PhaseBranch   PendingPhase = "branch"
	PhaseCheckout PendingPhase = "checkout"
	PhaseCopy     PendingPhase = "copy"
	PhaseSetup    PendingPhase = "setup"
)

type PendingUpdate

type PendingUpdate struct {
	Phase         PendingPhase
	Branch        string
	GitDir        string
	BaseRef       string
	CreatedBranch bool
	RunNamespace  string
	CreatedHead   string
}

type PullRequestEntry

type PullRequestEntry struct {
	Key                      PullRequestKey
	Facts                    *ForgeStatus
	LookupState, LookupCause string
	AttemptAt, RetryAfter    *time.Time
	FailureCount             int
	Stale                    bool
}

type PullRequestKey

type PullRequestKey struct{ WorkspaceID, RepoKey, Branch string }

type PullRequestService

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

PullRequestService is the sole writer of canonical display observations. Exact delivery evidence never enters this cache.

func NewPullRequestService

func NewPullRequestService(
	ctx context.Context,
	store PullRequestStore,
	forge ForgeProvider,
	runner GitRunner,
	changed func(string),
) *PullRequestService

func (*PullRequestService) Close

func (s *PullRequestService) Close()

func (*PullRequestService) DefaultBranchNames

func (s *PullRequestService) DefaultBranchNames(ctx context.Context, root string) []string

DefaultBranchNames shares the cached local origin HEAD with display filtering.

func (*PullRequestService) ForgetAutomatic

func (s *PullRequestService) ForgetAutomatic(key PullRequestKey)

ForgetAutomatic drops a removed worktree's absence streak and queued display refresh. Explicit readers may still need delivery evidence for the same branch.

func (*PullRequestService) IsDefaultBranch

func (s *PullRequestService) IsDefaultBranch(ctx context.Context, root, branch string) bool

IsDefaultBranch uses the local origin HEAD; absent metadata falls back to the conventional names. It never contacts the remote and caches each root briefly.

func (*PullRequestService) Peek

Peek returns cached observations without contacting the forge, for rows whose pull request no longer changes what the user can do, such as removed worktrees.

func (*PullRequestService) Read

Read returns cached observations and schedules a background refresh for each stale one.

func (*PullRequestService) Refresh

func (*PullRequestService) RefreshDue

RefreshDue is Refresh for a background watcher: while a recorded failure's RetryAfter still holds it returns that cached entry without contacting the forge.

func (*PullRequestService) RepoKey

func (s *PullRequestService) RepoKey(ctx context.Context, root string) (string, error)

func (*PullRequestService) RequestRefresh

func (s *PullRequestService) RequestRefresh(key PullRequestKey)

type PullRequestStore

type PullRequestStore interface {
	ReadPullRequests(context.Context, []PullRequestKey) (map[PullRequestKey]PullRequestEntry, error)
	SavePullRequest(context.Context, PullRequestEntry) error
}

type RealGitRunner

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

func NewRealGitRunner

func NewRealGitRunner(timeout time.Duration) (*RealGitRunner, error)

func (*RealGitRunner) Run

func (r *RealGitRunner) Run(ctx context.Context, dir string, args ...string) ([]byte, []byte, error)

func (*RealGitRunner) RunStreaming

func (r *RealGitRunner) RunStreaming(
	ctx context.Context,
	dir string,
	onOutput GitOutputHandler,
	args ...string,
) ([]byte, []byte, error)

func (*RealGitRunner) RunWithIndex

func (r *RealGitRunner) RunWithIndex(ctx context.Context, dir, index string, args ...string) ([]byte, []byte, error)

func (*RealGitRunner) RunWithInput

func (r *RealGitRunner) RunWithInput(ctx context.Context, dir, input string, args ...string) ([]byte, []byte, error)

func (*RealGitRunner) RunWithTimeout

func (r *RealGitRunner) RunWithTimeout(
	ctx context.Context,
	dir string,
	timeout time.Duration,
	args ...string,
) ([]byte, []byte, error)

type ReclaimOutcome

type ReclaimOutcome struct {
	Eligible bool
	Deleted  bool
	Reason   string
}

type RefusalError

type RefusalError struct {
	Cause  error
	Detail string
}

func (*RefusalError) Error

func (e *RefusalError) Error() string

func (*RefusalError) Unwrap

func (e *RefusalError) Unwrap() error

type RemovalRefusal

type RemovalRefusal struct {
	Code      string
	Risk      RemovalRisk
	Downgrade bool
}

type RemovalRisk

type RemovalRisk struct {
	ChangedFiles    int
	Insertions      int
	Deletions       int
	UnpushedCommits int
	ExistsOnRemote  bool
	// LeftoverFiles counts files left in an orphaned checkout. Git can no
	// longer tell which of them hold changes, so all of them are at risk.
	LeftoverFiles int
}

type RemoveDiscoveredOptions

type RemoveDiscoveredOptions struct {
	// Force acknowledges dirty or unpushed loss on a live checkout.
	Force bool
	// ExpectStale freezes a confirmation that only clears a stale Git entry:
	// a checkout that is live again is refused instead of removed.
	ExpectStale bool
}

RemoveDiscoveredOptions carries the caller's acknowledgements for one target.

type RepoState

type RepoState struct {
	GitBacked    bool
	GitAvailable bool
	Diagnostic   string
}

type RepositoryLocks

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

func NewRepositoryLocks

func NewRepositoryLocks(maxWaiters int) *RepositoryLocks

func (*RepositoryLocks) Acquire

func (l *RepositoryLocks) Acquire(ctx context.Context, commonDir string) (func(), error)

type RunWorktreeRequest

type RunWorktreeRequest struct {
	BaseRef   string
	ProfileID string
	TaskSlug  string
	RunID     string
}

type Service

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

func NewService

func NewService(store Store, runner GitRunner, opts ...Option) *Service

func (*Service) AcquireBindingUsage

func (s *Service) AcquireBindingUsage(ctx context.Context, workspaceID, ref string) (*Worktree, func(), error)

AcquireBindingUsage excludes checkout mutation during a session binding change. Unlike runtime usage, this also permits leaving a missing checkout.

func (*Service) AcquireUsage

func (s *Service) AcquireUsage(
	ctx context.Context,
	workspaceID string,
	ref string,
) (*Worktree, func(), error)

AcquireUsage keeps a ready worktree available until the returned release function runs.

func (*Service) Adopt

func (s *Service) Adopt(ctx context.Context, profileID, workspaceID, candidatePath string) (*Worktree, error)

Adopt validates a discovered checkout under the repository lock before registering it for this profile or restoring its existing missing record.

func (*Service) CancelCreate

func (s *Service) CancelCreate(ctx context.Context, workspaceID, ref string) error

func (*Service) CancelExitAction

func (s *Service) CancelExitAction(ctx context.Context, workspaceID, ref, opID string) error

func (*Service) Capability

func (s *Service) Capability(ctx context.Context) (CapabilityDiagnostic, error)

Capability reports whether the Git dependency required by worktree mutations is ready.

func (*Service) Close

func (s *Service) Close()

func (*Service) CommitsAheadOf

func (s *Service) CommitsAheadOf(ctx context.Context, workspaceID, worktreeID, base string) (int, error)

CommitsAheadOf fails closed: an unreadable base must never authorize cleanup.

func (*Service) Create

func (s *Service) Create(ctx context.Context, workspaceID string, options CreateOptions) (*Worktree, error)

func (*Service) CreateAccepted

func (s *Service) CreateAccepted(
	ctx context.Context,
	workspaceID string,
	options CreateOptions,
) (*Worktree, error)

CreateAccepted durably inserts a pending worktree and continues materialization after the request ends. Callers observe phases through the catalog stream and canonical lifecycle events.

func (*Service) CreateReady

func (s *Service) CreateReady(
	ctx context.Context,
	workspaceID string,
	options CreateOptions,
) (*Worktree, error)

CreateReady inserts a visible pending worktree, waits for materialization, and returns only after the worktree is ready for session binding.

func (*Service) DeleteLocalBranch

func (s *Service) DeleteLocalBranch(
	ctx context.Context,
	workspaceID string,
	id string,
	force bool,
) (BranchOutcome, error)

DeleteLocalBranch deletes the recorded local branch of a removed or dismissed worktree. It refuses the root checkout's HEAD and default branches, never touches a path that reappeared, and uses Git's merged-only delete unless force is set. Refusals are outcomes; errors are reserved for unreadable state, and errors after the record is read still return the outcome with its branch name.

func (*Service) Dismiss

func (s *Service) Dismiss(ctx context.Context, workspaceID, id string) error

Dismiss hides a missing, removed, or failed record while retaining its history. It excludes active use, fences concurrent state changes, and is repeat-safe; no filesystem or Git operation runs, even if the saved path has reappeared.

func (*Service) ExitPlan

func (s *Service) ExitPlan(ctx context.Context, workspaceID, id string) (*ExitPlan, error)

func (*Service) ExitPlanForPaths

func (s *Service) ExitPlanForPaths(ctx context.Context, workspaceID, ref string, paths []string) (*ExitPlan, error)

func (*Service) Get

func (s *Service) Get(ctx context.Context, workspaceID, ref string) (*Worktree, error)

func (*Service) Inspect

func (s *Service) Inspect(ctx context.Context, workspaceID, ref string) (*Inspection, error)

Inspect returns durable registry and cached derived state. It probes only repository capability; status, discovery, and forge reads remain cached.

func (*Service) List

func (s *Service) List(ctx context.Context, workspaceID string, refresh bool) (*Listing, error)

List combines registered and discovered checkouts, reconciling vanished ready rows without overwriting concurrent lifecycle changes or guessing on stat errors.

func (*Service) ListAggregate

func (s *Service) ListAggregate(
	ctx context.Context,
	scope store.ReadScope,
	allowedWorkspaces map[string]bool,
) (*DetailedListing, error)

ListAggregate reads authorized stored state without Git discovery or status refresh.

func (*Service) ListDetails

func (s *Service) ListDetails(
	ctx context.Context,
	workspaceID string,
	refresh bool,
) (*DetailedListing, error)

ListDetails returns the registry/discovery merge plus cached status, forge, and live activity. Git status is refreshed only when refresh is explicit.

func (*Service) MaterializeForRun

func (s *Service) MaterializeForRun(
	ctx context.Context,
	workspaceID string,
	request RunWorktreeRequest,
) (*Worktree, error)

func (*Service) ObserveForgeStatus

func (s *Service) ObserveForgeStatus(ctx context.Context, workspaceID, id string) (*ForgeStatus, error)

ObserveForgeStatus reads fresh delivery evidence without consulting the display cache.

func (*Service) PrepareExitPlan

func (s *Service) PrepareExitPlan(ctx context.Context, workspaceID, id string) (*ExitPlan, error)

PrepareExitPlan resolves provider capabilities only for an explicit delivery gesture.

func (*Service) Reconfigure

func (s *Service) Reconfigure(value config.WorktreesConfig, resolvedRoot string)

Reconfigure applies global worktree settings to future operations. Existing registry rows retain their persisted paths and lifecycle state.

func (*Service) RecoverCreations

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

func (*Service) RecoverManagedDeliveries

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

RecoverManagedDeliveries repairs receipts without replaying unknown or terminal intents.

func (*Service) Remove

func (s *Service) Remove(
	ctx context.Context,
	workspaceID string,
	id string,
	force bool,
) (*RemovalRefusal, error)

func (*Service) RemoveDiscovered

func (s *Service) RemoveDiscovered(
	ctx context.Context,
	workspaceID string,
	path string,
	options RemoveDiscoveredOptions,
) (*RemovalRefusal, error)

RemoveDiscovered deletes a linked worktree that Git lists but no registry row owns. Stale entries only lose their admin metadata. Live checkouts keep the dirty and unpushed refusals of registered removal, and branches stay untouched.

func (*Service) RemoveKeepingBranch

func (s *Service) RemoveKeepingBranch(ctx context.Context, workspaceID, id string) (*RemovalRefusal, error)

RemoveKeepingBranch removes a clean checkout and keeps its branch: unpushed commits stay on the branch, so they do not block the removal, while uncommitted files still refuse it, before and after removal hooks run. Moving a session to another profile checks the same branch out again elsewhere.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, workspaceID, ref string) (*Worktree, error)

Resolve returns the canonical registry record for an ID-or-name reference without probing repository capability or derived status caches.

func (*Service) ResolveCommit

func (s *Service) ResolveCommit(ctx context.Context, path, ref string) (string, error)

ResolveCommit pins a ref using the service's configured Git runner and repository lock.

func (*Service) RollbackRunMaterialization

func (s *Service) RollbackRunMaterialization(
	ctx context.Context,
	workspaceID string,
	worktreeID string,
	runID string,
) error

RollbackRunMaterialization removes the exact per-run worktree produced for a session that could not be bound under its active task-run lease.

func (*Service) RunExitAction

func (s *Service) RunExitAction(
	ctx context.Context,
	workspaceID string,
	id string,
	request ExitActionRequest,
) (string, error)

func (*Service) Status

func (s *Service) Status(ctx context.Context, workspaceID, id string, refresh bool) (*Status, error)

func (*Service) StatusDetails

func (s *Service) StatusDetails(
	ctx context.Context,
	workspaceID, id string,
	refresh, refreshForge bool,
) (*StatusDetails, error)

func (*Service) SubmitManagedDelivery

func (s *Service) SubmitManagedDelivery(
	ctx context.Context,
	workspaceID, ref, sessionID string,
	request ExitActionRequest,
) (string, error)

SubmitManagedDelivery accepts an idempotent daemon-owned handoff. sessionID must come from validated transport identity, never from the request body.

func (*Service) SubscribeWorktreeCatalogEvents

func (s *Service) SubscribeWorktreeCatalogEvents(
	ctx context.Context,
) (<-chan CatalogEvent, func(), error)

func (*Service) VerifyReviewCandidate

func (s *Service) VerifyReviewCandidate(
	ctx context.Context,
	workspaceID, worktreeID string,
	paths []string,
	fingerprint string,
) (bool, error)

type SessionGuard

type SessionGuard interface {
	HasActiveSession(context.Context, string, string) (bool, error)
}

type SetupState

type SetupState string
const (
	SetupNone   SetupState = "none"
	SetupOK     SetupState = "ok"
	SetupFailed SetupState = "failed"
)

type State

type State string
const (
	StatePending   State = "pending"
	StateReady     State = "ready"
	StateFailed    State = "failed"
	StateRemoving  State = "removing"
	StateMissing   State = "missing"
	StateRemoved   State = "removed"
	StateDismissed State = "dismissed"
)

type Status

type Status struct {
	WorktreeID  string
	Branch      *string
	Detached    *bool
	HeadSHA     *string
	DirtyFiles  *int
	Insertions  *int
	Deletions   *int
	HasUpstream *bool
	Ahead       *int
	AheadOfBase *int
	Behind      *int
	ReadError   string
	RefreshedAt *time.Time
}

func (Status) IsStale

func (s Status) IsStale(now time.Time, ttl time.Duration) bool

IsStale reports whether the cached Git snapshot is older than the consumer's freshness window. A missing timestamp is always unknown and therefore stale.

type StatusDetails

type StatusDetails struct {
	WorktreeID  string
	Status      *Status
	ForgeStatus *ForgeStatus
}

type Store

type Store interface {
	RemoveMissing(context.Context, string, string, time.Time) (bool, error)
	Insert(context.Context, Worktree) error
	Get(context.Context, string, string) (*Worktree, error)
	GetByPath(context.Context, string, string) (*Worktree, error)
	// PathOwnedByAnyWorkspace reports whether a live record in any workspace owns the path.
	PathOwnedByAnyWorkspace(context.Context, string) (bool, error)
	List(context.Context, string) ([]Worktree, error)
	ListRecoverable(context.Context) ([]Worktree, error)
	DeletePending(context.Context, string, string) error
	DeleteRunMaterialization(context.Context, string, string, string) error
	UpdatePending(context.Context, string, string, PendingUpdate) error
	CompleteCreate(context.Context, string, string, SetupState, string, time.Time) error
	// FailCreate moves a pending row to failed and records the creation cause
	// and, when its rollback is incomplete, the rollback error.
	FailCreate(context.Context, string, string, string, string, time.Time) error
	// CompleteFailedCreateRollback clears a failed row's incomplete rollback.
	CompleteFailedCreateRollback(context.Context, string, string, time.Time) error
	CompareAndSwapState(context.Context, string, string, State, State, time.Time) (bool, error)
	// FenceRemoval moves a ready row to removing with its removal mode, unless an
	// exit action is running on it; it reports whether the fence was taken.
	FenceRemoval(ctx context.Context, workspaceID, id string, keepBranch bool, updatedAt time.Time) (bool, error)
	SetState(context.Context, string, string, State, time.Time) error
	SaveStatus(context.Context, string, string, Status) error
	GetStatus(context.Context, string, string) (*Status, error)
	InsertExitOperation(context.Context, ExitOperation) error
	FinishExitOperation(context.Context, string, string, string, string, time.Time) (bool, error)
	ListRunningExitOperations(context.Context) ([]ExitOperation, error)
	FailRunningExitOperations(context.Context, time.Time) error
}

Store owns workspace-predicated persistence for the worktree domain.

type StreamingGitRunner

type StreamingGitRunner interface {
	RunStreaming(context.Context, string, GitOutputHandler, ...string) ([]byte, []byte, error)
}

type Workspace

type Workspace struct {
	ID            string
	Name          string
	Root          string
	Worktrees     config.WorktreesConfig
	WorktreesRoot string
}

type WorkspaceResolver

type WorkspaceResolver interface {
	ResolveWorktreeWorkspace(context.Context, string, string) (Workspace, error)
	ListWorktreeWorkspaces(context.Context) ([]Workspace, error)
}

type Worktree

type Worktree struct {
	ID              string
	ProfileID       string
	ProfileName     string
	ProfileColor    string
	ProfileIcon     string
	ProfileEmoji    string
	ProfileArchived bool
	WorkspaceID     string
	Name            string
	Branch          string
	Path            string
	GitDir          string
	State           State
	PendingPhase    PendingPhase
	Origin          Origin
	SetupState      SetupState
	SetupError      string
	// CreateError keeps the redacted cause of a failed creation until dismissal.
	CreateError string
	// CreateRollbackError is non-empty while that creation's rollback is
	// incomplete; boot reconciliation retries it until it clears.
	CreateRollbackError string
	BaseRef             string
	CreatedBranch       bool
	RunNamespace        string
	CreatedHead         string
	RunID               string
	// RemovalKeepsBranch marks a removing row whose removal keeps its branch, so an
	// interrupted removal finishes in the same mode after a daemon restart.
	RemovalKeepsBranch bool
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

func (Worktree) CreateFailure

func (w Worktree) CreateFailure() string

CreateFailure reports a failed creation's cause and, while it is incomplete, its rollback error.

Jump to

Keyboard shortcuts

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