worktree

package
v0.3.0-beta.35 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

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"
	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"
)

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")
	ErrOperationInProgress    = errors.New("worktree_operation_in_progress")
	ErrSessionActive          = errors.New("worktree_session_active")
	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")
	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")

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 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 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 {
	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 {
	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 ForgeFailure

type ForgeFailure struct {
	// 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 ForgeStatus

type ForgeStatus struct {
	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 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 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"`
}

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 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 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)

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
}

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) 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) 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) 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) 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) 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) 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 string,
	id string,
	refresh bool,
	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 {
	Insert(context.Context, Worktree) error
	Get(context.Context, string, string) (*Worktree, error)
	GetByPath(context.Context, string, string) (*Worktree, 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
	CompareAndSwapState(context.Context, string, string, State, State, 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)
	SaveForgeStatus(context.Context, string, string, ForgeStatus) error
	GetForgeStatus(context.Context, string, string) (*ForgeStatus, 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) (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
	BaseRef         string
	CreatedBranch   bool
	RunNamespace    string
	CreatedHead     string
	RunID           string
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

Jump to

Keyboard shortcuts

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