session

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0

README

session

The core domain: Instance, a running agent session in its own git worktree and tmux session, with its storage, reconcile, orphan discovery, resume decisions, Claude status, hooks, temp-dir archiving and launch environment. The model in ../core/ drives it; the TUI never holds an Instance. session/ itself holds the instance and everything that acts on it; the sub-packages (session/agent/, session/claudetmp/, session/files/, session/github/, session/hooks/, session/launch/, session/subagent/, session/git/, session/vt/) are described at the end, and session/tmux/ has its own README.md.

Instance

Instance (instance.go) has a status lifecycle: Ready (initial), Loading (setup in progress), Running (agent active), Paused (worktree removed, branch preserved), and Recoverable (an orphaned worktree found on disk, surfaced inline for recover or discard; never persisted). Its own API is lifecycle and state.

Its tmux session is a lifecycle-only tmux.Session that never attaches a client: the TUI's pane clients do that. Whatever lifecycle does to the agent's pane without a client lives on the AgentPane value Instance.Pane() returns (agent_pane.go): liveness probes, the session name and the program the session was launched with (SessionProgram), typing text and prompts (SendKeys, SendPrompt: load-buffer + paste-buffer), pressing Enter (TapEnter: send-keys), and a capture-pane Preview; for example, inst.Pane().SendPrompt(…). Rendering the pane and forwarding input through a PTY go through the TUI's attach clients (ui.Pane, from ui.PaneClients), keyed by session name, whose adapter comes from inst.Pane().SessionProgram(), never Program: a resume that reattaches a live session (R with a new program) keeps the old tmux.Session, while Program already names the new one. Instance.Kill and Pause end the agent's session and the terminal pane's loom_term_ shell by name (CloseRelatedSession), which gives each attach client's pump EOF; neither closes a client itself. A session.Instance never reaches the TUI.

Launch fields are set through SetLaunchOptions/SetProgram/SetPrompt/SetCrashRecovered and read through Program()/HeadroomProxy()/CacheTTL1h()/Prompt()/CrashRecovered(), never assigned directly: the accessors lock i.mu, so session code that already holds it reads the private fields instead (the lock is not reentrant).

FromInstanceData is a pure constructor: it spawns no tmux session. inst.EnsureRunning() only marks a restored instance whose session runs as started. Nothing in session attaches a PTY.

Storage and schema

storage.go (session.Storage, which carries its own mutex) serializes the instances array in state.json (not a separate file; config.InstancesFileName is unused). Since schema v6 a record's issue links a session to the GitHub issue it was created from; since v7 claude_session_id/claude_transcript_path name the conversation a crash relaunch resumes with --resume; since v8 account names the Claude account it runs on (empty means default).

session.InstanceData has a SchemaVersion field and session.CurrentSchemaVersion constant; session/storage_migrate.go:Migrate upgrades a record step by step, and MigrateAll runs it over a payload. A record Migrate rejects, or one that fails to decode (corrupt, or a schema_version newer than this binary after a downgrade), is skipped, held as raw bytes (UndecodableCount), and appended verbatim to every write. SaveInstances and DeleteInstance (and the test seam UpdateInstanceForTest) all go through writeLocked, which also loads first on a never-loaded Storage. Records that fail ReconcileAndRestore are kept as raw InstanceData (the unrecovered cache), so a transient failure does not drop them at the next save.

