shellliveness

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package shellliveness decides, from tmux evidence alone, whether a Sidecar shell's tmux session is gone.

Both Workspaces surfaces — the project plugin and the global browser — must reach the same answer, so the rule lives here rather than in either of them. Each surface already watches tmux for its own reasons (the plugin polls the pane it is rendering, the global browser takes one `list-panes -a` per refresh cycle); this package turns what they already saw into a verdict and confirms it with one bounded probe. Nothing here runs on a timer, and nothing here belongs on the startup path.

The asymmetry is deliberate. Leaving a dead row on screen for another poll is a cosmetic defect; deleting a live user's shell entry because tmux hiccuped is data loss. So every ambiguous signal — a missing binary, a socket we could not reach, a server that is not running — resolves to Unknown, and Unknown never closes anything.

Index

Constants

View Source
const DefaultConfirmations = 1

DefaultConfirmations is how many consecutive Gone probes close a shell.

One is correct here because a probe is never the only evidence: the caller has already observed the session missing from a listing or failing to capture, and the probe is the independent second opinion taken fresh from tmux. Two positives from two different observations beats two positives from the same one.

View Source
const DefaultProbeInterval = 15 * time.Second

DefaultProbeInterval throttles repeat probes for one session. The first probe after a suspicion is immediate — that is the one that closes a shell the user just exited. The interval only governs the stuck case, where tmux keeps answering Unknown: a shell that keeps failing must not spawn a tmux process per poll, because on a machine running an endpoint security agent every spawn is expensive.

View Source
const ProbeTimeout = 2 * time.Second

ProbeTimeout bounds one probe. It is generous relative to a `list-sessions` against a healthy server and short enough that a wedged one cannot pin a poll chain for long.

Variables

This section is empty.

Functions

func ConfirmReap added in v1.11.0

func ConfirmReap(tracker *Tracker, server tmuxserver.Incarnation, probe ReapProbe, verdict Verdict) bool

ConfirmReap folds one probe verdict in and reports whether this shell should now leave the surface and have its manifest entry tombstoned.

server is the tmux server identity observed at the moment the verdict is being applied, which can be a different one from the identity the suspicion was formed under; recording it here is what makes the fence in Confirm fire.

func PathWithin added in v1.15.0

func PathWithin(path, root string) bool

PathWithin reports whether the canonical path lies at or beneath the canonical root, component-wise: `feature-2` is not within `feature`.

func ReapShell added in v1.11.0

func ReapShell(probe ProbeFunc, forget ForgetFunc, target ReapProbe, server tmuxserver.Incarnation) (resurrected bool, err error)

ReapShell performs the write half: one fresh probe, then the conditional tombstone.

The re-probe is not belt and braces. A verdict is a statement about the moment it was taken, and between that moment and this write the user can have brought the same tmux name back — pressing Enter on an offline row recreates the session under its old name — and deleting the identity of a shell that is running right now is the one outcome this feature must never produce. Two independent things prevent it: ConfirmReap's incarnation fence, and this probe, which makes the evidence fresh at the instant of the deletion.

resurrected reports that the session was back and no write was attempted.

server is the tmux server observed at the instant of the write, and it travels all the way into the writer: see ForgetFunc for why the decision the writer makes with it is the difference between tombstoning a closed terminal and deleting the record of a shell whose server crashed underneath it.

func SamePath added in v1.15.0

func SamePath(a, b string) bool

SamePath compares two already-canonical paths.

func SuspectsDeath

func SuspectsDeath(message string) bool

SuspectsDeath reports whether a failed tmux interaction is worth probing. It is intentionally cheap and text-based: the caller already has the error in hand, and a probe only follows a positive answer here.

func SuspectsDeathErr

func SuspectsDeathErr(err error) bool

SuspectsDeathErr is SuspectsDeath over an error value.

tmux's actual message is almost never in the error string: a failed exec.Cmd.Output() wraps to "exit status 1" and hides "can't find session" in ExitError.Stderr. Callers that only matched err.Error() were therefore matching nothing at all, which is why an exited shell used to linger.

Types

type ForgetFunc added in v1.11.0

type ForgetFunc func(projectRoot, tmuxName, namespace string, observedAt time.Time, server tmuxserver.Incarnation) error

ForgetFunc retires one shell record. workspaceops.ReapManagedShell is the production implementation; its signature is restated here rather than imported so this package stays free of the writer's dependencies and both callers can substitute it in tests.

