workspaceops

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package workspaceops holds the parts of workspace creation that belong to no particular view.

It exists so the project Workspaces plugin and, later, the global browser can invoke one implementation of the same operation rather than each owning a copy. The rule that keeps it honest is the same one workspacelist follows: nothing here imports a plugin, the app, or a view. It receives explicit arguments and returns explicit results.

This first file is the path-containment and durable-write layer. It moved first because it is the code most worth having in one reviewable place: every function here exists to stop a symlink, a racing rename, or a partially written file from turning workspace setup into a write outside the worktree it was aimed at.

Index

Constants

View Source
const WorktreeSessionPrefix = "sidecar-ws-"

WorktreeSessionPrefix names the tmux sessions Sidecar runs a worktree's agent in.

Variables

View Source
var DefaultEnvOverrides = map[string]string{
	"GOWORK": "off", "GOFLAGS": "", "NODE_OPTIONS": "", "NODE_PATH": "", "PYTHONPATH": "", "VIRTUAL_ENV": "",
}
View Source
var ErrWorktreeDirty = errors.New("worktree is dirty (uncommitted or untracked changes)")

ErrWorktreeDirty is returned when a removal that was not asked to force finds uncommitted or untracked work in the worktree.

Functions

func BranchOID

func BranchOID(ctx context.Context, repoPath, branch string) string

BranchOID resolves a local branch's tip, so an interactive caller can pin the identity it is about to delete before it starts removing things. An unresolvable branch yields an empty OID, which means "nothing to pin" to DeleteLocalBranch rather than a failure.

func BuildEnvOverrides

func BuildEnvOverrides(mainRepoPath string) map[string]string

func CanonicalWorktreePath

func CanonicalWorktreePath(path string) string

CanonicalWorktreePath resolves a worktree path the way git reports it, so two spellings of the same directory compare equal.

func ContainedRegularFile

func ContainedRegularFile(root, rel string) (string, error)

ContainedRegularFile resolves rel under root and returns its real path, refusing anything that is not a regular file reached without traversing a symlink.

func CopyOpenFile

func CopyOpenFile(source *os.File, dst string) error

CopyOpenFile copies an already-opened source to dst, preserving its mode and flushing before it reports success.

func DefaultBranch

func DefaultBranch(ctx context.Context, workDir string) string

DefaultBranch detects a repository's default branch: origin's HEAD when it is known, then the conventional names, then "main". Answers are cached per working directory.

func DefaultBranchObserved

func DefaultBranchObserved(ctx context.Context, workDir string, onSpawn func()) string

DefaultBranchObserved is DefaultBranch with a hook called immediately before each git process it spawns. Hosts that count subprocesses (the startup trace) pass their recorder here so detection is not under-reported as one spawn.

func DeleteCreatedWorktree

func DeleteCreatedWorktree(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error

DeleteCreatedWorktree removes only the exact clean identity returned by the creation core, then deletes its local branch. It has no force fallback.

It runs the shared removal path (DeleteWorktree) rather than its own git commands, which is what stops a rollback from orphaning the session a host may already have launched into the new worktree: the kill lives inside that path, ahead of the removal, for every caller.

func DeleteLocalBranch

func DeleteLocalBranch(ctx context.Context, req BranchDeletion) error

DeleteLocalBranch deletes a local branch, refusing the repository's default branch outright and refusing a branch that has moved since the caller resolved it.

func DeleteManagedShell

func DeleteManagedShell(projectRoot, sessionName, namespace string) error

DeleteManagedShell removes the durable identity and then closes the exact tmux session. If tmux has already exited, the requested state is achieved.

func DeleteRemoteBranch

func DeleteRemoteBranch(ctx context.Context, req BranchDeletion) error

DeleteRemoteBranch deletes the remote's copy of a branch. A branch the remote has already dropped (GitHub's auto-delete, for instance) is not an error. With ExpectedOID set the push carries a lease, so a branch someone else has advanced is left alone.

func DeleteWorktree

func DeleteWorktree(ctx context.Context, req WorktreeRemoval) error

