session

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: AGPL-3.0 Imports: 27 Imported by: 0

Documentation

Overview

Package session owns the core domain: a running AI coding agent represented by the Instance type.

An Instance moves through a small lifecycle — Ready → Loading → Running → Paused (and optionally Killed) — coordinating with neighbouring packages at each stage: session/git for worktree creation and cleanup, session/tmux for the PTY that drives the agent, and session/agent for program-specific behaviour such as trust-prompt handling and recovery flags.

Persistence lives in storage.go and is versioned via CurrentSchemaVersion; when the on-disk InstanceData schema changes, bump the constant and add an upgrade step in storage_migrate.go. State transitions are validated through Instance.TransitionTo; disallowed edges return an error rather than silently mutating.

Index

Constants

View Source
const CurrentSchemaVersion = 6

CurrentSchemaVersion is the schema version written by the current binary. Any on-disk InstanceData with a lower SchemaVersion is routed through storage_migrate.go's Migrate before use.

View Source
const HeadroomProxyURL = "http://127.0.0.1:8787"

HeadroomProxyURL is the base URL Loom points ANTHROPIC_BASE_URL at when the Headroom Proxy launch option is enabled — Headroom's own default proxy address (`headroom proxy`, port 8787). Loom does not start or manage the proxy process itself; the user is expected to have it running already (e.g. via `headroom install`'s persistent deployment).

Variables

View Source
var ErrInstanceNotFound = errors.New("instance not found")

ErrInstanceNotFound signals that a storage mutation (delete, update) referenced a title that is no longer persisted. Callers performing idempotent cleanup — e.g. the kill path, where Kill() has already destroyed tmux + worktree before DeleteInstance runs — can match it with errors.Is to distinguish "already gone" from a real write error.

View Source
var ErrStorageLoadFailed = errors.New("instance storage could not be read; refusing to overwrite it")

ErrStorageLoadFailed signals that a write was refused because the persisted instance payload could not be decoded as a whole (not a JSON array). Writing anyway would replace records this Storage never saw with whatever the caller holds — usually nothing. The latch clears on the next successful load, or on DeleteAllInstances (the explicit wipe).

Functions

func BuildEffortCommand added in v0.6.0

func BuildEffortCommand(program, effort string) string

BuildEffortCommand modifies a program command string to launch with the given --effort value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without an effort-level concept or when effort is "" / "default".

func BuildLoomContextCommand added in v0.13.0

func BuildLoomContextCommand(program, filePath string) string

BuildLoomContextCommand returns program with Claude's --append-system-prompt-file flag pointing at filePath. The adapter registry no-ops for non-Claude programs.

func BuildModelCommand added in v0.5.0

func BuildModelCommand(program, model string) string

BuildModelCommand modifies a program command string to launch with the given --model value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without a model-selection concept or when model is "" / "default".

func BuildPermissionModeCommand added in v0.4.0

func BuildPermissionModeCommand(program, mode string) string

BuildPermissionModeCommand modifies a program command string to launch with the given --permission-mode value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without a permission-mode concept or when mode is "" / "default".

func BuildRecoveryCommand

func BuildRecoveryCommand(program string) string

BuildRecoveryCommand modifies a program command string for crash recovery. The adapter registry decides whether and how the string is modified (e.g. "claude" → "claude --continue"). Unsupported agents are returned unchanged.

func BuildRemoteControlCommand added in v0.3.0

func BuildRemoteControlCommand(program, sessionName string) string

BuildRemoteControlCommand modifies a program command string to launch the agent with its remote-control mode enabled, naming the remote session after sessionName. The adapter registry decides whether and how the string is modified (e.g. "claude" → "claude --remote-control <name>"). Idempotent, and a no-op for agents without a remote-control mode.

func BuildSettingsCommand added in v0.13.0

func BuildSettingsCommand(program, path string) string

BuildSettingsCommand returns program with Claude's --settings flag pointing at path. The adapter registry no-ops for non-Claude programs.

func CacheTTL1hEnv added in v0.6.0

func CacheTTL1hEnv(enabled bool, program string) []string

CacheTTL1hEnv returns the tmux session environment variable that extends Claude's prompt cache from the default 5-minute TTL to 1 hour. A no-op (nil) unless enabled and program resolves to Claude — ENABLE_PROMPT_CACHING_1H is a Claude-CLI-specific toggle, so setting it for any other agent wouldn't do anything useful.

func CheckTmuxAlive

func CheckTmuxAlive(sessionTitle string, cmdExec internalexec.Executor) bool

CheckTmuxAlive checks if a tmux session exists by its sanitized name. A probe killed at its deadline is not evidence of death: under load `tmux has-session` can simply take too long while the session is perfectly healthy. Reading that as "gone" maps to ActionRestart, which then tries to create a session that already exists ("duplicate session"). So retry once, and if tmux still has not answered, assume alive — a wrong "alive" costs a failed restore, while a wrong "dead" tears down a running agent's session.

func CheckWorktreeExists

func CheckWorktreeExists(worktreePath string) bool

CheckWorktreeExists checks if the worktree directory exists on disk.

func ClaudeFullscreenEnv added in v0.13.0

func ClaudeFullscreenEnv(program string) []string

ClaudeFullscreenEnv returns the tmux session environment variable that forces Claude's fullscreen (alternate-screen) renderer. Unconditional for Claude, a no-op (nil) for every other program.

Loom cannot scroll Claude's classic inline renderer: it wraps every frame in synchronized output (DEC 2026), so tmux repaints Loom's attach client instead of scrolling it and the pane emulator never accumulates scrollback (TestSyncOutputDefeatsEmulatorScrollback_RealTmux). On the alternate screen Loom forwards the wheel into Claude, which scrolls its own transcript. The env var (not --settings) keeps `/tui default` usable per session: Claude drops CLAUDE_CODE_NO_FLICKER when it relaunches for a renderer switch.

func HeadroomProxyEnv added in v0.6.0

func HeadroomProxyEnv(enabled bool, program string) []string

HeadroomProxyEnv returns the tmux session environment variables needed to route program's API calls through Headroom's proxy. A no-op (nil) unless enabled and program resolves to Claude — ANTHROPIC_BASE_URL is Anthropic-API-specific, so setting it for any other agent wouldn't do anything useful.

func HumanizeBranchLeaf added in v0.1.3

func HumanizeBranchLeaf(branch string) string

HumanizeBranchLeaf turns a branch name into a plausible display title by taking the last `/`-segment and replacing dashes with spaces. e.g. "aidanb/example-jupyter-notebook" → "example jupyter notebook". This is the lossy fallback used when the original title is unrecoverable; users can rename via the existing rename flow if the auto-derived title is wrong.

func InstanceEnv added in v0.6.0

func InstanceEnv(program string, headroomProxy, cacheTTL1h bool) []string

InstanceEnv combines every per-session environment variable derived from an instance's launch options (Headroom Proxy, Cache TTL) plus the always-on Claude fullscreen renderer into the single slice tmux.NewTmuxSession's variadic env parameter needs. Centralized here so the four Instance call sites that construct a TmuxSession don't each repeat the same combination.

func IsAllowedTransition

func IsAllowedTransition(from, to Status) bool

IsAllowedTransition reports whether from → to is permitted by the Status state machine. Self-transitions are always allowed.

func IsClaudeProgram added in v0.3.0

func IsClaudeProgram(program string) bool

IsClaudeProgram reports whether program launches the Claude Code agent (matching by binary basename, so absolute paths and trailing flags still resolve). Used to scope remote-control behavior to Claude sessions.

func KillOwnedTmuxSession added in v0.13.0

func KillOwnedTmuxSession(title string, scope SweepScope, cmdExec internalexec.Executor) (bool, error)