server is the tmux server observed at the moment of the write. It is the whole incarnation rather than an id string because the writer must be able to tell "no server is running" from "I could not identify the server": a socket-only observation is Present with pid 0, and reading that as death is what made two surfaces stop tombstoning entirely. It is a parameter rather than a detail of the writer because the writer's most important decision depends on it: a shell that vanished along with its server is preserved and marked as a cold-restore candidate, and only a shell that vanished inside a server that is still running is tombstoned. Passing the server identity down to the write is what makes a server death structurally unable to produce a deletion, instead of merely guarded against producing one.

type ListedWorktree added in v1.15.0

type ListedWorktree struct {
	// Path is canonical: absolute and symlink-resolved.
	Path     string
	Prunable bool
	// Sessions are the tmux names Sidecar would give this worktree's session.
	// A live session under one of them belongs to this worktree.
	Sessions []string
}

ListedWorktree is one entry of `git worktree list --porcelain`.

type OrphanObservation added in v1.15.0

type OrphanObservation struct {
	Inventories []WorktreeInventory
	Registered  []RegisteredRoot
	Sessions    []TmuxSession
	// ListingFailed reports that the tmux session listing errored.
	ListingFailed bool
	// SessionPrefix is the worktree session prefix (sidecar-ws-). Sessions
	// outside it are never judged.
	SessionPrefix string
}

OrphanObservation is everything one pass knows.

type OrphanPlan added in v1.15.0

type OrphanPlan struct {
	Orphans []OrphanSession
	// Roots maps every registered root with a verdict to its reason, whether or
	// not a session is running in it. `shell list` uses it to mark shells
	// rooted in a removed worktree.
	Roots map[string]OrphanReason
	// Skipped names the guard that stopped the pass. Empty when it ran.
	Skipped string
}

OrphanPlan is what one pass's evidence supports.

func PlanWorktreeOrphans added in v1.15.0

func PlanWorktreeOrphans(obs OrphanObservation) OrphanPlan

PlanWorktreeOrphans names every live worktree session whose worktree is gone.

type OrphanReason added in v1.15.0

type OrphanReason string

OrphanReason says why a worktree root no longer backs its sessions. Empty means it does, or that the evidence cannot say.

const (
	// OrphanNotListed: the owning repository answered and no answering
	// repository lists the root. This is `git worktree remove`.
	OrphanNotListed OrphanReason = "worktree_not_in_git"
	// OrphanPrunable: git still lists the root but marks it prunable, because
	// its directory is gone. This is `rm -rf` without `git worktree prune`.
	OrphanPrunable OrphanReason = "worktree_prunable"
	// OrphanDirectoryMissing: a worktree session no registered project
	// accounts for, whose own start directory is gone. Its name is derived
	// from that directory, which is the whole of its identity.
	OrphanDirectoryMissing OrphanReason = "worktree_directory_missing"
)

func RootOrphanReason added in v1.15.0

func RootOrphanReason(root RegisteredRoot, inventories []WorktreeInventory) OrphanReason

RootOrphanReason judges one registered root against every inventory. It is the git half of the decision, usable without a tmux listing.

type OrphanSession added in v1.15.0

type OrphanSession struct {
	// ProjectKey, ProjectRoot and ProjectPath are empty for an
	// OrphanDirectoryMissing session no registered project accounts for.
	ProjectKey, ProjectRoot, ProjectPath string
	// Root is the removed worktree the session was started in.
	Root        string
	Session     string
	SessionPath string
	Reason      OrphanReason
}

OrphanSession is one live worktree session with no worktree behind it.

type ProbeFunc

type ProbeFunc func(session string) Verdict

ProbeFunc answers "is this tmux session running?" for one session name.

type ReapObservation added in v1.11.0

type ReapObservation struct {
	// Server is the tmux server identity this pass observed. It is recorded
	// even when the pass is about to be skipped: a vanished server still
	// changes incarnation, and the tracker's reset must fire on that
	// transition rather than on the next non-empty listing.
	Server tmuxserver.Incarnation

	// Namespace is the tmux namespace this surface can see. An empty namespace
	// means the surface cannot say which server it is looking at, so nothing
	// is judged.
	Namespace string

	// Panes is one entry per pane in this cycle's listing, holding its session
	// name. It is the listing itself and not a deduplicated set of live
	// sessions, because an EMPTY listing is what the first guard triggers on: a
	// caller that filtered blank names out first could turn a listing that
	// existed into one that did not.
	Panes []string

	// ListingFailed reports that the pane listing errored rather than
	// answering. A failed listing is no evidence about anything.
	ListingFailed bool

	// Shells are the shell records in view this cycle. Callers filter their own
	// inventory down to shells before building this; the kind check needs their
	// types, the rest does not.
	Shells []Shell

	// Now is the clock the probe throttle is measured against. Zero means
	// time.Now.
	Now time.Time
}