DeleteWorktree closes the worktree's tmux session and then removes the worktree at Path. A worktree whose directory has already gone is pruned from git's metadata instead.

This is the only worktree removal in the tree. Interactive deletion on both surfaces, post-merge cleanup, and creation rollback all reach it, so there is one place that decides what "delete a worktree" does to git and to the tmux session, and one place to read to find out.

The session teardown lives here, ahead of the git work, because the ordering is the point: removing the directory first leaves whatever is running in the session — an agent, most of the time — alive in a working directory that no longer exists (td-a66836, td-3df472). Putting it on the shared path is what stops one caller having it and another not; no caller can opt out or spell the session name differently, because none of them supplies it.

A removal that has not been forced validates first and kills second, so a refusal costs nobody their session; the kill still precedes the destructive command, which is the guarantee that matters.

Interaction with internal/shellliveness: none, deliberately. That subsystem reaps *shells* — sidecar-sh-* sessions recorded in shells.json — and both of its bindings skip anything that is not a KindShell workspace. A worktree session is in neither the manifest nor a liveness tracker, so a kill here cannot be mistaken for a suspicious disappearance and cannot race the reaper.

func EnsureRealDirectoryPath

func EnsureRealDirectoryPath(root, target string, requireExisting bool) error

EnsureRealDirectoryPath rejects symlink traversal for every existing path component below root. Missing components are allowed only when requested; callers re-run this after creation to narrow the remaining TOCTOU window.

func ForgetManagedShell

func ForgetManagedShell(projectRoot, sessionName, namespace string, observedAt time.Time) error

ForgetManagedShell drops the durable identity of a shell whose tmux session is already gone. It is DeleteManagedShell without the kill: there is nothing left to close, and issuing kill-session anyway would be one more spawn and one more way to hit the wrong target. Callers must have positive evidence the session is gone (see internal/shellliveness); this operation does not re-check that, because the surfaces that call it already asked tmux.

observedAt is the CreatedAt the caller saw when it decided. The removal is refused with shellstate.ErrShellChanged if the entry on disk is newer, so a shell created under the same tmux name while the caller was confirming keeps its identity. The comparison happens under the manifest's exclusive lock, which is the same lock the creating write takes. Pass the zero time to remove unconditionally.

func ForgetShellsInWorktree

func ForgetShellsInWorktree(projectRoot, worktreePath string) error

ForgetShellsInWorktree closes every managed shell of projectRoot that is rooted in worktreePath: the manifest row goes, and so does the tmux session.

Killing the sessions is the point, not a side effect. A shell whose working directory has been deleted is orphaned in exactly the way td-a66836 fixed for the worktree's own session — a shell (usually an agent) left running in a directory that no longer exists, invisible in the UI because its workspace is gone, and unreachable except by knowing the tmux name. Removing only the manifest row would make that *worse*: the row is the last thing that records the session exists at all. So this goes through DeleteManagedShell, which removes the durable identity first and then closes the session, and which is the same operation the Workspaces surfaces already use to close a shell by hand.

Errors are collected rather than fatal: one shell that will not close must not leave the other shells' rows behind.

It is reached through DeleteWorktree rather than called beside it: the forgetting is part of removing a worktree, not a step a caller has to remember, which is what stops one surface growing it and another not.

func GenerateSingleEnvCommand

func GenerateSingleEnvCommand(overrides map[string]string) string

func IsDefaultBranch

func IsDefaultBranch(ctx context.Context, workDir, branch string) bool

IsDefaultBranch reports whether branch is the repository's primary branch.

func KillWorktreeSession

func KillWorktreeSession(ctx context.Context, sessionName string) error

KillWorktreeSession closes a worktree's tmux session, if one is running.

A session tmux has already lost is success: the requested state is reached. A session that is still there after the kill is a hard failure, because the only reason to call this is that the directory underneath it is about to be removed — see DeleteWorktree.

func LookupWorktreeDisplayName

func LookupWorktreeDisplayName(stateDir, projectRoot, worktreePath string) (string, error)