A payload that is not a JSON array fails the load and latches every write shut (ErrStorageLoadFailed, state untouched) until a later load succeeds; WritesRefused() reports it. DeleteAllInstances (loom reset) is the one write allowed through, and clears the latch. Both kinds of preserved record are claimed by worktree path (PreservedWorktreePaths), so orphan discovery doesn't offer them as Recoverable, and by title (PreservedTitles, folded in by core's claimTitles at every sweep site), so the orphan tmux sweep and the hooks sweep spare their sessions, workspace-terminal auto-create doesn't kill and duplicate a preserved terminal, and a new session can't take a preserved title (the TUI's preservedTitleErr); both are counted in the recovery summary.

loom workspace migrate (cmd/workspace_migrate.go) bypasses writeLocked: it decodes records into its own typed mirror and writes via config.SaveStateTo, so a newer-schema record passing through it loses every field this binary doesn't know. Changing a field: ../docs/claude/changing-the-instance-schema.md.

Reconcile, orphans and ownership

Storage.LoadAndReconcile restores each record against tmux and disk. tmux.RenameLegacySessions runs there, before per-record reconcile, on every load path, so live claudesquad_ sessions are renamed loom_ and keep their panes.

orphan.go (session/orphan.go) discovers worktree directories on disk that state.json doesn't reference (DiscoverOrphans) and classifies them (Disposition): stale leftovers (dead tmux, clean tree) are auto-cleaned (RemoveOrphanWorktree), and ones with unsaved work or a live agent surface inline as Recoverable entries. A live orphan keeps its account: discovery reads the session's CLAUDE_CONFIG_DIR back with tmux show-environment and maps it through the registry (liveSessionAccount). A dead one recovered from disk (r on a Recoverable entry) comes back on the default account, since nothing on disk records which account it ran on.

tmux names are per server, not per workspace, so reconcile.go proves ownership before it acts. Each check takes the record's session.SessionHome{Dir, Exact} (Instance.SessionHome): an agent's session starts in its worktree, so one started there or below is its own; a workspace terminal's starts in its repository itself (loom launches it with -c <repo>), so only an exact match is, because an agent titled after the workspace starts its session in <repo>/.loom/worktrees under the terminal's tmux name.

  • startedElsewhere counts only positive evidence: a non-Paused record whose name is alive on a session started anywhere else goes straight to ActionMarkPaused, workspace terminals included, so reconcile neither restores it onto that session, crash-restarts it under a name known to be taken, nor kills the other session. An unreadable listing or start directory keeps the old behaviour, which may restore onto or kill that session; HeldElsewhere is the fail-closed check.
  • HeldElsewhere is asked by a caller about to kill or replace whatever runs under a name, and fails closed with three outcomes: held (a live session not provably the record's own, one with no start directory included), free (no session of that name, or no server), or an error (a listing tmux left unanswered, a timeout under load: change nothing and ask again). Instance.Kill and Instance.Resume ask it of the session under the record's name (sessionHeldElsewhere, through tmux.Session.StartDir): a kill leaves a held name's sessions running, the agent's and the terminal-pane loom_term_ shell, and cleans up only what is the record's own; a resume refuses on a held name before decideResume; both refuse, changing nothing, when tmux can't say whose the session is.
  • The orphan tmux sweep (CleanupOrphanedSessions) sees every session on the server, and "not in my lists" is no proof of an orphan. It reads each session's start directory (#{session_path}, the -c dir loom passes to new-session; unlike pane_current_path it ignores a later cd and survives the dir's deletion) and kills an unclaimed loom_*/claudesquad_* session only when that directory, compared after filepath.EvalSymlinks and component-wise (/a/repo does not hold /a/repo2), lies inside an owned root of its SweepScope (session/reconcile.go), with no foreign root nested deeper. Owned roots are each served workspace's repo root and <configDir>/worktrees, except a workspace whose load failed (WorkspaceSweepRoots; NewSweepScope builds the scope from the same workspaces claimTitles covers, in core's sweepOrphans at boot and in loom reset); foreign roots are every other registered workspace's, a failed one's included, and the global worktrees dir. An empty, relative or unplaceable directory is left alone (orphan_tmux.skip_unowned, debug), as is a name that cannot be targeted exactly (tmux.ExactlyTargetable, orphan_tmux.skip_untargetable). Kills are exact-name (-t=, through tmux.SessionTarget). The sweep returns a SweepResult (killed, unowned, untargetable, failed; logged as orphan_tmux.sweep_done) and an error for any listing failure other than "no server running" (isNoTmuxServer) and for every failed kill, so reset stops before deleting worktrees and branches under live agents (TestResetCmd_StopsBeforeWorktreesWhenSweepFails); the boot's sweep only logs it. loom reset kills only the reset workspace's sessions (default: global's).
  • KillOwnedTmuxSession applies the sweep's test to one title: a workspace terminal's title is just the workspace's name, which another loom's workspace can share, so a session not started in this workspace's roots, or any listing that fails, is left running.

Two global dirs that register the same repository both own its roots, so each one's boot could sweep the other's sessions there (rare; unguarded). The sweep does not stop a nested dev daemon serving the same workspaces as its host from sweeping the host's sessions; the nesting guard in the root's serve.go does.

Resume, worktrees and failed starts

When an agent exits on its own (/exit, a crash), the model's tick only calls TransitionTo(Paused): no stash, no removal, so the worktree still holds the only copy of any uncommitted work. The same state arrives via a failed CrashRestart and via adopting a dead-tmux Recoverable orphan (adoption sets crashRecovered, but nothing restarts it, so the tick pauses it).

Resume classifies the path with GitWorktree.InspectTree and feeds it to the pure decideResume (resume_decision.go): a live session is reattached; dead + intact relaunches in place with the agent's recovery flag (recording a missing base commit, EnsureBaseCommit); dead + gutted rebuilds (leftovers moved aside); TreeUnverified or an unanswered probe refuses. The unverified refusal (unverifiedTreeError) tells a git.IsTimeout (retry) from a rejection (move the directory aside, with a shell-quoted mv; the next resume rebuilds), and sameFile reports a path it cannot stat as that error, never as the tree belonging to another repository. finishResume closes the dead session object before starting its replacement and refuses when the probe gets no answer.

Anything that reaches gw.Setup() runs git worktree remove -f, which silently deletes an intact dirty tree. CrashRestart refuses a non-intact tree for the same reason, startFreshWithRecovery never cleans up on a failed start (its old gw.Cleanup() deleted the tree and the branch), and Start(true)'s failed-start cleanup (failedStartCleanup → CleanupFailedStart) deletes the branch only if Setup created it (a reused title checks out the branch an earlier session left behind). That cleanup runs only when nothing can be running in the tree: a name tmux.Start refused before launching (tmux.ErrSessionExists), or a session SessionLiveness confirms Dead, as Pause requires. Any other failure may come after the agent launched, so the tree and branch stay and the error says the agent may still be running.

Stashes and notices

A pending StashRef in place (restoreStashInPlace):

  • no longer in git stash list: forget it, never re-apply it, whatever the tree holds;
  • clean tree: apply;
  • tree already equals the stash (StashOnDisk, an interrupted pause): forget it and drop the duplicate;
  • dirty and different: refuse, naming the full SHA, until the user drops the entry.

The rebuild path asks StashListed too, before Setup, and fails closed (nothing rebuilt) when the list can't be read. When Pause aborts because the session survived Close, it drops its own stash and saves the cleared reference: the tree still holds everything the stash captured.

ApplyStash returns git.ErrStashNotDropped when the apply worked but the drop didn't (callers clear the reference and pass it on). A Resume or Kill that succeeded with something to report returns a session.Notice (notice.go; OnlyNotice means the operation succeeded, NoticeIn finds one inside a failure), naming the SHA: a forgotten stash's Resume notice adds git stash apply <sha> / git fsck --unreachable | grep commit, while Kill's undroppable-stash notice names the SHA only. The model reports them as core.Notice events (resumeOutcome → ResumeResult.Notice, KillResult.Notice), which the TUI shows through handleError; a Lua inst:resume()/inst:kill() returns without raising and its Reply carries the notice. Pause's abort includes a failed drop in its error. Tests: session/resume_inplace_test.go, session/resume_decision_test.go, session/start_cleanup_test.go, session/stash_notice_test.go.

Claude status

Each Claude instance holds one merged observation (claude_state.go, claudeState, guarded by Instance.mu). Hook events (SessionStart, UserPromptSubmit, PermissionRequest, Notification, Stop, SessionEnd) and roster answers are both offered to it, each stamped with when it was observed (a hook event's At from its file name, hooks.eventTime; a roster answer's query start), and the newer one wins whichever source it came from. There is no grace window: a live probe (spec docs/superpowers/specs/2026-09-23-claude-hook-events-design.md, payloads in session/hooks/testdata/probe-2.1.280/) showed the roster moving slightly before the hook's timestamp, so an answer stamped after an event already reflects it, and stamping with the query's start is conservative. TestRealClaude_HookStatusContract (opt-in) asserts that ordering.

Rules of the merge: only parent events (no agent_id) count, except PermissionRequest, whose prompt shows in the parent; Stop ends a turn, not the work (a Stop listing a running subagent task is Running, and teammate and shell tasks never count, since idle teammates stay listed as running); only SessionStart sets the session ID (a failed --resume sends a SessionEnd carrying the unknown ID); a roster answer with no opinion voids a roster-sourced status but never a hook-sourced one; a same-status roster answer keeps the hook's more specific reason (permission: Bash). A reported status also exempts the session from the TUI's Ready→Running promotion on output (paneDirtyMsg).

Without a working roster two gaps remain: an answered prompt stays Prompting until the next hook, and a lead resuming after a teammate reply shows Ready. A relaunch resumes the recorded conversation (BuildResumeCommand, agent_restart.go: --resume <id> when the ID is a UUID and its transcript exists, else --continue; Claude writes the transcript with the first message, so a session that never got one falls back), and a stopped session's card shows the end of Claude's last message (ui.MessageTailLines), valid from its Stop until the next prompt or permission request. App and core test instances start on a mock tmux session, so Start never prepares their hooks folder: like a restored instance they have no launch ID and adopt a scan's. Tests: session/claude_state_test.go (a replay of the whole probe included), core/claude_status_test.go, core/hook_scan_test.go, app/claude_status_test.go, ui/card_message_test.go, and in e2e TestE2E_FakeClaudeHooksDriveStatus.

The roster (claude_roster.go): QueryClaudeRoster/QueryClaudeRosterEnv run claude agents --json (through account.Command for an account's config dir) and key every live Claude session by cwd. Only interactive entries are joined: background (claude --bg) sessions publish state where interactive ones publish status, and a --bg session started inside a worktree would otherwise collide with loom's own session. An entry with no kind counts as interactive (older CLI builds omit it). Two interactive sessions in one directory are an ambiguous cwd, dropped with a session.roster.ambiguous_cwd debug line. The CLI is never a hard dependency. Tests: session/claude_roster_test.go.

Hooks and subagents

Transcripts can't say whether an agent is running (each content block is its own record, and the stop reason is missing from most responses), so Claude is launched with --settings {ConfigDir}/hooks/<folder>/settings.json, where <folder> is the path-escaped tmux session name (hooksFolderName: url.PathEscape(tmux.ToLoomTmuxName(title)), always one path segment, so a / in a title can't nest one instance's folder inside another's, where launching, killing or sweeping the outer one would delete it). It registers SubagentStart/SubagentStop/TeammateIdle/Stop/SessionEnd plus the status events. Each hook writes a file to events/; core's maybeHookScan (core/hook_scan.go) collects them into Instance's subagent.Tracker and claudeState (session/subagent_hooks.go, session/hook_scan.go).

On an account whose projects/ is a link into the main config dir, the same settings.json also sets autoMemoryDirectory to the link's resolved <projects>/<key>/memory (claude_memory.go, accountMemoryDir). Claude lets memory writes through unasked only under its own spelling, <CLAUDE_CONFIG_DIR>/projects/<key>/memory, but checks every write under the resolved path too, so through the link each memory write prompts (Claude Code 2.1.292). The key is claudetmp.DirName of the physical repository root: Claude reads a worktree's root from its .git file, which git writes resolved. Loom sets nothing for the default account, an unlinked projects/, a settings.json that sets (or can't be read to rule out) its own autoMemoryDirectory, a repository without a .git directory, or a key Claude would hash; those sessions prompt as before, and the reason is logged as claude_memory.unresolved. Opt-in contract test, run with CLAUDE_CONFIG_DIR set to a loom account: LOOM_TEST_REAL_CLAUDE=1 go test ./session -run TestRealClaude_AccountMemoryDir.

Hooks are prepared only on real launches (launchProgram(…, true): Start(true), startFreshWithRecovery, CrashRestart, Restart), never on Restore, because a reattached Claude is still writing to its folder. Restart() (the workspace-terminal auto-restart) closes the dead session and rebuilds it as Session.WithProgramEnv(launchProgram(env, true), InstanceEnv(env)) with a freshly resolved env. Every real launch first resets the previous launch's state, even when hooks end up skipped: resetHookLaunch clears the tracker, warm flag, Claude status and last message (keeping the conversation ID the relaunch resumes), sets the launch ID to the noHooksLaunchID sentinel so no scan result matches, and removes the old hooks folder; a successful Prepare then sets the real launch ID. The folder lives outside worktrees/ because DiscoverOrphans would walk it.

Only the parent's Stop reconciles against background_tasks (a SubagentStop list can omit a parallel foreground agent), and in the tracker a missing or malformed list is never read as empty. (claude_state.go's runningSubagent reads a missing list as none running on purpose: it only decides Running versus Ready.) Teammates can't be matched by ID in that list, so shutdown is inferred by count. Read events are kept as compact .ev files so a restarted loom replays them (Request.Cold); a restored instance adopts the folder's launch-id, and results for another launch ID are dropped. A scan returning ErrNoHooks for a launch with a real ID means its folder vanished mid-run, and ForgetSubagentsWithoutHooks drops its rows. An agent without its metadata sidecar is hidden. Windows, non-Claude programs, a user-supplied --settings, or a ' in the config dir path launch without hooks (the folder name itself escapes '). claude_subagent_tracking only decides whether Instance.Subagents returns rows (stored inverted as subagentRowsHidden, so the zero value is enabled): every Claude launch that can take hooks gets them. Opt-in contract test: LOOM_TEST_REAL_CLAUDE=1 go test -timeout 15m ./session/subagent -run TestRealClaude (costs money).