ReapObservation is everything one refresh cycle knows, handed over whole so the guards can be applied here rather than re-derived per surface.

type ReapPlan added in v1.11.0

type ReapPlan struct {
	// Probes are the shells to take an independent second opinion on. The
	// caller runs them however its surface runs work — a tea.Cmd in the
	// browser, an inline call in the serve loop — and feeds each verdict back
	// through [ConfirmReap].
	Probes []ReapProbe

	// Skipped names the guard that stopped the pass, for tracing. Empty when
	// the pass ran. A surface that silently does nothing is indistinguishable
	// from one that decided nothing was dead, and those are very different
	// facts when a user asks why a row is still there.
	Skipped string
}

ReapPlan is what this cycle's evidence supports.

func PlanReap added in v1.11.0

func PlanReap(tracker *Tracker, obs ReapObservation) ReapPlan

PlanReap records this cycle's liveness and answers which shells to probe.

It mutates the tracker — that is what "record this cycle's liveness" means — but holds no state of its own, so the tracker is the caller's and the decision is identical on every surface.

type ReapProbe added in v1.11.0

type ReapProbe struct {
	Shell
	// Incarnation is the life of the tmux name at the moment of suspicion.
	Incarnation uint64
	// Server is the tmux server incarnation the suspicion was formed under.
	// Distinct from Incarnation, which is the life of the name.
	Server tmuxserver.Incarnation
}

ReapProbe names one shell whose absence is worth a second opinion, carrying the two identities the verdict will be fenced against.

type RegisteredRoot added in v1.15.0

type RegisteredRoot struct {
	ProjectKey, ProjectRoot string
	// ProjectPath is the project path exactly as registered. ProjectRoot is
	// canonical for comparison; ProjectPath is what state lookups match on.
	ProjectPath string
	// Root is canonical, resolved as far as the filesystem still allows.
	Root string
	// Sessions are the tmux names Sidecar may have started this worktree's
	// session under, most canonical first.
	Sessions []string
	// Missing reports that Root is gone while its parent is not. A root that
	// exists, or whose parent is also gone, gets no verdict.
	Missing bool
}

RegisteredRoot is a worktree Sidecar created and recorded for a project.

type Shell added in v1.11.0

type Shell struct {
	ProjectKey  string
	ProjectRoot string
	TmuxName    string
	Namespace   string
	// CreatedAt identifies the record, not the session. It fences the manifest
	// write: an entry rewritten since this observation is a different shell
	// wearing a reused name, and the conditional writer refuses it.
	CreatedAt time.Time
}

Shell is one manifest record a surface is asking about.

It is deliberately not workspaceinventory.Workspace. This package has to stay importable from the headless serve loop and from both UI surfaces, and these five fields are the whole of what the decision needs.

func LiveShells added in v1.11.0

func LiveShells(obs ReapObservation) []Shell

LiveShells reports the shells this observation saw running, so a caller can record their cold-restore eligibility.

It is derived from the same listing PlanReap already consumed rather than from a second tmux call, which is what keeps the marker free: the surfaces collect this listing for their own display every cycle. It returns nothing when the pass was skipped, because a listing that was not evidence of death is not evidence of life either.

type TmuxSession added in v1.15.0

type TmuxSession struct {
	Name string
	// Path is the session's start directory (#{session_path}), canonical.
	// Empty means tmux did not say, and an unknown directory proves nothing.
	Path string
	// PathMissing reports that Path no longer exists while its parent still
	// does. The parent check is what keeps an unmounted volume, where every
	// path is missing at once, from reading as a removed worktree.
	PathMissing bool
	// NameFromPath reports that Name is one of the names Sidecar derives from
	// Path, which is how a session that no registered project accounts for
	// proves it is a worktree session for that directory.
	NameFromPath bool
	// PanePathsMissing is positive evidence that every pane's absolute current
	// directory is missing while its parent exists. Blank, unreadable, or
	// incomplete pane evidence leaves this false and cannot justify a prune.
	PanePathsMissing bool
}

TmuxSession is one entry of the session listing.

type Tracker

type Tracker struct {

	// Confirmations and ProbeInterval default to the constants above when zero.
	Confirmations int
	ProbeInterval time.Duration
	// contains filtered or unexported fields
}

Tracker remembers, per tmux session, what a surface has observed. It holds no tmux handles and starts no goroutines, so constructing one costs nothing and it is safe to build during plugin construction.