LookupWorktreeDisplayName reads the registered Sidecar worktree identity without creating state. Worktrees without an explicit name use their path basename, matching the human workspace list.

func MainWorktreePath

func MainWorktreePath(ctx context.Context, workDir string) string

func MkdirPinnedTemp

func MkdirPinnedTemp(root *os.File) (string, error)

MkdirPinnedTemp creates a uniquely named staging directory inside an already open directory handle, so the parent cannot be swapped between naming and creating.

func NewSessionWithIdentity

func NewSessionWithIdentity(args []string, sessionName, displayName string) error

NewSessionWithIdentity creates the session carrying its identity environment, falling back to a plain create if this tmux rejects new-session -e (added in tmux 3.2). Losing the environment cue is a degraded shell; failing to create the session is a broken one, and the fallback still publishes the values to the session environment for any pane opened later.

It is exported for the creation paths that build their own new-session arguments rather than going through CreateShell.

func NormalizeOpenError

func NormalizeOpenError(path string, err error) error

NormalizeOpenError converts the platform's symlink errnos into a PathError.

func OpenContainedRegularFile

func OpenContainedRegularFile(root, rel string) (*os.File, error)

OpenContainedRegularFile opens rel under root with no symlink traversal.

func OpenContainedRegularFileWithHook

func OpenContainedRegularFileWithHook(root, rel string, beforeWalk func()) (*os.File, error)

OpenContainedRegularFileWithHook is OpenContainedRegularFile with a seam for tests to interleave a racing rename between pinning the root and walking it.

func OpenPinnedDirectory

func OpenPinnedDirectory(root, rel string, create bool) (*os.File, error)

OpenPinnedDirectory opens root, then walks rel beneath it a component at a time. The caller owns the returned directory handle.

func PaneID

func PaneID(sessionName string) string

PaneID returns a session's first pane identifier, or "" if tmux cannot say. Callers that cache do so around this; there is one tmux call, here.

func PathRootedIn

func PathRootedIn(path, root string) bool

PathRootedIn reports whether path lies at or beneath root.

The comparison is deliberately stricter than a string prefix. Worktree directories are siblings with related names — a repo with `feature` and `feature-2` checked out side by side is ordinary — and `strings.HasPrefix` would let deleting `feature` sweep up every shell in `feature-2`. The test is therefore made on path components: equal, or separated by a path separator.

Both sides are canonicalised (absolute, symlink-resolved where the path still exists, cleaned) so that /tmp and /private/tmp on macOS, or a trailing separator, do not decide the answer. Resolution is best-effort: by the time a caller asks, the worktree may already be gone.

A parent never matches a child: a shell in the repo root is not rooted in one of its worktrees, and deleting that worktree must not touch it.

func PendingCreationPath

func PendingCreationPath(ctx context.Context, plan *WorktreePlan) (string, error)

func PersistPendingCreation