Claude temp dirs

Claude keeps each session's scratchpad and task output under <root>/<encoded cwd>/ (tmpfs on most Linux machines); session/claude_tmp.go wires claudetmp/ into Pause, Kill, Resume and SweepClaudeTemp.

  • Pause archives the dir after the worktree is removed but before it marks the instance Paused. Kill archives it when nothing failed; a tmux session tmux confirms gone counts as closed, so killing an exited agent archives at once. Both are best-effort.
  • Resume restores <name>.zip before the agent launches, on the rebuild and relaunch-in-place paths only (a reattach launches nothing); a failed restore is a Notice, never a failed resume, and Restore creates a missing root (a reboot empties tmpfs).
  • Archives live in <configDir>/archive/claude-tmp/ (dir 0700, files 0600) and are never pruned, unless the global config.json's claude_tmp_archive_dir relocates them under <claude_tmp_archive_dir>/<encoded config dir>/: session.ClaudeTmpArchiveDir(configDir) is the one place every archive, restore and sweep asks, rereading the setting each time, and a resume also looks in the default folder. <name>.zip is the only file a resume restores; a Pause, Kill or sweep that finds one already there demotes it to <name>.<UTC stamp>.zip.
  • Claude names the dir after its physical cwd, so claudetmp.Names encodes both the resolved path and the stored one, and Locate fails closed on zero or several matches and never matches a truncated name.
  • SweepClaudeTemp, queued by core on every workspace load (core/claude_tmp.go), reaps .loom-trash-* tombstones and .loom-restore-* staging dirs older than an hour and archive *.partial files older than a day. It takes a dir only when all of these hold: its name carries this config dir's encoded worktrees prefix and no other known config dir's (the encoding is lossy: foo_bar and foo-bar collide); it ends in a worktree timestamp and is not truncated; no record claims it; nothing in its top three levels changed within sweepQuietPeriod; and, rechecked just before archiving, no directory under the config dir's worktrees* dirs encodes to it. A dir that fails to archive is skipped until the daemon restarts.
  • The daemon computes Claude's root from its own environment (claudetmp.Root), while each agent's Claude computes its own from the agent's, so a differing TMPDIR or CLAUDE_CODE_TMPDIR makes archiving find nothing (safe). loom debug prints its own environment's root. IsolateLoomDirs (internal/testenv) points CLAUDE_CODE_TMPDIR at a throwaway dir. Opt-in contract test (an interactive Claude in a private tmux server, since claude -p gets no scratchpad): LOOM_TEST_REAL_CLAUDE=1 go test ./session -run TestRealClaude_TempDirLayout.

