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 CanonicalWorktreePath(path string) string
- func ContainedRegularFile(root, rel string) (string, error)
- func CopyOpenFile(source *os.File, dst string) 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 ForgetShellsInWorktree(projectRoot, 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 ListLocalBranches(ctx context.Context, workDir string) ([]string, error)
- func LookupWorktreeDisplayName(stateDir, 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 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 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 PruneWorktrees(ctx context.Context, workDir string) error
- 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 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 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 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 BranchDeletion
- type DiffRef
- type ExecTmuxRunner
- type IssueRef
- type ManagedShellSpec
- type NoteRef
- type PathError
- type PendingCreationJournal
- type SetupOutcome
- type ShellResult
- type ShellSpec
- type TmuxRunner
- type WorktreeAction
- type WorktreeActionState
- type WorktreeDisplayNameResult
- type WorktreePlan
- type WorktreeRecord
- type WorktreeRemoval
- type WorktreeState
Constants ¶
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 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 CanonicalWorktreePath ¶
CanonicalWorktreePath resolves a worktree path the way git reports it, so two spellings of the same directory compare equal.
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 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 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 ¶
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 ForgetShellsInWorktree ¶
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 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 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 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 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 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 PruneWorktrees ¶
PruneWorktrees drops git's records of worktrees whose directories are gone.
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 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 SessionExists ¶
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 ¶
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 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 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 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 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 ¶
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 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 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 ShellResult ¶
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 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.