func PersistPendingCreation(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error

func PinnedDirectoryPath

func PinnedDirectoryPath(file *os.File) (string, error)

func PruneWorktrees

func PruneWorktrees(ctx context.Context, workDir string) error

PruneWorktrees drops git's records of worktrees whose directories are gone.

func RemoteBranchExists

func RemoteBranchExists(ctx context.Context, workDir, branch string) bool

RemoteBranchExists reports whether origin carries the branch.

func RemovePendingCreation

func RemovePendingCreation(plan *WorktreePlan) error

func RemovePendingCreationWithOps

func RemovePendingCreationWithOps(plan *WorktreePlan, remove func(string) error, syncDir func(string) error) error

func RepoName

func RepoName(ctx context.Context, workDir string) string

func ResolveAgentCommand

func ResolveAgentCommand(worktreePath, agentType string, configured map[string]string, skipPerms bool) string

func RunSetupHookWithHook

func RunSetupHookWithHook(ctx context.Context, plan *WorktreePlan, beforeOpen func()) error

func SafeRelativePath

func SafeRelativePath(path string) bool

SafeRelativePath reports whether a configured path may be joined to a root. It is the first gate: absolute paths, "..", and anything climbing out are refused before any filesystem call is made.

func SanitizeSessionName

func SanitizeSessionName(name string) string

SanitizeSessionName strips the characters tmux gives meaning to in a target. It is the project plugin's rule, kept here so the shared delete path can resolve a session that plugin created.

func SessionExists

func SessionExists(name string) bool

SessionExists reports whether a tmux session of that name is already running.

func SetShellEnv

func SetShellEnv(sessionName, displayName string)

SetShellEnv publishes the display name to the tmux session environment. Panes already running keep the value they were created with — the manifest and `sidecar shell rename` remain the authority, this is only the cue.

func ShellEnvArgs

func ShellEnvArgs(sessionName, displayName string) []string

ShellEnvArgs is the new-session flag pair that publishes a shell's identity into its own environment, so a pane can name itself without asking Sidecar.

func ShellNames

func ShellNames(projectRoot string, existing []shellstate.Definition) (displayName, sessionName string)

ShellNames resolves the next generated display and session names from one project's inventory. It tolerates legacy names while never reusing a suffix.

func ShellQuote

func ShellQuote(value string) string

func ShellsRootedIn

func ShellsRootedIn(defs []shellstate.Definition, root string) []shellstate.Definition

ShellsRootedIn selects the definitions whose recorded WorkDir lies at or beneath root.

A definition with an empty WorkDir is never selected. Manifests written before td-4819be did not record one, and an entry that does not say where it lives is not evidence that it lives here — guessing would mean deleting one worktree could forget a shell in a different one. Those entries stay, and the liveness reaper handles them once their session has been observed.

This is a pure function over the manifest rows so the rule can be tested, and reused, without a repository, a tmux server, or a state directory.

func SlugifyWorktreeName

func SlugifyWorktreeName(name string) string

func StablePathKey

func StablePathKey(path string) string

func StartAgentInShell

func StartAgentInShell(ctx context.Context, sessionName, command string) error

func StartAgentInShellWithRunner

func StartAgentInShellWithRunner(ctx context.Context, sessionName, command string, runner TmuxRunner) error

func TmuxInstalled

func TmuxInstalled() bool

TmuxInstalled reports whether a tmux binary is on PATH. Creating a shell without one fails in a way worth refusing early and explaining.

func WalkPinnedDirectory

func WalkPinnedDirectory(current *os.File, rel string, create bool) (*os.File, error)

WalkPinnedDirectory descends rel from an already-open directory using openat with O_NOFOLLOW, so no component can be swapped for a symlink mid-walk. It closes current on every path out, including failure.

func WorktreeActionRefusal

func WorktreeActionRefusal(wt *WorktreeActionState, action WorktreeAction) string

func WorktreeIsDirty

func WorktreeIsDirty(ctx context.Context, path string) (bool, error)

WorktreeIsDirty reports whether a worktree holds work a removal would destroy: anything `git status` shows, tracked or untracked.

This is the one definition of "dirty" in the delete path. The refusal above consults it before a removal nobody forced, and both delete confirmations consult it to decide whether to warn that uncommitted changes will be lost — so the sentence the user reads and the check the code makes cannot disagree.

It costs one git process, which is why no caller runs it on a refresh cycle: the confirmations ask when the modal opens, once, for the single worktree the user named. An error is not "clean": callers must treat an unanswerable worktree as unknown rather than reassure the user about it.

func WorktreeOperationState

func WorktreeOperationState(ctx context.Context, path string) string

WorktreeOperationState names the Git operation a worktree is in the middle of, or "clean".

func WorktreeRoot

func WorktreeRoot(ctx context.Context, path string) string

WorktreeRoot returns the Git worktree root containing path.

func WorktreeSessionName

func WorktreeSessionName(path, name string) string

func WorktreeSessionNames

func WorktreeSessionNames(path, name string) []string

WorktreeSessionNames lists every tmux session name Sidecar may have started a worktree's agent under, most-canonical first and never empty of meaning.

There are two spellings in live use and this is not the place to unify them: WorktreeSessionName above lowercases and slugifies (it names the sessions the global surface and the CLI create), while the project plugin only replaces tmux's metacharacters. For an ordinary lowercase directory the two agree and this returns one name; for `My_Feature` they do not, and a delete that knew only one spelling would leave the other session running — the exact bug this path exists to prevent. Killing both is safe: both are Sidecar-owned `sidecar-ws-` names derived from this one directory.

func WriteDurableFile

func WriteDurableFile(path string, data []byte, mode os.FileMode) (err error)

WriteDurableFile writes data to path atomically: a temp file in the same directory, flushed and renamed, then the directory itself flushed. A reader sees either the old contents or the new ones, never a partial write, and the result survives a crash immediately after the call returns.

Types

type AgentLaunchResult

type AgentLaunchResult struct {
	SessionName, PaneID string
	Reconnected         bool
}

func LaunchWorktreeSession

func LaunchWorktreeSession(ctx context.Context, spec AgentLaunchSpec) (AgentLaunchResult, error)

func LaunchWorktreeSessionWithRunner

func LaunchWorktreeSessionWithRunner(ctx context.Context, spec AgentLaunchSpec, runner TmuxRunner) (AgentLaunchResult, error)

type AgentLaunchSpec

type AgentLaunchSpec struct {
	SessionName, WorkDir, AgentCommand, TaskID string
	Env                                        map[string]string
	StartAgent                                 bool
}

type BranchDeletion

type BranchDeletion struct {
	// RepoPath is a surviving checkout the git commands run from.
	RepoPath string
	// Branch is the branch to delete.
	Branch string
	// ExpectedOID is the tip the caller resolved for this branch. When set,
	// deletion is refused if the branch has moved since — the safety property
	// the post-merge cleanup path has always had, applied to every caller that
	// can name a tip.
	ExpectedOID string
	// Remote names the remote for DeleteRemoteBranch; empty means origin.
	Remote string
	// Force deletes a branch git considers unmerged. Interactive deletion sets
	// it because the everyday case — a branch merged by squash or rebase — is
	// one git cannot recognise as merged; cleanup sets it only after it has
	// validated the merge itself.
	Force bool
}

BranchDeletion is one caller's stated intent to delete a branch. As with WorktreeRemoval, the destructive choice is named by the caller: Force is `git branch -D`, which drops commits nothing else references.

type ExecTmuxRunner

type ExecTmuxRunner struct{}

func (ExecTmuxRunner) Run

func (ExecTmuxRunner) Run(ctx context.Context, args ...string) ([]byte, error)

type ManagedShellSpec

type ManagedShellSpec struct {
	ShellSpec
	ProjectRoot string
	AgentType   string
	SkipPerms   bool
}

ManagedShellSpec adds the durable project identity that turns a tmux session into a Sidecar shell. The operation resolves no project state on its own; the caller explicitly chooses the owning project and agent metadata.

type PathError

type PathError struct {
	Path string
	Err  error
}

PathError gives callers a stable, actionable refusal while retaining the platform errno for errors.Is and diagnostics. With O_NOFOLLOW, Darwin reports a final symlink as ELOOP and a symlink used as a directory as ENOTDIR; both mean the path cannot be safely traversed.

func (*PathError) Error

func (e *PathError) Error() string

func (*PathError) Unwrap

func (e *PathError) Unwrap() error

type PendingCreationJournal

type PendingCreationJournal struct {
	Version     int            `json:"version"`
	RepoKey     string         `json:"repoKey"`
	OperationID string         `json:"operationId"`
	Plan        WorktreePlan   `json:"plan"`
	Worktree    WorktreeRecord `json:"worktree"`
}

PendingCreationJournal v2 persists only transport-neutral operation and Git identity. Version 1 is accepted: field-based JSON decoding ignores the plugin-owned Agent pointer and presentation state stored by older builds.

func LoadPendingCreation

func LoadPendingCreation(ctx context.Context, projectRoot string, candidates []WorktreeRecord, repoKey string) (*PendingCreationJournal, error)

type SetupOutcome

type SetupOutcome struct {
	Kind, Action string
	Required     bool
	Err          error
}

func PersistWorktreeIdentity

func PersistWorktreeIdentity(ctx context.Context, plan *WorktreePlan) []SetupOutcome

PersistWorktreeIdentity records the minimal Sidecar metadata shared by every host after Git creates a worktree.

func RunConfiguredSetup

func RunConfiguredSetup(ctx context.Context, plan *WorktreePlan) []SetupOutcome

RunConfiguredSetup performs only repository-artifact setup. Durable Sidecar metadata and task/agent presentation stay with the calling application host.

type ShellResult

type ShellResult struct {
	SessionName string
	PaneID      string
}

ShellResult reports what was created. PaneID is empty when tmux created the session but did not report a pane, which is survivable: the session exists and the pane can be resolved again later.

func CreateManagedShell

func CreateManagedShell(spec ManagedShellSpec) (ShellResult, error)

CreateManagedShell creates the tmux session and then records it in the owning project's manifest. A newly-created session is rolled back if the durable identity cannot be written; a pre-existing retry is never killed.

func CreateShell

func CreateShell(spec ShellSpec) (ShellResult, error)

CreateShell makes the detached session described by spec.

An existing session of that name is treated as success rather than an error: the caller asked for a session by that name and there is one. That is what makes a retry after an interrupted create safe.

type ShellSpec

type ShellSpec struct {
	// WorkDir is the directory the session starts in.
	WorkDir string
	// SessionName is the tmux session identity, already checked for collisions
	// by whoever owns the naming scheme.
	SessionName string
	// DisplayName is what a human sees. It is published to the session
	// environment as a cue; the manifest remains the authority.
	DisplayName string
	// Cols and Rows size the pane at creation. Without them tmux uses its
	// default 80x24 and anything started before the follow-up resize — an
	// editor especially — lays itself out for 24 rows. Zero means let tmux
	// decide.
	Cols, Rows int
}

ShellSpec is everything creating a shell needs. Every field is resolved by the caller; nothing here is discovered.

type TmuxRunner

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

type WorktreeAction

type WorktreeAction string
const (
	WorktreeActionDelete WorktreeAction = "delete"
	WorktreeActionPush   WorktreeAction = "push"
	WorktreeActionMerge  WorktreeAction = "merge"
)

type WorktreeActionState

type WorktreeActionState struct {
	Path, Branch                         string
	IsMain, IsBare, IsDetached, IsLocked bool
	IsMissing, IsPrunable                bool
	// TrustPath lets an inventory-backed presentation avoid a filesystem call
	// on every frame; activation still performs its own current validation.
	TrustPath bool
}

WorktreeActionState is the shared, presentation-neutral refusal input.

type WorktreeDisplayNameResult

type WorktreeDisplayNameResult struct {
	OldName string `json:"oldName"`
	Name    string `json:"name"`
	Changed bool   `json:"changed"`
}

WorktreeDisplayNameResult describes the shared outcome used by both the TUI rename action and the agent-facing CLI.

func RenameWorktreeDisplayName

func RenameWorktreeDisplayName(ctx context.Context, stateDir, projectRoot, worktreePath, name string) (WorktreeDisplayNameResult, error)

RenameWorktreeDisplayName validates and durably persists the presentation name Sidecar owns. It does not rename the Git branch, worktree, or tmux session identity.

type WorktreePlan

type WorktreePlan struct {
	RepoKey        string   `json:"repoKey"`
	OperationID    string   `json:"operationId"`
	SourceWorktree string   `json:"sourceWorktree"`
	MainWorktree   string   `json:"mainWorktree"`
	SourceRef      string   `json:"sourceRef"`
	SourceOID      string   `json:"sourceOid"`
	Branch         string   `json:"branch"`
	Path           string   `json:"path"`
	DisplayName    string   `json:"displayName"`
	TaskID         string   `json:"taskId,omitempty"`
	TaskTitle      string   `json:"taskTitle,omitempty"`
	AgentType      string   `json:"agentType,omitempty"`
	SkipPerms      bool     `json:"skipPerms,omitempty"`
	RemotePolicy   string   `json:"remotePolicy"`
	CopyEnv        bool     `json:"copyEnv"`
	EnvFiles       []string `json:"envFiles,omitempty"`
	RunHook        bool     `json:"runHook"`
	HookPath       string   `json:"hookPath"`
	HookRequired   bool     `json:"hookRequired"`
}

WorktreePlan is the presentation-neutral contract confirmed before Git is mutated. UI-only choices may be retained by hosts beside this value.

func ResolveWorktreePlan

func ResolveWorktreePlan(ctx context.Context, workDir, projectRoot, name, base string, dirPrefix bool, setup config.WorktreeSetupConfig) (*WorktreePlan, error)

ResolveWorktreePlan validates names, source identity, destination containment, and configured setup without changing the repository.

type WorktreeRecord

type WorktreeRecord struct {
	Key        string    `json:"key"`
	RepoKey    string    `json:"repoKey"`
	Name       string    `json:"name"`
	Path       string    `json:"path"`
	Branch     string    `json:"branch"`
	BaseBranch string    `json:"baseBranch"`
	HEADOID    string    `json:"headOid"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
}

WorktreeRecord is the lifecycle identity returned by creation. It deliberately owns no panes, output buffers, trackers, or plugin state.

func ExecuteWorktree

func ExecuteWorktree(ctx context.Context, repoKey string, plan *WorktreePlan) (*WorktreeRecord, error)

ExecuteWorktree revalidates the confirmed plan, creates into a pinned staging directory, and moves/repairs it into the confirmed destination.

func ExecuteWorktreeWithRunner

func ExecuteWorktreeWithRunner(ctx context.Context, repoKey string, plan *WorktreePlan, run func(*exec.Cmd) ([]byte, error)) (*WorktreeRecord, error)

type WorktreeRemoval

type WorktreeRemoval struct {
	// RepoPath is a surviving checkout the git commands run from.
	RepoPath string
	// ProjectRoot is the owning project — the manifest whose shells rooted in
	// this worktree are forgotten and closed as part of the removal
	// (td-f017b9). It is not RepoPath: on the project surface the git commands
	// run from the current worktree while the manifest belongs to the project,
	// and on the global browser the two happen to coincide. Empty means the
	// caller has no manifest to reconcile.
	ProjectRoot string
	// Path is the worktree to remove.
	Path string
	// Branch is the branch the worktree is expected to have checked out.
	// Required when Force is false; ignored otherwise.
	Branch string
	// ExpectedOID is the HEAD the caller pinned when the user confirmed.
	// Required when Force is false; ignored otherwise.
	ExpectedOID string
	// Missing means the directory is already gone, so git's record of it is
	// pruned instead of removed.
	Missing bool
	// Force removes the worktree even when it holds uncommitted or untracked
	// work, and is the only way to reach `git worktree remove --force`.
	//
	// It belongs to interactive deletion and nothing else. A person who chose
	// "Delete" in the confirmation, which says in as many words that
	// uncommitted changes will be lost, has stated the intent; refusing them
	// afterwards leaves no way to finish the job from inside Sidecar, and a
	// worktree with one untracked build artefact in it is "dirty" by the same
	// check. Every non-interactive caller — post-merge cleanup, creation
	// rollback — leaves this false and pins Branch and ExpectedOID instead:
	// nobody confirmed anything there, so an unexpected change is a reason to
	// stop, not a thing to force past.
	Force bool
}

WorktreeRemoval is one caller's stated intent to remove a worktree. It is a struct rather than a list of arguments because the dangerous choice — Force — has to be spelled out at the call site instead of hiding in a fallback.

type WorktreeState

type WorktreeState struct {
	Path     string
	Branch   string
	HEAD     string
	Bare     bool
	Detached bool
	Locked   bool
	Prunable bool
}

WorktreeState is what `git worktree list --porcelain` reports about one worktree.

func ListWorktreeStates

func ListWorktreeStates(ctx context.Context, dir string) ([]WorktreeState, error)

ListWorktreeStates reads git's worktree inventory for the repository dir belongs to.

Jump to

Keyboard shortcuts

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