Launch environment and accounts

session.ClaudeFullscreenEnv, folded into InstanceEnv (agent_restart.go), launches every Claude session with CLAUDE_CODE_NO_FLICKER=1: Claude's classic renderer brackets every frame in DEC 2026 synchronized output, which tmux relays to an attach client as a repaint rather than scroll sequences, so the emulator's scrollback stays empty (TestSyncOutputDefeatsEmulatorScrollback_RealTmux, which skips below tmux 3.7, where the relay still scrolls). The env var, not --settings, keeps /tui default working per session, because Claude drops it on renderer relaunch. Any other sync-output app in either pane still can't scroll.

Instances store the account name (InstanceData.Account, "" = default). Every real launch resolves it through the map the model publishes with session.SetAccountDirs (account_env.go) and fails closed rather than fall back to default, which would bill the wrong subscription: *MissingAccountError (MissingAccountError) for a name the registry no longer has (its message points at R on the session to pick another account), *AccountDirMissingError (AccountDirMissingError) when the account is registered but its dir has vanished (the CLI would otherwise start a fresh, logged-out identity there; its message says to loom account remove and add the name again), and *RegistryLoadError when the registry won't load (SetAccountDirs carries that error alongside the map, so it is never reported as "account removed"). Every launch on an account (launchEnv(true)) calls account.EnsureOnboarded, which sets .claude.json's hasCompletedOnboarding for a logged-in account (oauthAccount or .credentials.json), since claude auth login leaves it unset and the CLI would otherwise run its login screen again; a failure is logged, not fatal. CLAUDE_CONFIG_DIR is Claude-only: only Claude programs get it (LaunchEnv/ClaudeConfigDirEnv), so a wrapper program's sessions and the terminal pane's shell run on the default account. Two account-selection gaps stay open by design. R on a Paused session whose tmux session still lives reattaches it (decideResume → resumeReattach) on its old account even after another is picked: reattaching launches nothing, so Instance.Resume skips the account resolution that would otherwise fail closed. And an orphan recovered from disk whose tmux session is dead comes back on the default account, while a live one keeps its account (liveSessionAccount).

Runtime files

  • <configDir>/worktrees/ (~/.loom/worktrees/ for the global workspace): the worktrees; .loom-title sidecars sit beside them.
  • <configDir>/hooks/ (hooks/): per-instance Claude hook folders for status, resume and subagent tracking, one per path-escaped tmux session name; emptied at each launch, removed when an instance is killed, swept when unclaimed and its tmux session is gone.
  • archive/claude-tmp/ (or the claude_tmp_archive_dir relocation): zips of Claude's per-session temp dirs, minus CACHEDIR.TAG caches: one <name>.zip per paused session (restored and deleted on resume), plus permanent archives from kills, sweeps and demoted parks.

Sub-packages

agent

Adapter interface and per-program implementations (claude, aider, gemini, default fallback): trust-prompt keys, recovery flags, and Matches(program) checks, resolved through Registry.Lookup. A new agent program is an adapter here, not edits to tmux/tmux.go or agent_restart.go.

claudetmp

Claude Code's per-session temp dir, <root>/<encoded cwd>/<session id>/{scratchpad,tasks}, where root is the first of $CLAUDE_CODE_TMPDIR/$TMPDIR/$TMP/$TEMP (else /tmp) plus claude-<uid>. Root; DirName/Names (Claude's encoding: every UTF-16 unit outside [a-zA-Z0-9] becomes -, truncated past 200 characters with a hash loom can't compute, so a truncated name never matches and such dirs are left alone); Locate; Archive/ArchiveAs (zip; symlinks stored as links; CACHEDIR.TAG dirs skipped; the source renamed to a .loom-trash-* tombstone, then deleted, only after the zip's rename); Parked; Restore (through os.Root). Root reads its own process's environment. No tmux, UI, app or config dependency.

files

Stateless filesystem enumeration helpers backing the file-explorer overlay (files/ls_files.go, files/recent_md.go). Separate from git/ because callers may operate on non-git roots (workspace terminals pointed at bare directories).

github

Reads GitHub state through the gh CLI: Query (PRs by head branch plus open issues, one snapshot per repo), View (one issue with body), CheckCLI, StateFor (the pure per-session join), SeedPrompt/SlugTitle/ParseShorthand. SlugTitle's output becomes a git branch name (loom names branches {username}/{session_title}), so it whitelists lowercase ASCII alphanumerics only, and a fully non-ASCII title yields a bare gh-<n>. No app, ui or session imports; injected executor. Core's poller drives Query and StateFor; core.Model.FetchIssue runs View; app/state_issue_picker.go seeds a draft from an issue (SlugTitle, SeedPrompt).

hooks

Loom's side of the Claude Code hooks it registers on every Claude launch: hooks/hooks.go writes the per-launch hooks folder (settings.json, launch-id, events/); hooks/scan.go turns new event files into compact .ev files, replays them when needed, and stamps each event's At from its file name; hooks/event.go parses payloads, keeping only the fields loom reads. hooks/testdata/probe-2.1.280/ holds the payloads of a live probe (see its README). No tmux, UI or app dependency.

launch

A Claude session's launch options and their composition into, and decoding from, the agent command line (launch/launch.go). Options holds remote control, permission mode, model, the [1m] context suffix and effort (all baked into the program), plus the Headroom proxy, the 1h cache TTL, the branch prefix and the account, which never reach the command line; the Session Launch Options modal edits one (overlay.LaunchOptions is an alias). FromConfig (or FromSettings, over a config.Settings copy) snapshots the config's defaults, Compose applies them to a program, Parse is its inverse (the R restart flow recomposes from the bare program it returns), EffectiveRemoteControl applies Headroom proxy's exclusivity, and RemoteControlBlocked says when to warn before a launch. A leaf package: it imports only config and session, so the model's workspace-terminal auto-create composes a launch program without importing the UI. Changing an option: ../docs/claude/launch-options.md.

subagent

Tracks the subagents and agent-team teammates a Claude session spawns, from hooks events: subagent/tracker.go is the state machine; subagent/meta.go/subagent/readmeta.go parse and read the agent-<id>.meta.json sidecars. No tmux, UI or app dependency. subagent_hooks.go and hook_scan.go wire both into Instance.

