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
- Variables
- func AgentSkipFlag(agentType string) string
- func BranchOID(ctx context.Context, repoPath, branch string) string
- func BuildEnvOverrides(mainRepoPath string) map[string]string
- func CanonicalWorkPath(path string) string
- func CanonicalWorktreePath(path string) string
- func CommsSessionID(sessionName string) string
- func ContainedRegularFile(root, rel string) (string, error)
- func CopyOpenFile(source *os.File, dst string) error
- func CreationError(result CreationResult) error
- func CurrentBranch(ctx context.Context, workDir string) (string, error)
- func DefaultBranch(ctx context.Context, workDir string) string
- func DefaultBranchObserved(ctx context.Context, workDir string, onSpawn func()) string
- func DeleteCreatedWorktree(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error
- func DeleteLocalBranch(ctx context.Context, req BranchDeletion) error
- func DeleteManagedShell(projectRoot, sessionName, namespace string) error
- func DeleteRemoteBranch(ctx context.Context, req BranchDeletion) error
- func DeleteWorktree(ctx context.Context, req WorktreeRemoval) error
- func EnsureRealDirectoryPath(root, target string, requireExisting bool) error
- func ForgetManagedShell(projectRoot, sessionName, namespace string, observedAt time.Time) error
- func ForgetRecoverableSession(session string) error
- func ForgetShellsInWorktree(_ string, worktreePath string) error
- func GenerateSingleEnvCommand(overrides map[string]string) string
- func IsDefaultBranch(ctx context.Context, workDir, branch string) bool
- func KillWorktreeSession(ctx context.Context, sessionName string) error
- func KnownAgentType(agentType string, configured map[string]string) bool
- func KnownAgentTypes(configured map[string]string) []string
- func ListLocalBranches(ctx context.Context, workDir string) ([]string, error)
- func LookupWorktreeDisplayName(stateDir, projectRoot, worktreePath string) (string, error)
- func LookupWorktreeDisplayNameIn(index *projectdir.WorktreeIndex, projectRoot, worktreePath string) (string, error)
- func MainWorktreePath(ctx context.Context, workDir string) string
- func MkdirPinnedTemp(root *os.File) (string, error)
- func NewSessionWithIdentity(args []string, sessionName, displayName string) error
- func NormalizeOpenError(path string, err error) error
- func NoteTitle(title, content string) string
- func ObserveManagedShellsLive(projectRoot, namespace, currentServer string, sessionNames []string, ...) (int, error)
- func OpenContainedRegularFile(root, rel string) (*os.File, error)
- func OpenContainedRegularFileWithHook(root, rel string, beforeWalk func()) (*os.File, error)
- func OpenPinnedDirectory(root, rel string, create bool) (*os.File, error)
- func PaneDirectoryMissing(path string) bool
- func PaneID(sessionName string) string
- func PathRootedIn(path, root string) bool
- func PendingCreationPath(ctx context.Context, plan *WorktreePlan) (string, error)
- func PersistPendingCreation(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error
- func PinnedDirectoryPath(file *os.File) (string, error)
- func PruneOrphanedWorktreeSession(ctx context.Context, req OrphanedSessionPrune) (gone bool, err error)
- func PruneWorktrees(ctx context.Context, workDir string) error
- func ReapManagedShell(projectRoot, sessionName, namespace string, observedAt time.Time, ...) (shellstate.ReapOutcome, error)
- func ReapManagedShellFunc(projectRoot, sessionName, namespace string, observedAt time.Time, ...) error
- func RecordRecoverableSession(session, workDir, displayName, agentType string) error
- func RecoverySessionsPath(stateDir string) string
- func RemoteBranchExists(ctx context.Context, workDir, branch string) bool
- func RemovePendingCreation(plan *WorktreePlan) error
- func RemovePendingCreationWithOps(plan *WorktreePlan, remove func(string) error, syncDir func(string) error) error
- func RepoKeyForPath(ctx context.Context, path string) (string, error)
- func RepoName(ctx context.Context, workDir string) string
- func ResolveAgentCommand(worktreePath, agentType string, configured map[string]string, skipPerms bool) string
- func ResolveAgentCommandFromConfig(agentType string, configured map[string]string, skipPerms bool) string
- func ResolveAgentLaunchArgv(worktreePath, agentType string, configured map[string]string, skipPerms bool, ...) (argv []string, opaque bool, err error)
- func RestoreManagedShell(projectRoot, sessionName, namespace string) (shellstate.Definition, error)
- func RunSetupHookWithHook(ctx context.Context, plan *WorktreePlan, beforeOpen func()) error
- func SafeRelativePath(path string) bool
- func SanitizeSessionName(name string) string
- func ServerIncarnation() tmuxserver.Incarnation
- func ServerPID() int
- func ServerStateOf(inc tmuxserver.Incarnation) shellstate.ServerState
- func SessionExists(name string) bool
- func SetShellEnv(sessionName, displayName string)
- func ShellEnvArgs(sessionName, displayName string) []string
- func ShellNames(projectRoot string, existing []shellstate.Definition) (displayName, sessionName string)
- func ShellQuote(value string) string
- func ShellsRootedIn(defs []shellstate.Definition, root string) []shellstate.Definition
- func SlugifyWorktreeName(name string) string
- func StablePathKey(path string) string
- func StartAgentInShell(ctx context.Context, sessionName, command string) error
- func StartAgentInShellWithRunner(ctx context.Context, sessionName, command string, runner TmuxRunner) error
- func TmuxInstalled() bool
- func TypeInShell(ctx context.Context, sessionName, command string) error
- func TypeInShellWithRunner(ctx context.Context, sessionName, command string, runner TmuxRunner) error
- func WalkPinnedDirectory(current *os.File, rel string, create bool) (*os.File, error)
- func WorktreeActionRefusal(wt *WorktreeActionState, action WorktreeAction) string
- func WorktreeDeleteState(ctx context.Context, path string) (string, error)
- func WorktreeIsDirty(ctx context.Context, path string) (bool, error)
- func WorktreeOperationState(ctx context.Context, path string) string
- func WorktreeRoot(ctx context.Context, path string) string
- func WorktreeSessionName(path, name string) string
- func WorktreeSessionNames(path, name string) []string
- func WriteDurableFile(path string, data []byte, mode os.FileMode) (err error)
- type AgentLaunchResult
- type AgentLaunchSpec
- type AgentLauncher
- type AgentStartStage
- type BranchDeletion
- type CreationResult
- type DiffRef
- type ExecTmuxRunner
- type IssueRef
- type ManagedShellSpec
- type NoteRef
- type OrphanedSessionPrune
- type PathError
- type PendingCreationJournal
- type Service
- func (s Service) BeginWorktree(ctx context.Context, plan *WorktreePlan) CreationResult
- func (s Service) CreateShell(spec ManagedShellSpec) (ShellResult, error)
- func (s Service) CreateWorktree(ctx context.Context, plan *WorktreePlan, startTask bool) CreationResult
- func (Service) DeleteCreatedWorktree(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error
- func (s Service) DeleteShell(projectRoot, session, namespace string) error
- func (Service) DeleteWorktree(ctx context.Context, request WorktreeRemoval) error
- func (s Service) FinalizeWorktree(plan *WorktreePlan) error
- func (s Service) LaunchWorktree(ctx context.Context, spec AgentLaunchSpec) (AgentLaunchResult, error)
- func (Service) PlanWorktree(ctx context.Context, workDir, projectRoot, name, base string, dirPrefix bool, ...) (*WorktreePlan, error)
- func (Service) RenameCurrentShell(stateDir string, request shellstate.RenameRequest) (shellstate.RenameResult, error)
- func (Service) RenameShell(path string, request shellstate.RenameRequest) (shellstate.RenameResult, error)
- func (Service) RenameWorktree(ctx context.Context, stateDir, projectRoot, path, name string) (WorktreeDisplayNameResult, error)
- func (Service) RestoreShell(projectRoot, session, namespace string) (shellstate.Definition, error)
- func (s Service) SetupWorktree(ctx context.Context, plan *WorktreePlan, startTask bool) []SetupOutcome
- func (Service) StartShell(ctx context.Context, projectRoot, session, namespace string) (SessionStartResult, error)
- func (s Service) StartWorktree(ctx context.Context, stateDir, projectRoot, target string) (SessionStartResult, error)
- type SessionStartResult
- type SetupOutcome
- type ShellCreateError
- type ShellEditor
- type ShellRecords
- type ShellResult
- type ShellSpec
- type TmuxRunner
- type WorktreeAction
- type WorktreeActionState
- type WorktreeDisplayNameResult
- type WorktreeIdentityError
- type WorktreePlan
- type WorktreeRecord
- type WorktreeRemoval
- type WorktreeRemovedWarning
- type WorktreeShell
- type WorktreeState
Constants ¶
const RecoverySessionsFile = "recovery-sessions.json"
RecoverySessionsFile is deliberately separate from shells.json. Worktree sessions and terminal splits already have UI identities in workspace state; putting them in shells.json would manufacture duplicate shell rows.
const WorktreeSessionPrefix = "sidecar-ws-"
WorktreeSessionPrefix names the tmux sessions Sidecar runs a worktree's agent in.
Variables ¶
var DefaultEnvOverrides = map[string]string{
"GOWORK": "off", "GOFLAGS": "", "NODE_OPTIONS": "", "NODE_PATH": "", "PYTHONPATH": "", "VIRTUAL_ENV": "",
}
var ErrOrphanChanged = errors.New("session changed since it was planned")
ErrOrphanChanged refuses a prune whose session or root no longer matches the plan.
var ErrSessionStartNotFound = errors.New("no recorded shell or worktree matches the target")
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 AgentSkipFlag ¶ added in v1.2.1
AgentSkipFlag returns the CLI flag that opts this agent into auto-approve, or "" if the agent has no such flag. Creation forms use this to decide whether to show the auto-approve checkbox; do not copy this map elsewhere.
func BranchOID ¶
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 CanonicalWorkPath ¶ added in v1.15.0
CanonicalWorkPath is canonicalWorkPath for callers outside this package that compare a path which may no longer exist (a removed worktree) against one git reports canonically.
func CanonicalWorktreePath ¶
CanonicalWorktreePath resolves a worktree path the way git reports it, so two spellings of the same directory compare equal.
func CommsSessionID ¶ added in v1.16.0
CommsSessionID derives the explicit comms identity of a newly-created local terminal. Split terminals use it without claiming managed-shell ownership. It never inherits COMMS_SESSION or changes the launching process environment.
func ContainedRegularFile ¶
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 ¶
CopyOpenFile copies an already-opened source to dst, preserving its mode and flushing before it reports success.
func CreationError ¶ added in v1.16.0
func CreationError(result CreationResult) error
CreationError retains the execution error and required setup failures for callers whose surface has only one error channel.
func CurrentBranch ¶ added in v1.2.1
CurrentBranch returns the checked-out branch name (`git rev-parse --abbrev-ref HEAD`). Detached HEAD is "HEAD".
func DefaultBranch ¶
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 ¶
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 ¶
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 identity and dirtiness first. A forced removal with ExpectedOID still validates its pinned identity: Force authorizes deleting dirty content, not deleting a different checkout. Every initial validation runs before shell/session teardown. State-fenced requests also revalidate after teardown and before each Git removal attempt; a refusal there can leave sessions closed but always leaves the checkout intact.
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 ¶
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 ¶
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 ForgetRecoverableSession ¶ added in v1.15.0
ForgetRecoverableSession removes the supplemental identity after an explicit close. A missing record is already the requested state.
func ForgetShellsInWorktree ¶
ForgetShellsInWorktree closes every managed shell rooted in worktreePath on this tmux server, across all projects: the manifest row and tmux session go. Shells recorded on another socket stay recorded and produce a warning.
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 IsDefaultBranch ¶
IsDefaultBranch reports whether branch is the repository's primary branch.
func KillWorktreeSession ¶
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 KnownAgentType ¶ added in v1.11.0
KnownAgentType reports whether agentType names an agent family this Sidecar can launch: a catalog family, a launchable legacy one, or a name the caller has configured a start command for.
It exists because a value a caller has just typed deserves a verdict rather than a resolution. `--agent claud` records "claud" as the family, and every surface that keys off the agent type — the provider column, activity identification, session lookup — would then disagree with whatever ends up running in the pane. A picker cannot produce that value; a flag can, so the flag checks. It is deliberately wider than agentcatalog.Find: this answers "can this Sidecar launch it", which includes the legacy and configured families a picker no longer offers.
func KnownAgentTypes ¶ added in v1.11.0
KnownAgentTypes lists the agent families a caller should choose from, sorted, so a refusal can say what was expected rather than only what was wrong.
Narrower than KnownAgentType on purpose, and in one direction only: the legacy families agentcatalog keeps launchable are still accepted but are not offered here, for the same reason no picker offers them. A list is advice about what to type next, and advertising a compatibility case would be advice to start using it.
func ListLocalBranches ¶ added in v1.2.1
ListLocalBranches returns local branch short names in workDir (`git branch --format=%(refname:short)`).
func LookupWorktreeDisplayName ¶
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 LookupWorktreeDisplayNameIn ¶ added in v1.16.0
func LookupWorktreeDisplayNameIn(index *projectdir.WorktreeIndex, projectRoot, worktreePath string) (string, error)
LookupWorktreeDisplayNameIn is LookupWorktreeDisplayName answered from an index of the state tree, for callers that name many worktrees at once.
func MkdirPinnedTemp ¶
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 ¶
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 ¶
NormalizeOpenError converts the platform's symlink errnos into a PathError.
func NoteTitle ¶ added in v1.8.0
NoteTitle is what a note is called on screen: its own title, or the first non-blank line of its body when it has none. td leaves the title column empty for notes captured body-first, and the notes plugin has always shown that first line — this is the same rule, shared so a note does not read as "untitled" in one surface and by name in another.
func ObserveManagedShellsLive ¶ added in v1.11.0
func ObserveManagedShellsLive(projectRoot, namespace, currentServer string, sessionNames []string, now time.Time) (int, error)
ObserveManagedShellsLive records that these sessions are running under this tmux server, which is what makes them cold-restore candidates later.
It writes only when a shell's marker actually changes, so calling it once per refresh cycle costs one manifest read and, in the steady state, no write.
func OpenContainedRegularFile ¶
OpenContainedRegularFile opens rel under root with no symlink traversal.
func OpenContainedRegularFileWithHook ¶
OpenContainedRegularFileWithHook is OpenContainedRegularFile with a seam for tests to interleave a racing rename between pinning the root and walking it.
func OpenPinnedDirectory ¶
OpenPinnedDirectory opens root, then walks rel beneath it a component at a time. The caller owns the returned directory handle.
func PaneDirectoryMissing ¶ added in v1.16.0
PaneDirectoryMissing is the same conservative filesystem evidence for the orphan plan and its close-time recheck. Unknown cwd or an unmounted parent must never count as a removed directory.
func PaneID ¶
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 ¶
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 PruneOrphanedWorktreeSession ¶ added in v1.15.0
func PruneOrphanedWorktreeSession(ctx context.Context, req OrphanedSessionPrune) (gone bool, err error)
PruneOrphanedWorktreeSession closes one rootless worktree session and forgets what Sidecar recorded about it, touching nothing git owns: the worktree is already gone, and whether to prune git's metadata or delete the branch is git's question, not this one.
Everything the plan concluded is checked again at the moment of the kill, because a plan is a statement about the moment it was taken:
- the root must still be gone (a checkout can have been re-created there);
- the session must still start in the planned directory, inside the root (its name is derived from a base name, so a new worktree can reuse it);
- every pane, including associated managed shells, must have positive missing-directory evidence (an agent may follow a moved worktree).
gone reports that the session had already closed, which is success.
func PruneWorktrees ¶
PruneWorktrees drops git's records of worktrees whose directories are gone.
func ReapManagedShell ¶ added in v1.11.0
func ReapManagedShell(projectRoot, sessionName, namespace string, observedAt time.Time, server tmuxserver.Incarnation) (shellstate.ReapOutcome, error)
ReapManagedShell is what a liveness pass calls instead of ForgetManagedShell.
It is the same conditional write with one question asked first: did this shell exit, or did its tmux server? When the server is gone or has been replaced, the record is kept and marked as a cold-restore candidate instead of being tombstoned, because a session that vanished along with the process hosting it has not been closed by anyone — it is exactly what a cold restore exists to bring back.
This is the fix for the failure mode that destroyed a user's sidecar and braid shell records: when a server dies, every session disappears in the same instant, and a per-shell "is this one gone?" question has no true answer. Answering it anyway tombstones the whole file. Routing the liveness path through here means a server death can no longer produce a deletion at all, rather than being guarded against producing one.
currentServer is the tmux server observed at the moment of the write, as a "pid=N" id from tmuxserver.Incarnation.ServerID, or empty when no server is running.
func ReapManagedShellFunc ¶ added in v1.11.0
func ReapManagedShellFunc(projectRoot, sessionName, namespace string, observedAt time.Time, server tmuxserver.Incarnation) error
ReapManagedShellFunc adapts ReapManagedShell to shellliveness.ForgetFunc.
The outcome is dropped here rather than never produced: ReapManagedShell returns it because preserved-versus-tombstoned is the fact worth asserting on in a test, while the liveness surfaces need only success or failure — a preserved record simply reappears as an offline row on the next refresh, which is the correct display for a cold-restore candidate.
func RecordRecoverableSession ¶ added in v1.15.0
RecordRecoverableSession gives a Sidecar-owned non-shell tmux session the same prior-live eligibility marker managed shells receive at creation.
func RecoverySessionsPath ¶ added in v1.15.0
func RemoteBranchExists ¶
RemoteBranchExists reports whether origin carries the branch.
func RemovePendingCreation ¶
func RemovePendingCreation(plan *WorktreePlan) error
func RepoKeyForPath ¶ added in v1.3.0
RepoKeyForPath is the workspace plugin's repoSnapshot.Key: StablePathKey of the resolved git common-dir. Pending-creation resume looks up this identity.
func ResolveAgentCommand ¶
func ResolveAgentCommandFromConfig ¶ added in v1.11.0
func ResolveAgentCommandFromConfig(agentType string, configured map[string]string, skipPerms bool) string
ResolveAgentCommandFromConfig resolves an agent's launch command from configuration and the built-in defaults alone, without consulting the checkout's .sidecar-agent-start file.
It exists for callers whose worktree is on ANOTHER machine. Handing a remote path to ResolveAgentCommand does not fail — it reads THIS machine's file at a path that, on a developer's two similarly laid out machines, usually exists here too, and launches whatever that file says. That is the same failure class as resolving a remote workspace's path against the local filesystem, and it is silent.
func ResolveAgentLaunchArgv ¶ added in v1.11.0
func ResolveAgentLaunchArgv(worktreePath, agentType string, configured map[string]string, skipPerms bool, extra []string) (argv []string, opaque bool, err error)
ResolveAgentLaunchArgv preserves the difference between catalog launches and legacy user-authored shell commands. Catalog launches remain structured argv. A .sidecar-agent-start or plugins.workspace.agentStart override stays opaque and is evaluated once through sh -lc; it must never be persisted as replayable structured provider metadata.
extra are provider arguments the caller supplied alongside the family. On a catalog launch they are argv entries after the command. On an opaque command they are appended quoted, one shell word each, so the configured command still runs and a value with a space in it stays one argument — but only when that command is a plain command line. One that contains shell syntax (a pipe, a list, a redirection, a subshell) has no single place the arguments belong: appended to `claude | tee log` they would reach tee, and the provider would start without them and without a word said. That case is refused, naming the command, so the caller puts the arguments in it.
func RestoreManagedShell ¶ added in v1.6.0
func RestoreManagedShell(projectRoot, sessionName, namespace string) (shellstate.Definition, error)
RestoreManagedShell moves a forgotten shell record back onto the project's live list. It does not start a tmux session.
func RunSetupHookWithHook ¶
func RunSetupHookWithHook(ctx context.Context, plan *WorktreePlan, beforeOpen func()) error
func SafeRelativePath ¶
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 ¶
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 ServerIncarnation ¶ added in v1.11.0
func ServerIncarnation() tmuxserver.Incarnation
ServerIncarnation observes the tmux server with its pid, distinguishing "no server is running" from "the question could not be answered".
ServerPID alone cannot make that distinction — it returns 0 for both — and a caller that needs to decide whether a shell died with its server must not treat a failed subprocess as a dead server.
func ServerPID ¶ added in v1.11.0
func ServerPID() int
ServerPID returns the PID of the tmux server on the current socket, or 0 when there is none or it cannot be read.
func ServerStateOf ¶ added in v1.11.0
func ServerStateOf(inc tmuxserver.Incarnation) shellstate.ServerState
ServerStateOf maps an observed tmux incarnation onto the evidence the shell writer reasons about.
The fourth case is the one that matters and the one that was missed: an incarnation can be Present and still carry pid 0, because a socket stat alone identifies a socket rather than a server process. That is not "the server is gone" and it is not "the server is this one" — it is "I cannot tell which server this is", and it has to arrive at the writer as exactly that. Reading it as death is what made two production surfaces stop tombstoning entirely.
func SessionExists ¶
SessionExists reports whether a tmux session of that name is already running.
func SetShellEnv ¶
func SetShellEnv(sessionName, displayName string)
SetShellEnv publishes the same identity contract to the 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 ¶
ShellEnvArgs is the new-session flag set that publishes a shell's identity into its own environment, so a pane can name itself without asking Sidecar.
It also publishes the managed-shell contract documented on shellstate.ManagedEnv, which is what tells a provider hook it is allowed to report lifecycle state and which server incarnation to namespace it under. COMMS_SESSION gives shell-tool children an identity even without TMUX_PANE; a new managed session always derives it rather than inheriting another lane.
This function and SetShellEnv are a pair and must stay in step: the -e form needs tmux 3.2, and SetShellEnv is the fallback for older tmux and for the recreate paths. Anything added to one and not the other silently vanishes on exactly the machines least likely to be tested on.
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 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 StablePathKey ¶
func StartAgentInShell ¶
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 TypeInShell ¶ added in v1.3.0
TypeInShell types command into the session without pressing Enter, so the user can review it. This is the send-keys core behind resume injection.
func TypeInShellWithRunner ¶ added in v1.3.0
func TypeInShellWithRunner(ctx context.Context, sessionName, command string, runner TmuxRunner) error
func WalkPinnedDirectory ¶
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 WorktreeDeleteState ¶ added in v1.16.0
WorktreeDeleteState binds confirmation to this checkout incarnation and the bytes it would remove, including ignored and untracked work. It is computed only for delete planning/execution, never for catalog or startup refreshes. Symlinks are hashed as links; their destinations are never traversed.
func WorktreeIsDirty ¶
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 ¶
WorktreeOperationState names the Git operation a worktree is in the middle of, or "clean".
func WorktreeRoot ¶
WorktreeRoot returns the Git worktree root containing path.
func WorktreeSessionName ¶
func WorktreeSessionNames ¶
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 ¶
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 ¶
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 AgentLauncher ¶ added in v1.16.0
type AgentLauncher struct {
Wait func(context.Context, agentcontrol.Target, time.Duration) (agentcontrol.Snapshot, error)
StartAgent func(context.Context, agentcontrol.StartRequest) (agentcontrol.Agent, error)
}
AgentLauncher runs the common readiness-then-start sequence. Callers supply the resolved target and argv, and retain their presentation and naming rules. The zero value uses one local agentcontrol service for both phases.
func (AgentLauncher) Start ¶ added in v1.16.0
func (l AgentLauncher) Start(ctx context.Context, request agentcontrol.StartRequest, waitReady, useReadyTarget bool) (agentcontrol.Agent, AgentStartStage, error)
Start waits only when requested: reconnecting worktree sessions already have an occupant that Start must inspect rather than waiting for an idle shell. useReadyTarget preserves callers that pin the physical identity observed during readiness. Other callers keep their existing requested identity. Failures retain the original error and never retry or submit after a failed readiness check.
type AgentStartStage ¶ added in v1.16.0
type AgentStartStage string
AgentStartStage identifies the failed phase without prescribing a surface's error wording. A successful start returns the empty stage.
const ( AgentWaitReady AgentStartStage = "wait_ready" AgentStartProvider AgentStartStage = "start_provider" )
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 CreationResult ¶ added in v1.16.0
type CreationResult struct {
Record *WorktreeRecord
Outcomes []SetupOutcome
Err error
}
type DiffRef ¶ added in v1.7.0
DiffRef is one recent commit or branch the diff picker can offer. Identity is what a target resolves from (`sidecar open --diff <identity>` shape); Label is what the row displays.
func RecentDiffRefs ¶ added in v1.7.0
RecentDiffRefs lists recent commits and local branches in workDir, commits first, newest first. These are offers, not resolutions: opening re-resolves host-side through uirequest.DiffTarget exactly as the CLI does.
type ExecTmuxRunner ¶
type ExecTmuxRunner struct{}
type IssueRef ¶ added in v1.7.0
IssueRef is one td issue the issue picker can offer. Updated is when the issue last changed, which is what a picker row uses to say how fresh it is.
type ManagedShellSpec ¶
type ManagedShellSpec struct {
ShellSpec
// Allocate requests a fresh identity under the manifest lock. SessionName
// is only a caller preview; DisplayName empty requests a generated label.
Allocate bool
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 NoteRef ¶ added in v1.7.0
NoteRef is one td note the note picker can offer. Title is what the note reads as, not the raw title column: most notes carry an empty title and are known by their first line, so the picker would otherwise offer rows a user cannot tell apart. Updated is when the note last changed, which is what a picker row uses to say how fresh it is.
type OrphanedSessionPrune ¶ added in v1.15.0
type OrphanedSessionPrune struct {
// ProjectRoot is the owning project's path exactly as registered (it is
// matched against the registry, so a canonicalized spelling can miss). It
// owns the manifest whose shells rooted in Root are closed with
// the session, exactly as DeleteWorktree closes them. Empty for a session no
// registered project accounts for; only its own session is closed then.
ProjectRoot string
// Root is the removed worktree.
Root string
// Session is the tmux session to close.
Session string
// SessionPath is the start directory observed when the orphan was planned.
// The session is re-read immediately before the kill and left alone if it
// no longer starts there: the name is derived from a base name, so the same
// name can belong to a worktree created since the plan.
SessionPath string
}
OrphanedSessionPrune is one rootless worktree session to close: a session still running after its worktree was removed outside Sidecar (td-0b90da).
type PathError ¶
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.
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 Service ¶ added in v1.16.0
type Service struct {
Execute func(context.Context, string, *WorktreePlan) (*WorktreeRecord, error)
Journal func(context.Context, *WorktreePlan, *WorktreeRecord) error
Identity func(context.Context, *WorktreePlan) []SetupOutcome
Setup func(context.Context, *WorktreePlan) []SetupOutcome
Finalize func(*WorktreePlan) error
Launch func(context.Context, AgentLaunchSpec) (AgentLaunchResult, error)
Shells ShellRecords
}
Service is the application boundary for workspace mutations. It holds no operation, viewer, or selection state. A confirmed plan and its partial result belong to the caller, which can resume the same phases after a failure. The zero value uses the local Git, shellstate, setup, and tmux adapters.
func (Service) BeginWorktree ¶ added in v1.16.0
func (s Service) BeginWorktree(ctx context.Context, plan *WorktreePlan) CreationResult
BeginWorktree creates the confirmed identity and journals even a partial success. Cancellation after Git creates it must not lose recovery evidence.
func (Service) CreateShell ¶ added in v1.16.0
func (s Service) CreateShell(spec ManagedShellSpec) (ShellResult, error)
func (Service) CreateWorktree ¶ added in v1.16.0
func (s Service) CreateWorktree(ctx context.Context, plan *WorktreePlan, startTask bool) CreationResult
CreateWorktree runs the non-interactive sequence. Interactive clients use the same phases to display progress and offer recovery before finalization.
func (Service) DeleteCreatedWorktree ¶ added in v1.16.0
func (Service) DeleteCreatedWorktree(ctx context.Context, plan *WorktreePlan, record *WorktreeRecord) error
func (Service) DeleteShell ¶ added in v1.16.0
func (Service) DeleteWorktree ¶ added in v1.16.0
func (Service) DeleteWorktree(ctx context.Context, request WorktreeRemoval) error
func (Service) FinalizeWorktree ¶ added in v1.16.0
func (s Service) FinalizeWorktree(plan *WorktreePlan) error
func (Service) LaunchWorktree ¶ added in v1.16.0
func (s Service) LaunchWorktree(ctx context.Context, spec AgentLaunchSpec) (AgentLaunchResult, error)
func (Service) PlanWorktree ¶ added in v1.16.0
func (Service) PlanWorktree(ctx context.Context, workDir, projectRoot, name, base string, dirPrefix bool, setup config.WorktreeSetupConfig) (*WorktreePlan, error)
func (Service) RenameCurrentShell ¶ added in v1.16.0
func (Service) RenameCurrentShell(stateDir string, request shellstate.RenameRequest) (shellstate.RenameResult, error)
func (Service) RenameShell ¶ added in v1.16.0
func (Service) RenameShell(path string, request shellstate.RenameRequest) (shellstate.RenameResult, error)
func (Service) RenameWorktree ¶ added in v1.16.0
func (Service) RestoreShell ¶ added in v1.16.0
func (Service) RestoreShell(projectRoot, session, namespace string) (shellstate.Definition, error)
func (Service) SetupWorktree ¶ added in v1.16.0
func (s Service) SetupWorktree(ctx context.Context, plan *WorktreePlan, startTask bool) []SetupOutcome
SetupWorktree is also the retry path. Task start is an explicit option: the project create form links and starts a task, whereas other callers only link.
func (Service) StartShell ¶ added in v1.17.0
func (Service) StartShell(ctx context.Context, projectRoot, session, namespace string) (SessionStartResult, error)
StartShell starts only an exact, existing managed record on the caller's server. It retains agent metadata and never resumes a previous conversation.
func (Service) StartWorktree ¶ added in v1.17.0
func (s Service) StartWorktree(ctx context.Context, stateDir, projectRoot, target string) (SessionStartResult, error)
StartWorktree starts a session in an existing linked checkout, without creating a branch or running its setup pipeline again. The path is the catalog identity.
type SessionStartResult ¶ added in v1.17.0
SessionStartResult retains the selected identity when an inactive terminal is started.
type SetupOutcome ¶
func FailedSetupOutcomes ¶ added in v1.16.0
func FailedSetupOutcomes(outcomes []SetupOutcome, requiredOnly bool) []SetupOutcome
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 ShellCreateError ¶ added in v1.16.0
ShellCreateError gives every surface a named, actionable creation failure.
func (*ShellCreateError) Error ¶ added in v1.16.0
func (e *ShellCreateError) Error() string
func (*ShellCreateError) Unwrap ¶ added in v1.16.0
func (e *ShellCreateError) Unwrap() error
type ShellEditor ¶ added in v1.16.0
type ShellEditor interface {
EditShells(func(*shellstate.Snapshot) (bool, error)) error
}
ShellEditor retains a loaded projection's recovery policy and revision fence, while shellstate owns the cross-process transaction. Never reenter the store from the callback.
type ShellRecords ¶ added in v1.16.0
type ShellRecords interface {
AddShell(shellstate.Definition) error
RemoveShell(string) error
}
ShellRecords allows an existing projection to retain its recovery policy while the service owns the creation and deletion sequence. Both the default adapter and the workspace compatibility handle persist through shellstate.
type ShellResult ¶
type ShellResult struct {
SessionName string
PaneID string
DisplayName string
// contains filtered or unexported fields
}
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 exact tmux identity for restore/reconnect, or an
// advisory preview when ManagedShellSpec.Allocate is set.
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
// PreserveRecoveryEvidence keeps an inferred candidate and loss marker
// until the cold-restore executor has made its prefill decision. Ordinary
// creation leaves this false and starts a fresh observed lifetime.
PreserveRecoveryEvidence bool
// RequireNew refuses an occupied session instead of reconnecting.
RequireNew bool
}
ShellSpec is everything creating a shell needs. Every field is resolved by the caller; nothing here is discovered.
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 WorktreeIdentityError ¶ added in v1.14.0
type WorktreeIdentityError struct {
Cause error
}
WorktreeIdentityError is a removal refusal caused by a checkout no longer matching the branch and HEAD the caller pinned. It is typed so a transport can report an identity refusal distinctly from a Git or tmux failure while existing callers continue to receive the same non-nil error text.
func (*WorktreeIdentityError) Error ¶ added in v1.14.0
func (e *WorktreeIdentityError) Error() string
func (*WorktreeIdentityError) Unwrap ¶ added in v1.14.0
func (e *WorktreeIdentityError) Unwrap() error
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. Shell teardown inventories every
// registered project's manifest because shells from other projects can
// also be rooted inside this worktree (td-17b5e2).
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 or ExpectedOID is supplied. A supplied
// branch/OID pair is always enforced, including for a forced removal.
Branch string
// ExpectedOID is the HEAD the caller pinned when the user confirmed.
// Required when Force is false. When supplied with Force, it remains an
// identity fence: Force authorizes dirty content removal, not a different
// checkout that appeared after confirmation.
ExpectedOID string
// ExpectedDeleteState pins the exact checkout incarnation and contents.
ExpectedDeleteState 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 WorktreeRemovedWarning ¶ added in v1.14.0
type WorktreeRemovedWarning struct {
Cause error
}
WorktreeRemovedWarning reports a teardown error discovered after Git has already removed the worktree. Existing callers continue to receive a non-nil error, preserving their conservative behaviour; callers that own follow-up cleanup can use errors.As to distinguish this completed removal from a failure that left the checkout in place.
Today Cause is a failure closing one or more managed shells rooted in the worktree. DeleteWorktree deliberately attempts the Git removal anyway so a stubborn shell cannot strand both the checkout and its already-forgotten Sidecar records.
func (*WorktreeRemovedWarning) Error ¶ added in v1.14.0
func (e *WorktreeRemovedWarning) Error() string
func (*WorktreeRemovedWarning) Unwrap ¶ added in v1.14.0
func (e *WorktreeRemovedWarning) Unwrap() error
type WorktreeShell ¶ added in v1.16.0
type WorktreeShell struct {
ProjectRoot string
Definition shellstate.Definition
CanClose bool
// contains filtered or unexported fields
}
WorktreeShell is an affected managed shell and the project manifest owning it.
func ListShellsInWorktree ¶ added in v1.16.0
func ListShellsInWorktree(worktreePath string) ([]WorktreeShell, error)
ListShellsInWorktree finds shells rooted in the removed directory across all registered projects. The worktree's project does not own every shell started inside it: an agent may have opened it from another project's workspace.
func ListShellsInWorktreeWithStateDir ¶ added in v1.16.0
func ListShellsInWorktreeWithStateDir(stateDir, worktreePath string) ([]WorktreeShell, error)
ListShellsInWorktreeWithStateDir is the read-only inventory for an explicit state directory, shared by deletion planning and execution.
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.