Liveness is a joint property of a shell and the tmux server incarnation it was seen on. ObserveServer is how a surface tells the tracker which server it is currently watching; a transition (Equal reports false) invalidates every prior sighting.

func NewTracker

func NewTracker() *Tracker

NewTracker returns an empty tracker with default policy.

func (*Tracker) Confirm

func (t *Tracker) Confirm(name string, verdict Verdict, incarnation uint64, server tmuxserver.Incarnation) bool

Confirm folds one probe verdict in and reports whether the shell should now be closed. Alive and Unknown both clear the count, so a session that flickers out of reach is never condemned by accumulation.

incarnation is the name-life this verdict was taken about (see Incarnation). server is the tmux server incarnation it was taken under. A mismatch on either is a refuse: the name may have been recreated, or the whole server may have been replaced, and in both cases the verdict is about a world that no longer exists. Equal, not ==, is the server predicate.

func (*Tracker) Forget

func (t *Tracker) Forget(name string)

Forget drops all state for a session, for use when a shell is closed by any other route so a later reuse of the name starts clean.

func (*Tracker) Incarnation

func (t *Tracker) Incarnation(name string) uint64

Incarnation identifies the current life of a tmux name. A caller reads it when it starts confirming a death and hands it back to Confirm, which is what makes a verdict that was overtaken by a resurrection unusable rather than merely late (td-6a4100).

func (*Tracker) Observe

func (t *Tracker) Observe(name string)

Observe records positive evidence that the session is running — a listing that included it, a capture that succeeded, or a creation that just made it. It clears any accumulated suspicion: a session that answered is not dying. A surface must call it before a probe of that session can ever close a shell.

func (*Tracker) ObserveServer added in v1.6.0

func (t *Tracker) ObserveServer(inc tmuxserver.Incarnation)

ObserveServer records the tmux server this tracker is currently watching.

When inc is not Equal to the tracked incarnation, seenAlive is cleared and every gone count is reset on every entry. After a restart no shell has been seen alive under the current server, so ShouldProbe is false and Confirm cannot fire. Shells that are still there get re-observed by the next discovery pass and re-enter seenAlive legitimately.

The reset fires on the transition, not only at construction: a Sidecar instance running outside tmux survives a server restart and must observe it live. Equal is the predicate — == is field-wise and treats an unspecified pid (0) as a different server from the same socket with pid filled in.

func (*Tracker) SeenAlive

func (t *Tracker) SeenAlive(name string) bool

SeenAlive reports whether this tracker ever observed the session running.

It is the gate that separates "a shell died while Sidecar watched" from "a manifest entry that was already cold when Sidecar started". The second is what survives a reboot and what the offline-shell recreate path exists for, and auto-close must not eat it.

func (*Tracker) Server added in v1.6.0

func (t *Tracker) Server() tmuxserver.Incarnation

Server is the last incarnation ObserveServer recorded. The zero value is Unknown: this tracker has not yet been told which server it is watching.

func (*Tracker) ShouldProbe

func (t *Tracker) ShouldProbe(name string, now time.Time) bool

ShouldProbe reports whether a probe for this session is due: the tracker must have seen the session alive, and no probe may have run inside the throttle window. It records the attempt.

The liveness half of that gate is the whole safety property, so it lives here rather than in each surface. The project plugin used to substitute "this row has an Agent", which reads as liveness but is not: the nested sibling projection synthesises an Agent for rows whose tmux server this instance cannot even see. One gate, one meaning, both surfaces.

type Verdict

type Verdict int

Verdict is what the evidence supports, not what is true.

const (
	// Unknown means the evidence cannot distinguish a dead session from an
	// unreachable tmux. It is the safe default and must never close a shell.
	Unknown Verdict = iota
	// Alive means tmux positively listed the session.
	Alive
	// Gone means tmux answered, and its answer did not include the session.
	Gone
)

func ProbeSession

func ProbeSession(session string) Verdict

ProbeSession asks tmux for its full session list and compares names exactly.

`has-session -t name` is the obvious call and the wrong one: tmux target resolution falls back to prefix and pattern matching, so it answers about a session the caller did not name. A listing compared with == cannot do that. A listing also fails honestly — if tmux cannot answer at all, including when no server is running, the verdict is Unknown and no shell is closed.

func (Verdict) String

func (v Verdict) String() string

type WorktreeInventory added in v1.15.0

type WorktreeInventory struct {
	ProjectRoot string
	// Answered reports that git produced a listing. False is not "empty": it is
	// no evidence at all.
	Answered  bool
	Worktrees []ListedWorktree
}

WorktreeInventory is one repository's worktree listing.

Jump to

Keyboard shortcuts

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