git

Git worktree operations (git/): each session gets an isolated worktree under <configDir>/worktrees/, on a branch named {username}/{session_title} (the prefix is overridable per session: launch.Options.BranchPrefix → Instance.SetBranchPrefix → git.WorktreeSpec.BranchPrefix). It handles setup, diff stats (git.DiffStats, git/diff.go), parity, push, stashes, locks and cleanup.

  • Setup writes a .loom-title sidecar next to the worktree directory (a sibling path, not inside the work tree, so it never pollutes git status) recording the original instance title; Cleanup removes it. Orphan discovery (session/orphan.go) reads it to recover the exact title and tmux session name: branch-derived titles are lossy (lowercased, dash-collapsed) and would miss the live session. Worktrees predating the sidecar degrade to the humanized branch leaf.
  • InspectTree: intact means .git present and git rev-parse (stdout only; paths compared with os.SameFile) reports the path as its own top level and as a linked worktree of this repository (--git-common-dir matches the repo's, --git-dir differs from it), not still locked initializing by an unfinished worktree add. The .git check comes first: git in a gutted dir under <repo>/.loom/worktrees answers for the enclosing repo, which the top-level comparison would only report as unverified, refusing a resume a rebuild could serve.
  • Locks (git/worktree_lock.go): git worktree remove -f refuses any locked tree, and an add killed mid-checkout leaves its tree locked initializing forever (its registry entry makes prune skip it and worktree add refuse the path, "a missing but locked worktree"). git.RefuseLocked, called by orphan auto-clean (RemoveOrphanWorktree) and by GitWorktree.Cleanup/Remove (Kill, Pause), removes that lock only once it is older than gitWorktreeAddTimeout plus a minute (loom kills its own add at that deadline); any other lock gets a *git.LockedError (errors.Is(err, git.ErrWorktreeLocked)) naming git worktree unlock, before cleanup touches anything, branch and title sidecar included. Pause and Kill check locks first (before Pause stashes, and before Kill closes the agent's session or drops a stash), so a respected lock refuses either without killing the agent; a refused Kill keeps its row (core.Kill returns OpFailed) and shows the remedy. core's reconcileOrphans logs a locked orphan at debug and does not count it cleaned. clearWorktreePath (Setup, rebuild) runs git worktree remove -f on whatever sits at the path (so its callers must never send it an intact tree), refuses only when .git survives the remove, moves a gutted tree's leftovers aside, and runs git worktree unlock, on any lock, only when nothingLiveAt holds (absent, not a directory, or no .git; one that cannot be stat'ed counts as live). worktree add runs under gitWorktreeAddTimeout (addWorktree), not the short tick budget whose kill left that lock.
  • Stashes: refs/stash is shared by every worktree of the repo, and git stash drop only takes a stash@{N} position, which shifts under concurrent sessions. DropStash checks the SHA git reports dropping, stores a wrong entry back (retrying a failed store once; after that its error names the commit and the git stash store that restores it), and retries; StashListed fails, never answering "not listed", when the list can't be read; ApplyStash returns git.ErrStashNotDropped when the drop failed after a good apply.
  • Tests: session/git/worktree_inspect_test.go, session/git/worktree_hardening_test.go, session/git/stash_hardening_test.go.
vt

The embedded terminal emulator backing pane display: vt/vt.go defines the Emulator interface; vt/xvt.go (session/vt/xvt.go) is the github.com/charmbracelet/x/vt-backed implementation (vendored); vt/altfilter.go holds vt.NewAltScreenFilter. It decouples rendering and scrollback from tmux capture-pane, so panes can live-scroll and forward mouse and paste input. x/vt only accumulates scrollback on the primary screen, while tmux attach clients enter the alternate screen at attach and never leave it, so the output pump writes through the filter, which strips alt-screen mode switches (1047/1049/47) from the client stream. vt/xvt.go registers Callbacks that fire inside emu.Write, under the wrapper's write lock. One known vendored bug: the OSC-title parser truncates titles containing non-ASCII bytes (it terminates on the lead byte of a multi-byte UTF-8 sequence), so TmuxSession.PaneTitle rejects invalid UTF-8 rather than forward mangled bytes to the host terminal.

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 = 8

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 BuildResumeCommand added in v0.14.0

func BuildResumeCommand(program, sessionID, transcriptPath string) string

BuildResumeCommand rewrites program to resume the recorded conversation: --resume <sessionID> when the ID is a well-formed Claude session ID and its transcript still exists, else BuildRecoveryCommand's --continue. The transcript check matters because Claude deletes transcripts after cleanupPeriodDays (30 by default), and --resume on a missing one exits at once, which the health tick would read as the agent dying again.

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 CanonicalPath added in v0.14.0

func CanonicalPath(p string) string

CanonicalPath is canonicalPath for other packages: p with its symlinks resolved, through its nearest existing ancestor when p is gone; "" for an empty or relative path.

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 ClaudeConfigDirEnv added in v0.14.0

func ClaudeConfigDirEnv(dir, program string) []string

ClaudeConfigDirEnv returns the tmux session environment variable that runs Claude as the account whose config dir is dir. A no-op (nil) for the default account (empty dir) and for every program but Claude.

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 ClaudeTmpArchiveDir added in v0.14.0

func ClaudeTmpArchiveDir(configDir string) string

ClaudeTmpArchiveDir is where configDir's Claude temp-dir archives go. By default that is claudetmp.ArchiveDir(configDir), inside the workspace's own loom config folder. The global config.json's claude_tmp_archive_dir relocates every workspace's archives under one dir, each workspace in a subfolder named after its config dir (its canonical path, encoded the way Claude names its dirs), so two workspaces' archives never mix and a resume finds its own. The setting is read at each use, so an edit applies without a restart; one that cannot be used (not absolute) is logged and the default kept.

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 HeldElsewhere added in v0.14.0

func HeldElsewhere(title string, home SessionHome, cmdExec internalexec.Executor) (bool, error)

HeldElsewhere reports whether a live tmux session holds the name of the record titled title without being provably the record's own, that is started where its own session starts (home, Instance.SessionHome). A caller about to kill or replace whatever runs under that name (a workspace terminal's Restart or CrashRestart) checks it first, since another workspace's session, another loom's, or an agent titled after the workspace can carry the same name. Unlike reconcile's startedElsewhere it fails closed on what tmux answers: a session with no start directory, or a record with no directory of its own, reads as held. No session of that name, or no server, is false. A listing that can't be read (a timeout on a loaded server) is an error: no answer at all, so the caller should change nothing and ask again later.

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(e LaunchEnv) []string