KillOwnedTmuxSession kills the tmux session of the instance titled title, but only when its start directory lies in a root scope owns, by the same test the orphan sweep applies (see CleanupOrphanedSessions). The server is shared: another loom's session can carry the same title, and killing it on the strength of the name alone would take down that loom's agent. It fails closed: a listing that cannot be read, or a session starting anywhere scope does not own, is an error and nothing is killed. It reports whether it killed a session; no such session (or no server) is (false, nil).

func KillTmuxSessionByTitle

func KillTmuxSessionByTitle(title string, cmdExec internalexec.Executor) error

KillTmuxSessionByTitle kills the tmux session matching title's sanitized name. Best-effort: returns the command error if any (commonly a benign "session not found"), which most callers can ignore. Used to clear orphan sessions left over from a prior crash before reusing the title.

func NewNotice added in v0.13.0

func NewNotice(errs ...error) error

NewNotice wraps the non-nil errs in a Notice, or returns nil if there are none.

func QueryClaudeRoster added in v0.13.0

func QueryClaudeRoster(program string, runner internalexec.Executor) (map[string]RosterEntry, error)

QueryClaudeRoster runs `claude agents --json` and returns the live sessions keyed by working directory, which is how Loom joins them to instances (an instance's GetWorktreePath is the cwd Claude was launched in). The CLI lists every live session on the machine — ordinary interactive ones, not just `--bg` ones — so Loom's own tmux-hosted agents appear in it. Only interactive sessions are returned: a Loom instance is always one, and background sessions publish `state` rather than the `status` this package reads.

Returns an empty map and no error for non-Claude programs — callers can invoke it unconditionally. A missing subcommand, a hung CLI, or output this build cannot parse is an error: the caller logs it and keeps using pane-content detection.

func RemoveOrphanWorktree added in v0.3.0

func RemoveOrphanWorktree(repoPath, worktreePath string) error

RemoveOrphanWorktree removes an orphaned worktree directory while preserving its branch (git worktree remove -f deletes the working tree but never the branch). Used to auto-clean stale leftovers during reconciliation. -f is required because the worktree may hold tracked edits we have already decided to discard, or git may consider it dirty.

func SanitizedToTmuxName added in v0.1.3

func SanitizedToTmuxName(title string) string

SanitizedToTmuxName mirrors tmux.ToLoomTmuxName. Re-exporting the computation here keeps orphan discovery self-contained — callers don't have to reach into the tmux package directly.

func SetLoomContextEnabled added in v0.13.0

func SetLoomContextEnabled(enabled bool)

SetLoomContextEnabled updates the global loom-context toggle.

func SetSubagentTrackingEnabled added in v0.13.0

func SetSubagentTrackingEnabled(enabled bool)

SetSubagentTrackingEnabled updates the global subagent-tracking toggle.

func SubagentHooksDir added in v0.13.0

func SubagentHooksDir(configDir, title string) string

SubagentHooksDir returns the hooks folder for the instance titled title, a direct child of the hooks root. It is keyed by tmux session name (see hooksFolderName), so workspace terminals, which have no worktree, get one too.

func SweepSubagentHooks added in v0.13.0

func SweepSubagentHooks(configDir string, claimedTitles map[string]bool, cmdExec internalexec.Executor)

SweepSubagentHooks removes hooks folders under configDir that no instance claims and whose tmux session is not running. claimedTitles holds the title of every instance in the workspace. If tmux cannot be queried, nothing is removed, so a folder in use by a live session, such as one owned by another loom process, is never deleted on a guess.

func WorkspaceSweepRoots added in v0.13.0

func WorkspaceSweepRoots(repoPath, configDir string) []string

WorkspaceSweepRoots returns the directories a workspace's sessions start in: repoPath (its workspace terminal; the global context has none, so it passes "") and configDir's worktrees directory (every other session). An empty configDir means the default config dir, as for worktree creation.

func WriteLoomContextFiles added in v0.13.0

func WriteLoomContextFiles(configDir string) error

WriteLoomContextFiles writes both embedded prompt files into configDir, (re)writing a file only when it is missing or its bytes differ from the embedded content (so a loom upgrade refreshes the prose automatically). A no-op when configDir is empty.

Types

type AgentPane added in v0.13.0

type AgentPane struct {
	// contains filtered or unexported fields
}

AgentPane is the I/O and probe surface of an instance's agent pane: screen and scroll-back reads, keystrokes, paste and forwarded mouse/focus events, content/status probes, and tmux/PTY liveness. Each method keeps the guard it had as an Instance method: started and not paused for screen/input (SendKeysRaw and SendPrompt check only started), started for the status probes, and only "has a tmux session" for the liveness probes and HasEmulator. So on an instance with no live pane each is the same no-op, zero value or error as before.

It is a cheap value wrapper around the *Instance: take one with inst.Pane() at the call site rather than storing it. Instance itself keeps lifecycle, persistence, diff/git and attention state.

func (AgentPane) CaptureAndProcessStatus added in v0.13.0

func (p AgentPane) CaptureAndProcessStatus() (updated bool, hasPrompt bool, err error)

CaptureAndProcessStatus captures tmux pane content once and checks for trust prompts and content updates. Avoids duplicate CapturePaneContent calls. Returns a non-nil err when the underlying capture failed — previously the error was swallowed inside tmux.CaptureAndProcess and surfaced only in the log file, so callers saw "no updates" instead of a genuine capture failure.

func (AgentPane) CaptureHistory added in v0.13.0

func (p AgentPane) CaptureHistory() (string, bool)

CaptureHistory returns the agent pane's full tmux buffer (scrollback + visible screen) for windowed scroll-back, or ("",false) if unavailable.

func (AgentPane) CursorState added in v0.13.0

func (p AgentPane) CursorState() (vt.Cursor, bool)

CursorState returns the agent pane's live cursor state, or ok=false when the instance has no running emulator-backed session.

func (AgentPane) EmulatorScreen added in v0.13.0

func (p AgentPane) EmulatorScreen() (string, bool)

EmulatorScreen returns the current visible screen from the in-process VT emulator, or ok=false when the instance is not started, is paused, or has no emulator wired (snapshot path / Windows). Unlike Preview it performs no subprocess work — no tmux has-session liveness probe and no capture-pane fallback — so it is safe to call once per visible card per render frame (the rail's card tails). Two deliberate trade-offs versus Preview: a just-died session may serve one stale screen (the dead-event path handles liveness), and the snapshot path yields no tail at all rather than degrading to a per-frame capture-pane fork (cards fall back to their status label instead).

func (AgentPane) ForwardFocus added in v0.13.0

func (p AgentPane) ForwardFocus(in bool)

ForwardFocus forwards a host focus in/out event to the agent pane, gated on the app having enabled focus reporting. Errors are logged, not returned — focus is best-effort.

func (AgentPane) ForwardMouse added in v0.13.0

func (p AgentPane) ForwardMouse(cb, col, row int, press bool) error

ForwardMouse forwards one SGR mouse event (click/drag/release) to the agent's pane at (col,row). No-op for non-started/paused instances.

func (AgentPane) ForwardWheel added in v0.13.0

func (p AgentPane) ForwardWheel(up bool, n int) error

ForwardWheel forwards n mouse-wheel events (up or down) to the agent's pane so a TUI agent scrolls its own view. No-op for non-started/paused instances.

func (AgentPane) GetContentHash added in v0.13.0

func (p AgentPane) GetContentHash() []byte

GetContentHash returns the content hash of the last captured tmux pane.

func (AgentPane) HasEmulator added in v0.13.0

func (p AgentPane) HasEmulator() bool

HasEmulator reports whether this instance's pane renders through the in-process emulator (event-driven path).

func (AgentPane) HasUpdated added in v0.13.0

func (p AgentPane) HasUpdated() (updated bool, hasPrompt bool)

HasUpdated reports whether the tmux pane content has changed since the last call and whether an auto-yes-eligible prompt is currently visible. Returns (false, false) for non-started instances.

func (AgentPane) IsAlternateScreen added in v0.13.0

func (p AgentPane) IsAlternateScreen() bool

IsAlternateScreen reports whether the agent is a full-screen TUI on the alternate screen (no tmux scrollback). Scroll-back for such agents must be forwarded into the app via ForwardWheel rather than windowed from history.

func (AgentPane) PaneTitle added in v0.13.0

func (p AgentPane) PaneTitle() (string, bool)

PaneTitle returns the agent's OSC-set window title, or ok=false.

func (AgentPane) Paste added in v0.13.0

func (p AgentPane) Paste(text string) error

Paste sends text to the agent's pane as a bracketed paste. No-op for non-started/paused instances.

func (AgentPane) Preview added in v0.13.0

func (p AgentPane) Preview() (string, error)

Preview returns the current visible tmux pane content. Returns empty string (not an error) when the instance is not started or paused — the live tail is only meaningful for running sessions.

func (AgentPane) PtmxAlive added in v0.13.0

func (p AgentPane) PtmxAlive() bool

PtmxAlive reports whether the instance's tmux session currently has an attached PTY. TmuxAlive can be true (the session exists on the server) while this is false — e.g. a reattach failed after a full-screen attach returned — leaving every keystroke/resize on this instance silently fail forever with no periodic check ever noticing, since TmuxAlive is the only thing the metadata tick otherwise watches. See RepairPtmx.

func (AgentPane) RepairPtmx added in v0.13.0

func (p AgentPane) RepairPtmx() error

RepairPtmx re-attaches this instance's tmux session PTY. Intended for the metadata tick to call when it observes TmuxAlive()==true but PtmxAlive()==false: the session is healthy but Loom's own handle to it is gone, and nothing else will ever retry the attach. A no-op error if there is no tmux session at all.

func (AgentPane) SendKeys added in v0.13.0

func (p AgentPane) SendKeys(keys string) error

SendKeys sends keys to the tmux session

func (AgentPane) SendKeysRaw added in v0.13.0

func (p AgentPane) SendKeysRaw(b []byte) error

SendKeysRaw writes raw bytes to the tmux PTY. Used by inline attach mode.

func (AgentPane) SendPrompt added in v0.13.0

func (p AgentPane) SendPrompt(prompt string) error

SendPrompt sends a prompt to the tmux session

func (AgentPane) SetPreviewSize added in v0.13.0

func (p AgentPane) SetPreviewSize(width, height int) error

SetPreviewSize resizes the detached tmux pane so capture output matches the preview viewport. Returns an error if the instance is not running; paused instances have no live pane to resize.

func (AgentPane) TapEnter added in v0.13.0

func (p AgentPane) TapEnter()

TapEnter sends a single Enter keystroke to the tmux session when the instance is running. No-op otherwise. Exposed to Lua scripts as inst:tap_enter().

func (AgentPane) TmuxAlive added in v0.13.0

func (p AgentPane) TmuxAlive() bool

TmuxAlive returns true if the tmux session is alive. This is a sanity check before attaching.

func (AgentPane) TmuxLiveness added in v0.13.0

func (p AgentPane) TmuxLiveness() tmux.Liveness

TmuxLiveness reports the session's liveness, distinguishing "tmux answered no" from "the probe never got an answer". Callers that change an instance's state on a negative must use this rather than TmuxAlive, which collapses both cases into false.

func (AgentPane) TmuxSessionName added in v0.13.0

func (p AgentPane) TmuxSessionName() string

TmuxSessionName returns the sanitized tmux session name backing this instance, or "" when no session is attached. Pane events carry this name.

type DiffStatsData

type DiffStatsData struct {
	Added   int    `json:"added"`
	Removed int    `json:"removed"`
	Content string `json:"content"`
}

DiffStatsData represents the serializable data of a DiffStats

type GitWorktreeData

type GitWorktreeData struct {
	RepoPath         string `json:"repo_path"`
	WorktreePath     string `json:"worktree_path"`
	SessionName      string `json:"session_name"`
	BranchName       string `json:"branch_name"`
	BaseCommitSHA    string `json:"base_commit_sha"`
	IsExistingBranch bool   `json:"is_existing_branch"`
	// StashRef is the commit SHA of a pending git stash created by
	// Instance.Pause for this worktree's uncommitted changes, or ""
	// if none is pending (nothing was dirty at pause time, or Resume
	// already applied and cleared it). Added in schema v3.
	StashRef string `json:"stash_ref,omitempty"`
}

GitWorktreeData represents the serializable data of a GitWorktree

type Instance

type Instance struct {
	// Title is the title of the instance.
	Title string
	// Path is the path to the workspace.
	Path string
	// Branch is the branch of the instance.
	Branch string
	// Status is the status of the instance.
	Status Status

	// Height is the height of the instance.
	Height int
	// Width is the width of the instance.
	Width int
	// CreatedAt is the time the instance was created.
	CreatedAt time.Time
	// UpdatedAt is the time the instance was last updated.
	UpdatedAt time.Time

	// ConfigDir is the workspace config directory for worktree resolution.
	ConfigDir string
	// IsWorkspaceTerminal is true if this instance operates in the root repo without a worktree.
	IsWorkspaceTerminal bool
	// contains filtered or unexported fields
}

Instance is a single agent session managed by Loom. Each Instance owns a git worktree (or, for workspace terminals, targets the root repo) and a tmux session where the agent command runs. Instances move through the Status state machine — Ready → Loading → Running → Paused → Deleting — governed by allowedTransitions; use TransitionTo for every status write.

Field access rules: mu guards Status, diffStats, Branch, tmuxSession, gitWorktree, the started/starting flags, and the launch fields (program, headroomProxy, cacheTTL1h, prompt, crashRecovered). External callers must go through the exported accessors (GetStatus, GetBranch, GetDiffStats, Snapshot, TmuxSession, Program/SetProgram, SetLaunchOptions, Prompt/ SetPrompt, …) or the unexported get*/set* helpers — never read or write those fields directly. Holding mu across I/O is forbidden, and so is calling a locking accessor while holding it: sync.RWMutex is not reentrant, so session code that already holds mu reads the private fields instead.

Lifecycle entry points: NewInstance creates a blank instance (call Start(true) to materialize worktree + tmux). FromInstanceData rehydrates persisted state and does not spawn a PTY — callers must invoke EnsureRunning to bring a non-paused instance back online.

func FromInstanceData

func FromInstanceData(data InstanceData, configDir string) (*Instance, error)

FromInstanceData creates a new Instance from serialized data without spawning a tmux PTY attachment. Paused instances are constructed fully (started=true, TmuxSession object present, no PTY — matches their on-disk shape). Non-paused instances are returned with started=false; the caller must invoke EnsureRunning to attach the PTY. configDir is injected for workspace-scoped worktree resolution.

func NewInstance

func NewInstance(opts InstanceOptions) (*Instance, error)

NewInstance constructs a blank Instance in the Ready state. No git worktree or tmux session is allocated until Start(true) runs — this constructor only captures the caller's intent. The workspace path is resolved to an absolute path so worktree setup is not affected by later chdir calls.

func ReconcileAndRestore

func ReconcileAndRestore(data InstanceData, configDir string, cmdExec internalexec.Executor) (*Instance, error)

ReconcileAndRestore loads an instance from serialized data, checks the health of its tmux session and worktree, and takes the appropriate recovery action.

func (*Instance) ApplySubagentScan added in v0.13.0

func (i *Instance) ApplySubagentScan(res subagent.Result) bool

ApplySubagentScan applies one scan result and reports whether it was applied. A result for another launch is dropped. An instance restored after a loom restart has no launch ID yet and adopts the result's. A replayed result rebuilds the tracker from scratch, and an incremental one is only applied once the tracker is warm.

func (*Instance) BellPending added in v0.8.0

func (i *Instance) BellPending() bool

BellPending reports whether an unseen bell is pending for this instance.

func (*Instance) BranchPrefixOverride added in v0.13.0

func (i *Instance) BranchPrefixOverride() *string

BranchPrefixOverride returns the per-session branch prefix override, or nil when none was set and the configured prefix applies.

func (*Instance) CacheTTL1h added in v0.6.0

func (i *Instance) CacheTTL1h() bool

CacheTTL1h reports whether launches set ENABLE_PROMPT_CACHING_1H=1 (see CacheTTL1hEnv). Set via SetLaunchOptions.

func (*Instance) CrashRecovered

func (i *Instance) CrashRecovered() bool

CrashRecovered reports whether this instance was restored after a crash and still needs CrashRestart (an agent-aware relaunch, e.g. --continue). Runtime-only: never serialized.

func (*Instance) CrashRestart

func (i *Instance) CrashRestart() error

CrashRestart starts a new tmux session for a crash-recovered instance. The worktree already exists (for regular instances) or is unnecessary (for workspace terminals). The program is modified with --continue for supported agents.

Like Resume, it relaunches only into an intact worktree. Reconcile picks this path because the directory exists, but a gutted one has no .git, so git run inside it would answer for whatever repo encloses it (the workspace's own, when worktrees live under <repo>/.loom). Callers mark a failed restart Paused, and Resume then rebuilds a gutted tree with its leftovers moved aside.

func (*Instance) EnsureRunning

func (i *Instance) EnsureRunning() error

EnsureRunning attaches a PTY to the instance's tmux session, restoring any previously-persisted session state. A no-op for paused instances (they deliberately have no PTY) and for already-started instances. Idempotent: the underlying Start guards against double-attaches.

func (*Instance) ForgetSubagentsWithoutHooks added in v0.13.0

func (i *Instance) ForgetSubagentsWithoutHooks()

ForgetSubagentsWithoutHooks drops the tracked agents of a launch whose hooks folder has disappeared, which a scan reports as subagent.ErrNoHooks: the folder was deleted by hand, or by another loom process's sweep. Without it the last rows would stay on screen until the next launch. It acts only when hookLaunchID is a real launch ID: for an instance restored after a loom restart ("", nothing adopted yet) or launched without hooks (noHooksLaunchID), ErrNoHooks is the normal state. hookLaunchID itself is kept, so a folder written by another launch is still never adopted. Call it on the Update goroutine.

func (*Instance) GetBranch

func (i *Instance) GetBranch() string

GetBranch returns the branch name under a read lock. Safe to call concurrently with UpdateDiffStats* for workspace terminals, which refresh Branch on every tick.

func (*Instance) GetDiffStats

func (i *Instance) GetDiffStats() *git.DiffStats

GetDiffStats returns the current git diff statistics

func (*Instance) GetGitWorktree

func (i *Instance) GetGitWorktree() (*git.GitWorktree, error)

GetGitWorktree returns the git worktree for the instance

func (*Instance) GetStatus

func (i *Instance) GetStatus() Status

GetStatus returns the current status under a read lock.

func (*Instance) GetWorktreePath

func (i *Instance) GetWorktreePath() string

GetWorktreePath returns the worktree path for the instance, or empty string if unavailable. For workspace terminals, returns the root repo path.

func (*Instance) GitHubState added in v0.13.0

func (i *Instance) GitHubState() github.State

GitHubState returns the last joined GitHub state for this session.

func (*Instance) HeadroomProxy added in v0.6.0

func (i *Instance) HeadroomProxy() bool

HeadroomProxy reports whether launches point ANTHROPIC_BASE_URL at Headroom's proxy (see HeadroomProxyEnv). Set via SetLaunchOptions.

func (*Instance) IssueNumber added in v0.13.0

func (i *Instance) IssueNumber() int

IssueNumber returns the linked GitHub issue, or 0.

func (*Instance) Kill

func (i *Instance) Kill() (err error)

Kill terminates the instance and cleans up all resources. A stash entry it cannot drop does not fail the kill (everything else is gone): Kill then returns a Notice carrying DropStash's error, which says what is left on the stash list.

func (*Instance) Pane added in v0.13.0

func (i *Instance) Pane() AgentPane

Pane returns the agent pane's I/O and probe surface. It is never nil — a value wrapping i — and each of its methods applies its own guard.

func (*Instance) Parity added in v0.13.0

func (i *Instance) Parity() (ahead, behind int, ok bool)

Parity returns commits ahead/behind the base branch; ok is false when no count has succeeded yet.

func (*Instance) Pause

func (i *Instance) Pause(saveState func() error) (err error)

Pause stops the tmux session and removes the worktree, preserving the branch. If saveState is non-nil, it is called after committing changes and marking the instance as Paused, providing a checkpoint that reduces the crash inconsistency window.

func (*Instance) Paused

func (i *Instance) Paused() bool

Paused reports whether the instance is currently in the Paused state (can be resumed with Resume). A real Pause removed the worktree, but an agent that exited on its own is marked Paused with its worktree still on disk; see decideResume.

func (*Instance) Program

func (i *Instance) Program() string

Program returns the agent command this instance launches (the bare program, before loom's context flag and subagent hooks are added).

func (*Instance) Prompt

func (i *Instance) Prompt() string

Prompt returns the initial prompt still waiting to be sent to the agent, or "" when there is none (or it has already been sent).

func (*Instance) RecordRestartFailure added in v0.7.0

func (i *Instance) RecordRestartFailure() int

RecordRestartFailure increments and returns the consecutive-failure counter backing the workspace-terminal auto-restart circuit breaker. Call once per metadata tick this instance's tmux is observed dead.

func (*Instance) RepoName

func (i *Instance) RepoName() (string, error)

RepoName returns the human-visible repo/workspace name, delegating to the instance's backend. Errors if called before the instance has been started.

func (*Instance) ResetRestartFailures added in v0.7.0

func (i *Instance) ResetRestartFailures()

ResetRestartFailures clears the consecutive-failure counter. Call once per metadata tick this instance's tmux is observed alive.

func (*Instance) Restart added in v0.1.3

func (i *Instance) Restart() error

Restart brings an instance back online after its tmux session died out-of-band (e.g. a workspace terminal whose shell the user exited, or the tmux server was killed). Start(true) alone is a silent no-op on an already-started instance because reserveStart sees started=true and bails — that is the correct INST-04 behavior for a concurrent Start race, but the wrong behavior when the caller knows the tmux session is gone and wants to recreate it. Restart clears the flags first so Start can run its real path.

A restart is a real launch: the dead session object is closed and replaced by one running a command freshly composed by launchProgram, so the previous launch's subagent state and hooks folder are reset, new hooks are prepared, and the loom context flag is re-applied. Reusing the old object would relaunch its old command — for a session restored after a loom restart, the bare Program, with no hooks or context at all — while the tracker kept the dead process's rows.

func (*Instance) RestartFailureCount added in v0.7.0

func (i *Instance) RestartFailureCount() int

RestartFailureCount reports the current consecutive-failure count.

func (*Instance) Resume

func (i *Instance) Resume(saveState func() error) (err error)

Resume brings a Paused instance back to Running. It recreates the worktree from the branch only when the worktree is absent or gutted; an intact one is kept as it is and the agent relaunched in it, and a live session is reattached (see decideResume). Stashed changes are restored either way. If saveState is non-nil, it is called after the instance is Running, providing a checkpoint that reduces the crash inconsistency window.

A resume that succeeded but forgot a stash no longer in `git stash list`, or restored one it then could not drop, returns a Notice saying so (see OnlyNotice); a failed one includes those notices in its error.

func (*Instance) SetBellPending added in v0.8.0

func (i *Instance) SetBellPending(v bool)

SetBellPending sets or clears the pending-bell attention flag.

func (*Instance) SetBranchPrefix added in v0.13.0

func (i *Instance) SetBranchPrefix(prefix string)

SetBranchPrefix overrides the configured branch prefix for this instance. Call before Start(true); it has no effect afterwards, since the branch name is composed during first-time setup and fixed from then on.

func (*Instance) SetCrashRecovered added in v0.13.0

func (i *Instance) SetCrashRecovered(v bool)

SetCrashRecovered sets the crash-recovered flag; the app clears it once it has attempted CrashRestart.

func (*Instance) SetGitHubState added in v0.13.0

func (i *Instance) SetGitHubState(s github.State)

SetGitHubState records the poller's join result.

func (*Instance) SetIssue added in v0.13.0

func (i *Instance) SetIssue(n int)

SetIssue links this session to a GitHub issue (0 unlinks).

func (*Instance) SetLaunchOptions added in v0.13.0

func (i *Instance) SetLaunchOptions(program string, headroomProxy, cacheTTL1h bool)

SetLaunchOptions sets the program and both launch-env toggles under one lock, so no reader (Snapshot, a launch in a Cmd goroutine) can observe a program from one confirmation paired with toggles from another. Like SetProgram, it takes effect at the next launch.

func (*Instance) SetProgram added in v0.13.0

func (i *Instance) SetProgram(program string)

SetProgram replaces the agent command. It takes effect at the next launch (Start, Resume, CrashRestart, Restart); a running session keeps the command it was started with.

func (*Instance) SetPrompt added in v0.13.0

func (i *Instance) SetPrompt(prompt string)

SetPrompt sets the initial prompt sent once the instance has started. Pass "" to clear it after sending.

func (*Instance) SetSelectedBranch

func (i *Instance) SetSelectedBranch(branch string)

SetSelectedBranch sets the branch to use when starting the instance.

func (*Instance) SetTitle

func (i *Instance) SetTitle(title string) error

SetTitle sets the title of the instance. Returns an error if the instance has started. We cant change the title once it's been used for a tmux session etc.

func (*Instance) SetTmuxSession

func (i *Instance) SetTmuxSession(session *tmux.TmuxSession)

SetTmuxSession sets the tmux session for testing purposes

func (*Instance) SetWaitReason added in v0.13.0

func (i *Instance) SetWaitReason(reason string)

SetWaitReason records (or with "" clears) Claude's reason for blocking.

func (*Instance) ShouldRefreshDiff

func (i *Instance) ShouldRefreshDiff(tmuxUpdated, wantFull bool) bool

ShouldRefreshDiff reports whether a metadata tick needs to re-run the diff backend for this instance. It returns true when:

  • the instance has no cached diff stats yet (first-time fetch),
  • the tmux pane content changed since the last tick (agent wrote files),
  • the caller needs full diff content but only short-stats are cached (selection-change upgrade path).

When false, the tick can skip the git subprocess entirely. The paused branch is also short-circuited so a paused instance's tick stays cheap.

func (*Instance) Snapshot

func (i *Instance) Snapshot() InstanceData

Snapshot returns a serialization-safe copy of every Instance field under a single RLock. This is the only safe way to read every field at once from outside the main goroutine. Callers that previously invoked ToInstanceData from background Cmd goroutines (e.g. storage.DeleteInstance) must use this to avoid racing with the main loop's writes (INST-11, STORE-16).

GitWorktree's Get* accessors are pure field reads, so it is safe to call them while holding i.mu — no I/O happens under the lock.

func (*Instance) Start

func (i *Instance) Start(firstTimeSetup bool) (err error)

Start brings the instance online: sets up the worktree, spawns the tmux session, and transitions Ready → Loading → Running. Pass firstTimeSetup=true when the instance is newly created (initial commit, copy user-supplied prompt) and false when loaded from storage. Returns an error if setup fails, leaving the instance in its prior status.

func (*Instance) Started

func (i *Instance) Started() bool

Started reports whether Start or Resume has completed setup, so the instance has a live tmux session and worktree (or root-repo terminal).

func (*Instance) StatusAge added in v0.13.0

func (i *Instance) StatusAge() time.Duration

StatusAge returns how long the instance has been in its current status, or 0 when no transition has been observed this process.

func (*Instance) SubagentScanRequest added in v0.13.0

func (i *Instance) SubagentScanRequest() (subagent.Request, bool)

SubagentScanRequest describes the scan this instance needs, or returns false when it should not be scanned: a non-Claude agent, no config dir, or a status in which no agent can be running. Call it on the Update goroutine; the returned request is safe to hand to a tea.Cmd.

func (*Instance) Subagents added in v0.13.0

func (i *Instance) Subagents() []subagent.View

Subagents returns the live agents to render, or nil when nothing is tracked or the instance is in a status where no agent can be running (Paused, Recoverable, Deleting).

func (*Instance) TmuxSession

func (i *Instance) TmuxSession() *tmux.TmuxSession

TmuxSession returns the backing tmux session, or nil if the instance has not been started yet. Exposed so the app layer can drive a full-screen attach via tea.ExecProcess.

func (*Instance) ToInstanceData

func (i *Instance) ToInstanceData() InstanceData

ToInstanceData converts an Instance to its serializable form. Kept as a thin wrapper around Snapshot for backwards compatibility with existing callers; new code should prefer Snapshot.

func (*Instance) TransitionTo

func (i *Instance) TransitionTo(to Status) error

TransitionTo validates from→to against the state-machine allow-list and updates Status atomically. Disallowed transitions return an error and leave Status unchanged. Self-transitions are no-ops (success).

func (*Instance) UpdateDiffStats

func (i *Instance) UpdateDiffStats() error

UpdateDiffStats updates the git diff statistics for this instance

func (*Instance) UpdateDiffStatsShort

func (i *Instance) UpdateDiffStatsShort() error

UpdateDiffStatsShort updates only the line counts (Added/Removed) without fetching full diff content. Cheaper for non-selected instances that only display counts in the list view.

func (*Instance) UpdateParity added in v0.13.0

func (i *Instance) UpdateParity(base string)

UpdateParity recounts ahead/behind against base (a ref name such as "origin/main"). Skipped — leaving parity unknown — for workspace terminals, unstarted, paused or recoverable instances, and when base is empty. Runs one local git subprocess; call it from the metadata fan-out, never from Update.

func (*Instance) WaitReason added in v0.13.0

func (i *Instance) WaitReason() string

WaitReason returns Claude's reason for blocking, or "" when none is known — the roster is the only source, so a non-Claude agent or a scraper-driven status always yields "".

type InstanceData

type InstanceData struct {
	SchemaVersion int `json:"schema_version,omitempty"`

	Title     string    `json:"title"`
	Path      string    `json:"path"`
	Branch    string    `json:"branch"`
	Status    Status    `json:"status"`
	Height    int       `json:"height"`
	Width     int       `json:"width"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	Program             string          `json:"program"`
	HeadroomProxy       bool            `json:"headroom_proxy,omitempty"`
	CacheTTL1h          bool            `json:"cache_ttl_1h,omitempty"`
	Worktree            GitWorktreeData `json:"worktree"`
	DiffStats           DiffStatsData   `json:"diff_stats"`
	IsWorkspaceTerminal bool            `json:"is_workspace_terminal"`
	// Issue is the GitHub issue number this session was started from
	// (0 = not linked). Set once at creation by the issue picker or the
	// #n prompt shorthand; read by the GitHub poller join.
	Issue int `json:"issue,omitempty"`
}

InstanceData represents the serializable data of an Instance.

SchemaVersion is tracked for forward-compatible migrations. A missing field (zero) is interpreted as v0 (pre-versioning); migrations.go upgrades it to CurrentSchemaVersion at decode time.

func InstanceDataFromOrphan added in v0.3.0

func InstanceDataFromOrphan(cand OrphanCandidate, program string) InstanceData

InstanceDataFromOrphan reconstructs InstanceData for an orphan candidate. IsExistingBranch is always true so a later Kill (discard) removes only the worktree, never the branch. Status is left zero (Running); callers override it (Recoverable for the inline placeholder, Running for recovery).

func Migrate

func Migrate(raw []byte) (InstanceData, error)

Migrate decodes a single raw JSON object representing a stored instance and upgrades it to CurrentSchemaVersion. The function is idempotent: a record already at CurrentSchemaVersion round-trips unchanged.

v0 records (missing SchemaVersion field → decodes to 0) are treated as pre-versioning. The v0→v1 step is a pure field-default upgrade and exists to establish the migration plumbing. v1→v2 drops the AutoYes field (encoding/json already ignores the now-unknown "auto_yes" key on unmarshal, so this step too is just a version stamp). v2→v3 adds GitWorktreeData.StashRef; v3→v4 adds HeadroomProxy; v4→v5 adds CacheTTL1h; v5→v6 adds Issue — all default correctly on their own (empty string, false, 0), so every step is a pure version stamp.

Contributor protocol: when adding/renaming/removing an InstanceData field, bump CurrentSchemaVersion and append a new case to the switch that upgrades from the previous version. The JSON fixture in cmd/workspace_migrate_shape_test.go is a drift guard for the `workspace migrate` CLI's typed mirror struct and must be updated in the same commit.

func MigrateAll

func MigrateAll(rawArray []byte) (records []InstanceData, skipped []json.RawMessage, err error)

MigrateAll applies Migrate to every element of a JSON array of raw instance records.

A record that fails Migrate — corrupt, or written by a newer loom with a schema_version above CurrentSchemaVersion (e.g. after a downgrade) — is logged and returned in skipped as its original bytes rather than failing the whole array. Storage writes skipped records back verbatim on every save, so one unreadable record can never take the rest of the list down with it, nor be silently dropped itself. err is returned only when the top-level payload is not a JSON array at all; there are then no individual records to preserve, and Storage refuses to write over it.

Empty input returns nil, nil, nil.

type InstanceOptions

type InstanceOptions struct {
	// Title is the title of the instance.
	Title string
	// Path is the path to the workspace.
	Path string
	// Program is the program to run in the instance (e.g. "claude", "aider --model ollama_chat/gemma3:1b")
	Program string
	// HeadroomProxy controls whether this instance's tmux session gets
	// ANTHROPIC_BASE_URL pointed at Headroom's proxy. See Instance.HeadroomProxy.
	HeadroomProxy bool
	// CacheTTL1h controls whether this instance's tmux session gets
	// ENABLE_PROMPT_CACHING_1H=1. See Instance.CacheTTL1h.
	CacheTTL1h bool
	// Prompt is the initial prompt sent to the agent once the instance
	// has started (optional). See Instance.Prompt.
	Prompt string
	// Branch is an existing branch name to start the session on (empty = new branch from HEAD)
	Branch string
	// ConfigDir is the workspace config directory for worktree resolution.
	ConfigDir string
	// IsWorkspaceTerminal creates a workspace terminal instance (no worktree).
	IsWorkspaceTerminal bool
}

InstanceOptions collects the arguments for NewInstance. Title, Path, Program, and ConfigDir are expected; the launch toggles, Prompt, Branch, and IsWorkspaceTerminal are optional.

type Notice added in v0.13.0

type Notice struct {
	// contains filtered or unexported fields
}

Notice is the error an Instance operation returns when it did all it was asked but found something the user must hear about: a pending stash it forgot because it was no longer in `git stash list`, or a stash entry it could not drop. The operation's effects stand. A caller that gets exactly a Notice back (OnlyNotice) treats the operation as succeeded and shows the message — the app through its error bar, never just loom.log, since the message is often the only place a lost stash's SHA appears. A failure that also has notices to report joins them into its own error, where NoticeIn still finds them.

func NoticeIn added in v0.13.0

func NoticeIn(err error) (*Notice, bool)

NoticeIn returns the Notice anywhere in err's chain, for a caller that handles a failure itself but must still show what else it carried.

func OnlyNotice added in v0.13.0

func OnlyNotice(err error) (*Notice, bool)

OnlyNotice returns err as a Notice when it is one and nothing more: the operation that returned it succeeded. A Notice wrapped into another error is part of a failure and does not count.

func (*Notice) Error added in v0.13.0

func (n *Notice) Error() string

Error implements error.

func (*Notice) Unwrap added in v0.13.0

func (n *Notice) Unwrap() error

Unwrap exposes the notices for errors.Is/errors.As.

type OrphanCandidate added in v0.1.3

type OrphanCandidate struct {
	// WorktreePath is the absolute path of the orphaned worktree.
	WorktreePath string
	// BranchName is the sanitized branch this worktree was created on,
	// recovered by stripping the trailing `_<hex>` timestamp suffix
	// from the worktree directory name.
	BranchName string
	// RepoPath is the main repository's working tree (resolved via
	// `git -C <worktreePath> rev-parse --git-common-dir`). Discovery
	// drops candidates where this lookup fails — there's no way to
	// reconstruct a usable Instance without it.
	RepoPath string
	// BaseCommitSHA is the worktree's current HEAD, captured as the
	// recovered instance's diff-stats baseline. Without it, the diff
	// pipeline emits "base commit SHA not set" warnings on every
	// metadata tick until the user pause+resumes the instance.
	BaseCommitSHA string
	// Title is the humanized branch leaf (e.g. branch
	// "aidanb/example-jupyter-notebook" → title "example jupyter
	// notebook"). Used as the recovered instance's display title.
	Title string
	// HasLiveTmux reports whether a tmux session named
	// loom_<sanitized-title> is currently running. When true, recovery
	// can adopt the live PTY rather than spawning a new one.
	HasLiveTmux bool
	// HasUncommittedChanges reports whether the worktree has uncommitted
	// edits (git status --porcelain). True (conservatively, on probe
	// error) keeps an orphan in the needs-review bucket so auto-clean
	// never discards unsaved work.
	HasUncommittedChanges bool
}

OrphanCandidate describes a worktree directory found on disk that no loaded Instance refers to — typically the consequence of state.json being overwritten without removing the underlying worktree, or a crash mid-cleanup. Each field is populated to the extent possible from the filesystem and a quick git probe; downstream code uses this to reconstruct an InstanceData entry without losing the user's work.

func DiscoverOrphans added in v0.1.3

func DiscoverOrphans(configDir string, claimedPaths map[string]bool, cmdExec internalexec.Executor) ([]OrphanCandidate, error)

DiscoverOrphans scans configDir's worktrees directory and returns every entry that is not referenced by claimedPaths. Each returned candidate is enriched with the branch name, repo path (best-effort), humanized title, and a tmux liveness probe.

claimedPaths is the set of WorktreePaths already accounted for in state.json — typically built by the caller from instance.GetGitWorktree().GetWorktreePath() across the loaded list.

Returns an empty slice (not nil) when configDir has no worktree dir or no orphans exist. Errors from individual worktree probes are logged but do not abort discovery; the function only returns an error when the worktrees directory itself is unreadable for a non-NotExist reason.

func (OrphanCandidate) Disposition added in v0.3.0

func (c OrphanCandidate) Disposition() OrphanDisposition

Disposition buckets a candidate. Any signal of life (a running agent or unsaved edits) routes to review; everything else is safe to auto-clean.

type OrphanDisposition added in v0.3.0

type OrphanDisposition int

OrphanDisposition tells reconcileOrphans how to handle a candidate.

const (
	// DisposeClean means dead tmux and no uncommitted changes — a stale
	// leftover. Auto-remove the worktree (branch preserved).
	DisposeClean OrphanDisposition = iota
	// DisposeReview means live tmux or uncommitted changes — surface
	// inline as a Recoverable entry for the user to recover or discard.
	DisposeReview
)

type RecoveryAction

type RecoveryAction int

RecoveryAction describes what to do with an instance during startup reconciliation.

const (
	// ActionNoChange means the instance is already in a consistent state (e.g. Paused).
	ActionNoChange RecoveryAction = iota
	// ActionRestore means tmux + worktree are healthy; do a normal restore.
	ActionRestore
	// ActionRestart means tmux is dead but worktree exists; restart with scrollback + agent context.
	ActionRestart
	// ActionMarkPaused means both tmux and worktree are gone; mark as Paused (branch is preserved).
	ActionMarkPaused
	// ActionKillAndPause means tmux is alive but worktree is gone; kill tmux, mark Paused.
	ActionKillAndPause
	// ActionRestartWsTerminal means workspace terminal's tmux is dead; recreate it.
	ActionRestartWsTerminal
)

func DetermineRecoveryAction

func DetermineRecoveryAction(status Status, tmuxAlive, worktreeExists, isWorkspaceTerminal bool) RecoveryAction

DetermineRecoveryAction decides what to do with a loaded instance based on its persisted status and current filesystem/tmux state.

type RemoteControlAuth added in v0.3.0

type RemoteControlAuth struct {
	State  RemoteControlAuthState
	Reason string
}

RemoteControlAuth carries the detection state plus a human-readable reason shown to the user when Blocked.

func DetectClaudeRemoteControlAuth added in v0.3.0

func DetectClaudeRemoteControlAuth(program string, runner internalexec.Executor) RemoteControlAuth

DetectClaudeRemoteControlAuth determines whether the given program's Claude authentication can establish a --remote-control session. It is a no-op (Unknown) for non-Claude programs. Remote control requires a claude.ai OAuth login; API keys, Console accounts, and inference-scoped tokens are rejected by Claude, so this reports Blocked for them.

func (RemoteControlAuth) Blocked added in v0.3.0

func (a RemoteControlAuth) Blocked() bool

Blocked reports whether auth was clearly determined to be incompatible with remote control.

func (RemoteControlAuth) OK added in v0.3.0

func (a RemoteControlAuth) OK() bool

OK reports whether remote control is confirmed usable.

type RemoteControlAuthState added in v0.3.0

type RemoteControlAuthState int

RemoteControlAuthState is the tri-state result of checking whether the active Claude authentication can establish a --remote-control session.

Detection is deliberately conservative: only a clear positive is OK and only a clear negative is Blocked. Anything ambiguous is Unknown so callers can fail closed (skip the flag) without interrupting the user.

const (
	// RemoteControlAuthUnknown means auth could not be determined — the
	// program isn't Claude, the `auth status` subcommand is missing, or its
	// output didn't parse. Callers add no flag and show no prompt.
	RemoteControlAuthUnknown RemoteControlAuthState = iota
	// RemoteControlAuthOK means the session is logged in with a claude.ai
	// account and no API-key override — remote control will work.
	RemoteControlAuthOK
	// RemoteControlAuthBlocked means auth was clearly determined to be
	// incompatible with remote control (API-key/console/token auth, an
	// override env var, or simply not logged in).
	RemoteControlAuthBlocked
)

type RosterEntry added in v0.13.0

type RosterEntry struct {
	SessionID  string
	Name       string
	Status     RosterStatus
	WaitingFor string
}

RosterEntry is one live Claude session as reported by the roster.

func (RosterEntry) LoomStatus added in v0.13.0

func (e RosterEntry) LoomStatus() (Status, bool)

LoomStatus maps a roster status onto Loom's session lifecycle. The bool is false when the roster expressed no usable opinion, in which case the caller must leave the instance's status to the pane-content ladder.

type RosterStatus added in v0.13.0

type RosterStatus int

RosterStatus is a Claude session's self-reported state as published by `claude agents --json`. It is authoritative: Claude knows whether it is mid-turn or blocked on a dialog, where Loom's pane scraper can only infer it from screen text (see PendingPromptPattern and the redetect ladder in app/events.go).

const (
	// RosterStatusUnknown means the roster reported a status string this
	// build does not recognize. Callers must treat it as "no opinion" and
	// fall back to pane-content detection rather than guessing.
	RosterStatusUnknown RosterStatus = iota
	// RosterStatusIdle means the session is waiting for the user's next
	// instruction — Loom's Ready.
	RosterStatusIdle
	// RosterStatusBusy means the session is mid-turn — Loom's Running.
	RosterStatusBusy
	// RosterStatusWaiting means the session is blocked on a prompt or
	// dialog — Loom's Prompting. WaitingFor carries Claude's reason.
	RosterStatusWaiting
)

type SessionBackend

type SessionBackend interface {
	// RepoName returns the human-visible repo/workspace name used in
	// UI labels.
	RepoName() (string, error)
	// WorkTreePath returns the filesystem directory where the tmux
	// session should operate.
	WorkTreePath() string
	// Diff returns the current diff stats (line counts + content).
	Diff() *git.DiffStats
	// DiffShort returns diff line counts only, without content body —
	// cheaper for non-focused instances that only render counts.
	DiffShort() *git.DiffStats
	// RefreshBranch returns the current branch name, or empty string
	// if the backend doesn't need to refresh (worktrees have a fixed
	// branch for their lifetime; workspace terminals track HEAD).
	RefreshBranch() string
}

SessionBackend is the polymorphic surface for operations that differ between regular (worktree-backed) instances and workspace terminals. It consolidates scattered IsWorkspaceTerminal branching into a single indirection so new backend types (e.g., remote sessions) can be added by implementing this interface rather than extending a switch.

Scope note: lifecycle operations (Setup/Kill/Pause/Resume) still branch inline in Instance because they interact with shared state (tmux session, lock bookkeeping) in ways that don't fit cleanly behind this interface. Migrating those is a follow-up.

type Status

type Status int

Status is the Instance lifecycle state. Transitions are gated by allowedTransitions in instance.go; use Instance.TransitionTo for every write so invariants hold across the app and tests.

const (
	// Running is the status when the instance is running and claude is working.
	Running Status = iota
	// Ready is if the claude instance is ready to be interacted with (waiting for user input).
	Ready
	// Loading is if the instance is loading (if we are starting it up or something).
	Loading
	// Paused is if the instance is paused (worktree removed but branch preserved).
	Paused
	// Prompting is when the agent is asking for user permission.
	Prompting
	// Deleting is a transient status set immediately when the user confirms
	// deletion. Cleanup runs asynchronously; on failure the status reverts.
	Deleting
	// Recoverable is an orphaned worktree found on disk and surfaced inline
	// for the user to recover or discard. It has a worktree but no live tmux
	// and is never persisted to state.json (re-derived from disk each load).
	// Appended last so existing serialized Status ints are unchanged.
	Recoverable
)

func (Status) String

func (s Status) String() string

String implements fmt.Stringer for debugging and transition-error messages.

type Storage

type Storage struct {
	// contains filtered or unexported fields
}

Storage handles saving and loading instances using the state interface

func NewStorage

func NewStorage(state config.InstanceStorage, configDir string) (*Storage, error)

NewStorage creates a new storage instance. configDir is the workspace config directory injected into loaded instances.

func (*Storage) DeleteAllInstances

func (s *Storage) DeleteAllInstances() error

DeleteAllInstances removes all stored instances. It is the explicit wipe (`loom reset`), so it is allowed even while a failed load has latched ordinary writes shut, and it drops everything preserved on disk: unrecovered and undecodable records and the latch itself. The next write re-reads the (now empty) backing store first, as on a fresh Storage.

func (*Storage) DeleteInstance

func (s *Storage) DeleteInstance(title string) error

DeleteInstance removes an instance from storage. Operates on raw InstanceData so it does not construct live Instance objects (which would open tmux attach PTYs for every remaining running instance).

func (*Storage) LoadAndReconcile

func (s *Storage) LoadAndReconcile(cmdExec internalexec.Executor) ([]*Instance, error)

LoadAndReconcile loads instance data from disk and reconciles each instance against the live tmux/worktree state. Unlike LoadInstances, a single failing instance is logged and skipped rather than aborting the whole load. This is the correct entry point for any caller that can tolerate reconciliation side effects (killing orphan tmux sessions, marking instances paused).

Records that fail ReconcileAndRestore are stashed in s.unrecovered so the next SaveInstances preserves them on disk. Previously such failures led to permanent data loss: the failed record was silently omitted from the live list, and the next save overwrote state.json with only the survivors. Records that cannot be decoded at all are likewise skipped here and preserved verbatim (UndecodableCount); only a payload that is not a JSON array fails the load, which also latches every write shut until a later load succeeds.

func (*Storage) LoadInstanceData

func (s *Storage) LoadInstanceData() ([]InstanceData, error)

LoadInstanceData loads raw serialized instance data without constructing Instance objects. Used by reconciliation to inspect state before deciding how to restore. All records pass through Migrate so callers receive CurrentSchemaVersion data; records that fail it are omitted here and preserved on the next write.

func (*Storage) LoadInstances

func (s *Storage) LoadInstances() ([]*Instance, error)

LoadInstances loads the list of instances from disk. Records this binary cannot decode are skipped (and preserved on the next write).

func (*Storage) PreservedTitles added in v0.13.0

func (s *Storage) PreservedTitles() []string

PreservedTitles returns the titles of every record preserved on disk but absent from the live list: the unrecovered cache, plus each undecodable record's title, decoded best-effort (a missing, empty or unreadable title is skipped). Title-keyed sweeps — the orphan tmux sweep and the subagent hooks sweep — must spare these, or a preserved record keeps its JSON but loses its still-running agent (e.g. a newer loom's session after a downgrade, or a record whose reconcile failed transiently).

func (*Storage) PreservedWorktreePaths added in v0.13.0

func (s *Storage) PreservedWorktreePaths() map[string]bool

PreservedWorktreePaths returns the set of worktree paths held by records that are preserved on disk but absent from the live list: the unrecovered cache, plus undecodable records (their worktree path decoded best-effort; a record whose path can't be read is skipped). Orphan discovery uses this so a preserved record's worktree is not also surfaced as an orphan candidate, which would let the user re-recover it under a different title and produce a duplicate state.json entry.

func (*Storage) SaveInstances

func (s *Storage) SaveInstances(instances []*Instance) error

SaveInstances saves the list of instances to disk. Callers are responsible for filtering out instances that should not be persisted (e.g. Ready-but-not-yet-configured, Deleting) via persistableInstances at the call site. Filtering here on Instance.Started() is unsafe because Kill() flips started=false early (before tmux/worktree teardown), so a save during the kill window would silently drop the instance from disk and cause DeleteInstance to fail with ErrInstanceNotFound.

Unrecovered records from the most recent LoadAndReconcile pass are appended to the payload (deduped by title — a live record always wins) so reconcile failures do not silently delete persisted state. Records this binary cannot decode follow them verbatim (see writeLocked), and the save is refused with ErrStorageLoadFailed while the payload as a whole is unreadable.

func (*Storage) UndecodableCount added in v0.13.0

func (s *Storage) UndecodableCount() int

UndecodableCount returns how many persisted records the last successful load could not decode. Like unrecovered records they are preserved on disk but never appear in the live list, so callers surface the count.

func (*Storage) UnrecoveredTitles added in v0.7.0

func (s *Storage) UnrecoveredTitles() []string

UnrecoveredTitles returns the titles of records that failed the last LoadAndReconcile pass. These are preserved on disk and retried on the next load, but never appear in the live list — callers use this to tell the user they exist at all.

func (*Storage) UpdateInstance

func (s *Storage) UpdateInstance(instance *Instance) error

UpdateInstance replaces the persisted record for an existing instance. Uses the in-memory snapshot of the provided instance and the raw-data load path so the other stored entries are never reconstructed.

func (*Storage) WritesRefused added in v0.13.0

func (s *Storage) WritesRefused() bool

WritesRefused reports whether the write latch is engaged: the last load could not decode the payload as a whole, so every write returns ErrStorageLoadFailed until a later load succeeds. Callers check it before creating anything new, which could never be persisted — keeping a latched Storage's list to exactly what it loaded (nothing).

type SweepResult added in v0.13.0

type SweepResult struct {
	// Killed sessions were started under an owned root.
	Killed int
	// Unowned sessions were left running: started outside every owned
	// root, or with a start directory that could not be read.
	Unowned int
	// Untargetable sessions were left running: their names hold ':' or
	// '.', so no target names them exactly.
	Untargetable int
	// Failed sessions were owned, but killing them failed.
	Failed int
}

SweepResult counts what one orphan sweep (CleanupOrphanedSessions) did with the unclaimed loom sessions it found.

func CleanupOrphanedSessions

func CleanupOrphanedSessions(claimedTitles map[string]bool, scope SweepScope, cmdExec internalexec.Executor) (SweepResult, error)

CleanupOrphanedSessions kills the loom tmux sessions (either prefix, so upgrades from claude-squad don't leave zombie panes behind) that no title in claimedTitles owns and whose working directory scope owns. Unclaimed is not enough: the tmux server is shared, and the incident this rule answers was a second loom's startup sweep killing all 20 sessions on the server, the first loom's live agents included. It fails closed: a session whose directory is empty, unreadable or outside every owned root is left alone, and so is one whose name tmux cannot target exactly (tmux.ExactlyTargetable). Kills are by exact name (tmux.SessionTarget).

No server running means nothing to sweep. Any other listing failure (a timeout on a loaded server, say) is an error, as is every failed kill: either way some of scope's sessions may still be running, and `loom reset` must not go on to delete the worktrees under them. Startup callers log the error and carry on. Every sweep logs an orphan_tmux.sweep_done summary at info level.

type SweepScope added in v0.13.0

type SweepScope struct {
	// Owned holds the roots (WorkspaceSweepRoots) of every workspace
	// whose sessions the sweep covers.
	Owned []string
	// Foreign holds the roots of every other known workspace. They
	// matter only nested inside an owned root (a submodule, or a linked
	// worktree registered as its own workspace): a session there belongs
	// to the inner workspace, and its own loom sweeps it.
	Foreign []string
}

SweepScope bounds the orphan tmux sweep (CleanupOrphanedSessions) to sessions this process can prove it owns. The tmux server is shared by every loom process on it, so a loom_* session missing from this process's lists is not evidence of an orphan: it may be the live agent of another running loom, in a workspace this process never loaded. Every loom session starts in a directory loom chose: its worktree, or the repo root for a workspace terminal (and that terminal's pane). The sweep kills an unclaimed session only when the most specific root holding that directory is Owned.

func NewSweepScope added in v0.13.0

func NewSweepScope(owned []*config.WorkspaceContext, registry *config.WorkspaceRegistry) SweepScope

NewSweepScope returns the scope of a sweep covering the workspaces in owned (a nil entry owns nothing; an empty ConfigDir means the default config dir). Every workspace in registry (nil allowed) and the global config dir's worktrees are foreign; the ones owned also lists stay owned.

Directories

Path Synopsis
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.).
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.).
Package files provides filesystem enumeration helpers for the file explorer overlay.
Package files provides filesystem enumeration helpers for the file explorer overlay.
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup.
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup.
Package github reads GitHub state through the gh CLI for loom's session cards and issue picker.
Package github reads GitHub state through the gh CLI for loom's session cards and issue picker.
Package subagent tracks the subagents and agent-team teammates a Claude session has spawned, from the Claude Code hook events loom registers at launch.
Package subagent tracks the subagents and agent-team teammates a Claude session has spawned, from the Claude Code hook events loom registers at launch.
Package tmux manages the tmux sessions that drive each agent.
Package tmux manages the tmux sessions that drive each agent.
Package vt defines Loom's pane-display abstraction.
Package vt defines Loom's pane-display abstraction.

Jump to

Keyboard shortcuts

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