InstanceEnv combines every per-session environment variable derived from an instance's launch (Headroom Proxy, Cache TTL, the account's config dir) plus the always-on Claude fullscreen renderer into the single slice tmux.NewSession's variadic env parameter needs. Centralized here so the four Instance call sites that construct a tmux.Session 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 LoomContextEnabled added in v0.14.0

func LoomContextEnabled(configDir string) bool

LoomContextEnabled reports configDir's loom-context toggle.

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 is QueryClaudeRosterEnv for the default account.

func QueryClaudeRosterEnv added in v0.14.0

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

QueryClaudeRosterEnv runs `claude agents --json` with env appended to loom's own environment (nil: inherit unchanged) and returns its entries keyed by cwd. The roster lists only the sessions of the config dir the CLI runs under, so each account's sessions need a query run as that account (env = its CLAUDE_CONFIG_DIR).

Returns an empty map and no error for non-Claude programs — callers can invoke it unconditionally. A missing subcommand, a hung CLI, an account.ErrAccountDirMissing config dir, 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.

A stale "initializing" lock (an interrupted `git worktree add`) is removed first; any lock loom respects returns a *git.LockedError (errors.Is git.ErrWorktreeLocked) with the tree untouched.

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 SetAccountDirs added in v0.14.0

func SetAccountDirs(dirs map[string]string, registryErr error)

SetAccountDirs publishes the account registry's name → config dir map together with registryErr, the error that kept the registry from loading (nil on success). Bundling them in one atomic store means a launch reading the published state can never observe dirs left over from before a load failure, or vice versa. It copies dirs, so the caller may keep mutating its own.

func SetLoomContextEnabled added in v0.13.0

func SetLoomContextEnabled(configDir string, enabled bool)

SetLoomContextEnabled sets the loom-context toggle of the sessions whose config dir is configDir.

func SetSubagentTrackingEnabled added in v0.13.0

func SetSubagentTrackingEnabled(configDir string, enabled bool)

SetSubagentTrackingEnabled sets the subagent-tracking toggle of the sessions whose config dir is configDir.

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 SubagentTrackingEnabled added in v0.14.0

func SubagentTrackingEnabled(configDir string) bool

SubagentTrackingEnabled reports configDir's subagent-tracking toggle.

func SweepClaudeTemp added in v0.14.0

func SweepClaudeTemp(configDir string, claimed map[string]bool, otherConfigDirs []string) int

SweepClaudeTemp archives (reason "sweep") the Claude temp dirs of configDir's sessions that no longer exist: orphans the auto-clean just removed, sessions an older loom killed, and the backlog from before loom archived anything. It returns how many it archived. It first removes the ".loom-trash-" tombstones older than sweepTrashAge and the ".partial" zips older than sweepPartialAge in configDir's archive dir that an interrupted archive left behind (claudetmp.PurgeTrash, claudetmp.PurgePartials).

A dir under Claude's root is taken only when all of these hold:

  1. Its name starts with configDir's encoded worktrees prefix (resolved or as given) and with no other known config dir's: Claude's encoding is lossy (foo_bar and foo-bar share a prefix), and a workspace can be registered inside another's worktrees dir. otherConfigDirs lists every known config dir; configDir itself may be among them.
  2. Its last "-" segment is a plausible worktree timestamp suffix, and the name is not truncated (past claudetmp.MaxDirName its tail is a hash nothing here can compare).
  3. No path in claimed encodes to it.
  4. Checked again just before it is archived: no directory under configDir's worktrees dirs (worktreeOnDisk) encodes to it.
  5. This process did not already fail to archive it (sweepFailedDirs).
  6. Neither it nor anything in its top three levels was modified within sweepQuietPeriod (recentlyActive): defence in depth for a live session checks 1 to 4 cannot see, such as an agent that outlived a kill whose tmux close timed out. An orphan's dir is archived a day after it goes quiet; Pause and Kill are not delayed.

A live session's dir cannot be taken: its worktree exists before its Claude creates the dir, so it fails check 4 even when another loom started it after claimed was snapshotted. Paused sessions are claimed.

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 WorktreeCreatedAt added in v0.14.0

func WorktreeCreatedAt(worktreePath string) (time.Time, bool)

WorktreeCreatedAt reads when a worktree was made from the `_<hex UnixNano>` suffix resolveWorktreePaths gave its directory. ok is false when the name carries no plausible suffix (not a generated worktree).

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 AccountDirMissingError added in v0.14.0

type AccountDirMissingError struct {
	Name string
	Dir  string
}

AccountDirMissingError is a launch refused because a registered account's config directory no longer exists on disk (deleted by hand, say). Distinct from MissingAccountError: the account is still registered, but relaunching Claude against a missing CLAUDE_CONFIG_DIR would have the CLI silently create a fresh, logged-out identity there instead of loom reporting the account's state gone. The recovery is also distinct: the stale registration itself needs clearing (`loom account remove`) before the name can be reused, not just a different account picked for this launch.

func (*AccountDirMissingError) Error added in v0.14.0

func (e *AccountDirMissingError) Error() string

func (*AccountDirMissingError) Unwrap added in v0.14.0

func (e *AccountDirMissingError) Unwrap() error

Unwrap lets callers use errors.Is(err, account.ErrAccountDirMissing) regardless of whether the missing-dir case was caught here (an instance's own resolution) or in the account package (a direct CLI subprocess call).

type AgentPane added in v0.13.0

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

AgentPane is what session lifecycle does with an instance's agent pane without an attach client: liveness probes, the session name, a capture-pane read of the screen, typing text and prompts through load-buffer + paste-buffer (tmux.Session.TypeText), and pressing Enter through send-keys. Rendering the pane and forwarding input through a PTY belong to the TUI's client (ui.Pane), which the instance never holds. Each method keeps its guard: started and not paused for the screen read, keys and prompts, and only "has a tmux session" for the liveness probes.

It is a cheap value wrapper around the *Instance: take one with inst.Pane() at the call site rather than storing it.

func (AgentPane) Preview added in v0.13.0

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

Preview returns the pane's visible screen through capture-pane (no client needed). It is empty, not an error, when the instance is not started, is paused, or its session is gone. Used by Lua's inst:preview().

func (AgentPane) SendKeys added in v0.13.0

func (p AgentPane) SendKeys(keys string) error

SendKeys types keys, as text, into the agent's tmux session through load-buffer + paste-buffer (tmux.Session.TypeText).

func (AgentPane) SendPrompt added in v0.13.0

func (p AgentPane) SendPrompt(prompt string) error

SendPrompt types prompt into the agent's tmux session through load-buffer + paste-buffer and submits it with Enter through send-keys (tmux.Session.SendPrompt).

func (AgentPane) SessionProgram added in v0.14.0

func (p AgentPane) SessionProgram() string

SessionProgram returns the command line the agent's tmux session was launched with ("" without a session). A pane client's status scan must use it: after a reattach it can differ from Instance.Program.

func (AgentPane) TapEnter added in v0.13.0

func (p AgentPane) TapEnter()

TapEnter presses Enter in the tmux session when the instance is running; otherwise it does nothing. Exposed to Lua scripts as inst:tap_enter().

func (AgentPane) TmuxAliveForTest added in v0.14.0

func (p AgentPane) TmuxAliveForTest() bool

TmuxAliveForTest reports whether the tmux session answers a has-session probe, so a test can check what its fixture's mock executor says. Production code asks TmuxLiveness, which tells "no" from "no answer".

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 a boolean probe, which collapses both cases into false.

func (AgentPane) TmuxSessionName added in v0.13.0

func (p AgentPane) TmuxSessionName() string

TmuxSessionName returns the tmux session name backing this instance, or "" when it has no session. Pane events and the TUI's pane clients are keyed by it.

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 HookScanRequest added in v0.14.0

type HookScanRequest struct {
	Dir         string
	Cold        bool
	MissingMeta []subagent.MetaRef
}

HookScanRequest describes one instance's hook scan: the folder to scan, whether to replay its history, and the subagents still waiting for a metadata sidecar. Build it with Instance.NextHookScan on the Update goroutine; ScanHooks runs it off that goroutine.

type HookScanResult added in v0.14.0

type HookScanResult struct {
	LaunchID string
	Events   []hooks.Event
	Meta     map[string]subagent.Meta
	Replayed bool
}

HookScanResult is one instance's scan: the events found plus the sidecars read for them. Apply it with Instance.ApplyHookScan.

func ScanHooks added in v0.14.0

func ScanHooks(req HookScanRequest, now time.Time) (HookScanResult, error)

ScanHooks runs one instance's scan: hooks.Scan, then the subagent sidecars for its SubagentStart events and req.MissingMeta. It only touches the filesystem, so it is safe to run from a tea.Cmd.

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 touching tmux. Paused instances are constructed fully (started=true, tmux.Session object present — matches their on-disk shape). Non-paused instances are returned with started=false; the caller must invoke EnsureRunning to mark them started. 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) Account added in v0.14.0

func (i *Instance) Account() string

Account returns the Claude account this instance launches under: a registered account's name, or "" for the default account.

func (*Instance) ApplyHookScan added in v0.14.0

func (i *Instance) ApplyHookScan(res HookScanResult) bool

ApplyHookScan applies one scan result to the subagent tracker and the Claude state, 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 and the last message from scratch; the status observation needs no reset, since replayed events are never newer than it. An incremental result 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) ClaudeSession added in v0.14.0

func (i *Instance) ClaudeSession() (sessionID, transcriptPath string)

ClaudeSession returns the conversation a relaunch should resume: the session ID and transcript path from the latest parent SessionStart.

func (*Instance) ClaudeStatus added in v0.14.0

func (i *Instance) ClaudeStatus() (status Status, reason string, ok bool)

ClaudeStatus returns the status Claude's hooks or the roster last reported for this session, with the wait reason when Prompting. ok is false when neither has an opinion, and the status ladder decides.

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 --resume <id> (or --continue) for Claude, via BuildResumeCommand.

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 marks a restored instance whose tmux session is running as started (Start(false)). It attaches nothing (the TUI attaches its own client to the session by name) and is a no-op for paused, Recoverable and already-started instances.

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 hooks.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. The Claude status the hooks reported and the last message go with the rows; a roster-sourced status stays. 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) HooksLaunched added in v0.14.0

func (i *Instance) HooksLaunched() bool

HooksLaunched reports whether this session's current launch registered loom's hooks, so a scan can find its events: a Claude program with a config dir whose launch did not fall back to noHooksLaunchID. A restored instance that has not adopted its folder's ID yet (empty ID) counts.

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. A worktree locked with `git worktree lock` refuses the kill before anything is closed, dropped or removed (git.ErrWorktreeLocked), and the instance stays as it was. A tmux session under its name that is not its own (HeldElsewhere: another workspace's) is left running, with its terminal-pane shell, while the rest is cleaned up; when tmux does not answer whose it is, the kill is refused the same way.

func (*Instance) LastMessage added in v0.14.0

func (i *Instance) LastMessage() (string, bool)

LastMessage returns Claude's last message from its latest Stop, and whether it is still current (no prompt or permission request since).

func (*Instance) Launches added in v0.14.0

func (i *Instance) Launches() uint64

Launches counts the instance's real launches: every Start(true), Restart, CrashRestart and resume that relaunches its agent composes its command through launchProgram once. A resume that reattached to a live session leaves it unchanged, so the daemon watches only a relaunch for a trust prompt (core's watchLaunch). It counts attempts: a launch whose tmux start then failed counts too.

func (*Instance) NextHookScan added in v0.14.0

func (i *Instance) NextHookScan() (HookScanRequest, bool)

NextHookScan 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) ObserveRoster added in v0.14.0

func (i *Instance) ObserveRoster(status Status, reason string, ok bool, at time.Time) bool

ObserveRoster offers the roster's answer for this session, observed at at (when the query started). ok false means the roster had no opinion. Reports whether the status or wait reason changed. Call it on the Update goroutine.

func (*Instance) Pane added in v0.13.0

func (i *Instance) Pane() AgentPane

Pane returns the agent pane's lifecycle surface. It is never nil; 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.

It refuses a worktree locked with `git worktree lock` before it stashes or closes anything, and while another Pause or a Resume of the same worktree is running (see opsInFlight).

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 under a freshly resolved env — the account's CLAUDE_CONFIG_DIR (or Headroom Proxy / Cache TTL toggle) may have changed since the dead session was built — 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. A launch whose account no longer resolves refuses before touching anything: no close, no flag reset, nothing to undo.

func (*Instance) RestartFailureCountForTest added in v0.14.0

func (i *Instance) RestartFailureCountForTest() int

RestartFailureCountForTest reports the current consecutive-failure count of the workspace terminal's restart breaker (RecordRestartFailure).

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.

It refuses, before anything changes, while a Pause or another Resume of the same worktree is running (see opsInFlight).

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

func (*Instance) SessionHome added in v0.14.0

func (i *Instance) SessionHome() SessionHome

SessionHome is where i's own tmux session starts (see the type).

func (*Instance) SetAccount added in v0.14.0

func (i *Instance) SetAccount(name string)

SetAccount records the account the next launch runs under. account.DefaultName and "" both mean the default account.

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) SetTmuxSessionForTest added in v0.14.0

func (i *Instance) SetTmuxSessionForTest(session *tmux.Session)

SetTmuxSessionForTest sets the instance's tmux session, so a test can run the lifecycle and pane paths over a mock executor.

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) StatusSince added in v0.14.0

func (i *Instance) StatusSince() time.Time

StatusSince returns when the instance entered its current status, or the zero time when no transition has been observed this process. StatusAge is the time since then.

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, when the instance is in a status where no agent can be running (Paused, Recoverable, Deleting), or when subagent tracking is turned off.

func (*Instance) TmuxSession

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

TmuxSession returns the instance's tmux session (lifecycle only: launch, probe, kill, type text through paste-buffer and keys through send-keys), or nil if the instance has not been started. The app takes a full-screen attach command from it.

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"`
	// ClaudeSessionID and ClaudeTranscriptPath name the Claude
	// conversation a crash relaunch resumes with --resume: the session ID
	// and transcript of the latest parent SessionStart hook. Empty until
	// one is seen, which means --continue. Added in schema v7.
	ClaudeSessionID      string `json:"claude_session_id,omitempty"`
	ClaudeTranscriptPath string `json:"claude_transcript_path,omitempty"`
	// Account is the Claude account the session runs on ("" = default),
	// resolved to a CLAUDE_CONFIG_DIR at every launch. Added in schema v8.
	Account string `json:"account,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).

CreatedAt is when the worktree was made (WorktreeCreatedAt), not when it was discovered: the instance's ID derives from it, so every daemon and every load must read the same value from the same worktree.

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; v6→v7 adds ClaudeSessionID and ClaudeTranscriptPath; v7→v8 adds Account — 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 LaunchEnv added in v0.14.0

type LaunchEnv struct {
	Program       string
	HeadroomProxy bool
	CacheTTL1h    bool
	// ClaudeConfigDir is the CLAUDE_CONFIG_DIR of the account the session
	// runs on; empty for the default account.
	ClaudeConfigDir string
}

LaunchEnv is everything about an instance's launch that becomes tmux session environment rather than part of the program string.

type MissingAccountError added in v0.14.0

type MissingAccountError struct{ Name string }

MissingAccountError is a launch refused because the instance's account is not registered. A launch never falls back to the default account: that would bill the wrong subscription. The text names R because that is how the user actually recovers an existing session (relaunch with options, choosing a different account); it also fires on a brand-new Start, which removes the instance on failure instead — the wording stays accurate there too, since "pick another account" still applies and the parenthetical only claims R for an existing session.

func (*MissingAccountError) Error added in v0.14.0

func (e *MissingAccountError) Error() string

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`, a stash entry it could not drop, or Claude's archived scratchpad it could not restore. 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
	// Account is the account a live session's agent runs on
	// (liveSessionAccount), so adopting it keeps the account it is
	// billed to; "" (the default account) without a live session, whose
	// account nothing on disk records.
	Account string
	// 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 RegistryLoadError added in v0.14.0

type RegistryLoadError struct {
	Name string
	Err  error
}

RegistryLoadError is a launch refused because the account registry itself failed to load (a corrupt or unreadable accounts.json), so loom cannot tell whether the instance's account still exists. Distinct from MissingAccountError, whose "not registered" means the registry loaded fine and simply has no entry for this name — reporting that instead here would tell the user to pick another account when the real account may still be fine.

func (*RegistryLoadError) Error added in v0.14.0

func (e *RegistryLoadError) Error() string

func (*RegistryLoadError) Unwrap added in v0.14.0

func (e *RegistryLoadError) Unwrap() error

type RemoteControlAuth added in v0.3.0

type RemoteControlAuth struct {
	State  RemoteControlAuthState
	Reason string
	// Identity is what `claude auth status` reported; zero when it did
	// not run or did not parse.
	Identity account.Identity
}

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 is DetectClaudeRemoteControlAuthEnv for the default account.

func DetectClaudeRemoteControlAuthEnv added in v0.14.0

func DetectClaudeRemoteControlAuthEnv(program string, env []string, runner internalexec.Executor) RemoteControlAuth

DetectClaudeRemoteControlAuthEnv determines whether the Claude account selected by env (nil: the default account) can establish a --remote-control session, and carries the identity `claude auth status` reported — read before the override check below, and attached to every Blocked result including one from an override, so callers that show the account's identity (the usage strip, Launch Options, the Accounts overlay) still have it even when remote control itself is blocked. 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 SessionHome added in v0.14.0

type SessionHome struct {
	// Dir is the record's repository (a workspace terminal's) or worktree.
	Dir string
	// Exact means only Dir itself, not a directory below it.
	Exact bool
}

SessionHome is where a record's own tmux session starts. A workspace terminal's starts in its repository itself (loom launches it with -c <repo>), so only an exact match is its own: the repository also holds <repo>/.loom/worktrees, where an agent titled after the workspace starts its session under the terminal's tmux name. Any other record's session starts in its worktree or below it.

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. 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) LoadInstanceDataForTest added in v0.14.0

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

LoadInstanceDataForTest loads the raw serialized instance data, as the write paths see it: every record that decodes, migrated to CurrentSchemaVersion, and none that does not (those are 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) UpdateInstanceForTest added in v0.14.0

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

UpdateInstanceForTest replaces the persisted record for an existing instance with its in-memory snapshot, through the raw-data write path DeleteInstance takes, 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 claudetmp finds, archives and restores the per-session temp directory Claude Code keeps outside the worktree: <root>/<encoded cwd>/<session id>/{scratchpad,tasks}/.
Package claudetmp finds, archives and restores the per-session temp directory Claude Code keeps outside the worktree: <root>/<encoded cwd>/<session id>/{scratchpad,tasks}/.
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 hooks is loom's side of the Claude Code hooks it registers at launch: the per-instance folder layout, the settings file and hook command, and the scan that turns the files the hooks write into Events.
Package hooks is loom's side of the Claude Code hooks it registers at launch: the per-instance folder layout, the settings file and hook command, and the scan that turns the files the hooks write into Events.
Package launch is a Claude session's launch options and their composition into (and decoding from) the agent command line: remote control, permission mode, model, effort, plus the options that never reach the command line (Headroom proxy, the 1h cache TTL, the branch prefix, the account).
Package launch is a Claude session's launch options and their composition into (and decoding from) the agent command line: remote control, permission mode, model, effort, plus the options that never reach the command line (Headroom proxy, the 1h cache TTL, the branch prefix, the account).
Package subagent tracks the subagents and agent-team teammates a Claude session has spawned, from the hook events session/hooks collects.
Package subagent tracks the subagents and agent-team teammates a Claude session has spawned, from the hook events session/hooks collects.
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