shellstate

package
v1.16.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package shellstate owns Sidecar shell definitions, validation and persistence. It is deliberately independent of both the TUI and CLI transports.

Index

Constants

View Source
const (
	NameEnv    = "SIDECAR_SHELL_NAME"
	SessionEnv = "SIDECAR_SHELL"
)

NameEnv carries the current display name into the shell's environment, and SessionEnv the tmux session that owns it. An agent that can read its own shell name can tell a default ("Shell 9") from a real one, which is what makes the rename instruction actionable rather than a rule to remember.

View Source
const (
	// ManagedEnv is the boolean cue, set to "1". It is the single check a hook
	// makes before doing anything at all.
	ManagedEnv = "SIDECAR_MANAGED_SHELL"

	// ServerEnv carries the tmux server's PID, which is how lifecycle records
	// are namespaced by server incarnation.
	//
	// The PID rather than tmuxserver.Incarnation.String() is deliberate, and
	// the difference is not cosmetic: that string embeds the socket ctime,
	// which tmux bumps every time the attached-client set changes. Namespacing
	// stored records by it would silently orphan every report the moment a user
	// attached or detached a client, returning a healthy pane to screen
	// fallback for no visible reason. The PID is stable for the server's
	// lifetime and new after a restart, which is exactly the property the
	// namespace needs, and it is what agentcontrol already compares.
	ServerEnv = "SIDECAR_TMUX_SERVER"

	// HostEnv carries the host that owns the pane. Reports never cross hosts; a
	// registered remote resolves its own state locally.
	HostEnv = "SIDECAR_HOST"

	// BinEnv carries the absolute path of the Sidecar binary that created the
	// shell, for provider hook formats that need a command to invoke. It exists
	// so an asset never has to guess a path or search PATH, and so nothing has
	// to shell-compose one.
	BinEnv = "SIDECAR_BIN"

	// NamespaceEnv carries the tmux socket path that identifies this host-local
	// namespace. It is an identifier for diagnostics and matching, never a
	// location anything is written to.
	NamespaceEnv = "SIDECAR_NAMESPACE"
)

The managed-shell environment contract.

These are published alongside NameEnv and SessionEnv when Sidecar creates a shell, and they are what lets a provider hook running inside that shell know it may report lifecycle state, and for which pane. A hook that finds ManagedEnv unset exits successfully and silently: outside a Sidecar shell there is nothing to report to and nothing to complain about.

Two rules shape this list. Nothing here is a writable path — the report command resolves Sidecar's state directory itself, so provider input can never redirect where lifecycle records are written. And nothing here is trusted on its own: the report command re-derives the live pane and server from tmux and refuses a report whose claimed context does not match.

View Source
const CurrentVersion = 3

CurrentVersion is the shells.json schema version this binary writes.

Version 2 is version 1 plus the `tombstones` array. The bump exists so the version field stops being decoration: a writer that finds a version it does not understand now refuses the write instead of marshalling its own narrower struct over the file and silently dropping every key it could not parse. That is the same failure mode the whole shell-record durability plan is about — one writer destroying information it does not understand — one level up, in the format itself.

A v1 file is upgraded in place on the first write: v1 is a subset of v2, so there is nothing to migrate beyond the number.

Version 3 adds the per-shell `agent` and `restore` objects: the structured provider binding, the exact native session reference an official integration reported, and the cold-restore policy and eligibility. Like v1→v2 the change is purely additive, so v3 needs no migration step either — a v2 file read by this build simply has no agent or restore object on any record, which is exactly what "this shell has never run a reported agent" already means.

The bump is what buys the refusal in the other direction, and here it matters more than it did for tombstones. A v2 binary that rewrote a v3 file would drop the session reference, and the visible symptom would not be an error: it would be a cold restore that quietly declines to resume a conversation it was holding a valid reference for. CheckWritableVersion is what prevents that.

View Source
const MaxNameBytes = 50
View Source
const NamingInstruction = "This terminal is a Sidecar project shell. Learn its display name from $" + NameEnv +
	" as a cue (it may be empty on older shells, or lag after a rename in this process), or run " +
	"`sidecar shell name` for the authoritative name from Sidecar's manifest. \"Shell 3\" is the unset default; " +
	"a previous task's name is equally stale. Keep the name aligned with your current task: at the start of work " +
	"and whenever context changes materially, if the name does not describe what you are doing now, run " +
	"`sidecar shell rename \"short context\"`. Update at meaningful boundaries, not every sub-step. Prefer the " +
	"outcome (\"shell rename implementation\") over the model or a transient action (\"Codex running tests\"). " +
	"These commands act only on the current Sidecar shell; never edit shells.json or rename tmux sessions directly."

NamingInstruction is the canonical guidance for keeping a shell's display name useful. It lives here, next to the rules it describes, so every delivery channel — AGENTS.md, a harness system-prompt append, help text — quotes one source instead of drifting copies.

The trigger is "name does not describe current work," not only the generated "Shell N" default — a leftover previous-task name is equally stale.

Variables

View Source
var ErrKindDisagreement = errors.New("this shell's record names two different agent kinds")

ErrKindDisagreement reports a record whose two provider fields name different providers. It is a read-time refusal, not a repair: nothing here can tell which of the two is the mistake, and every way of choosing produces the failure the fields exist to prevent — one provider's CLI handed another provider's conversation.

View Source
var ErrNoManifestPath = errors.New("shell manifest has no path")

ErrNoManifestPath refuses a pathless handle before it can create a relative .lock or .tmp file next to the caller's working directory.

View Source
var ErrShellChanged = errors.New("shell entry was replaced since it was observed")

ErrShellChanged reports that the entry on disk is not the one the caller looked at, so the removal was refused.

View Source
var ErrUnknownVersion = errors.New("written by a newer Sidecar; upgrade Sidecar to write it")

ErrUnknownVersion reports a manifest written by a newer Sidecar than this one. Callers that want to distinguish "the file is from the future" from an ordinary IO failure test for it with errors.Is.

View Source
var ObserveLiveCountWrite = func(path string, before, after int, identityRemoval bool) {}

ObserveLiveCountWrite is the shells.json writer-boundary hook. Every path that replaces the file calls it after computing the next live list and before the rename. before and after are len(shells), not tombstones. identityRemoval is true only for RemoveAtPath, RemoveIfUnchangedAtPath, and the workspace RemoveShell equivalent — the only functions allowed to shrink the live list.

Tests wrap this instead of grepping call sites.

Functions

func AddAtPath added in v1.0.0

func AddAtPath(path string, def Definition) error

AddAtPath records one shell definition with the same locked, atomic read-before-write semantics used by rename. It is the state-free persistence boundary used by project and cross-project shell hosts.

func AgentKindOf added in v1.11.0

func AgentKindOf(def Definition) (kind, conflict string)

AgentKindOf answers "what provider does this record name", and — because a record can name two — "does it disagree with itself".

AgentType and Agent.Kind are documented as the same value and are written together by every writer here, but a record produced before that invariant existed can hold two different providers: a mis-attributed hook report set Agent.Kind and left AgentType alone. Readers preferring one field silently picked a side, which is how a shell created for grok came to offer `claude --resume` on a grok conversation id.

So the disagreement is returned rather than resolved. This package will not guess which field is right; a caller about to act on the answer — running a provider CLI against a stored conversation id, above all — is expected to refuse instead. conflict is empty whenever the record is self-consistent, which is every record any current writer produces.

func CheckWritableVersion added in v1.9.0

func CheckWritableVersion(version int) error

CheckWritableVersion reports whether a manifest carrying this version may be rewritten. Reads are always allowed — a newer file still parses into the fields this build knows, and refusing to read it would break `sidecar shell name` against a manifest a newer binary touched. Only writes are refused, because a write is what loses the fields.

func CompleteRestorePrefillAtPath added in v1.15.0

func CompleteRestorePrefillAtPath(path string, id Identity, at time.Time) error

CompleteRestorePrefillAtPath records that the claimed terminal write succeeded. It never creates a claim by itself.

func DescribeLastAgentActivity added in v1.15.0

func DescribeLastAgentActivity(kind, status string, changedAt time.Time) string

DescribeLastAgentActivity formats observed activity without inventing timing.

func EnsureWithAvailableNameAtPath added in v1.15.0

func EnsureWithAvailableNameAtPath(path string, def Definition) error

EnsureWithAvailableNameAtPath records a new identity using the preferred display name, or its first available numbered variant. Existing identities retain their name and metadata. Allocation and insertion share the manifest lock so concurrent automatic creations cannot claim the same name.

func IsAlready added in v1.6.0

func IsAlready(err error) bool

func IsNotFound added in v1.6.0

func IsNotFound(err error) bool

func IsUnknownVersion added in v1.9.0

func IsUnknownVersion(err error) bool

IsUnknownVersion reports whether err is a refusal to rewrite a newer-than-understood manifest.

func IsValidation

func IsValidation(err error) bool

func MarkRestorePrefilledAtPath added in v1.15.0

func MarkRestorePrefilledAtPath(path string, id Identity, at time.Time) (bool, error)

MarkRestorePrefilledAtPath claims the one permitted prefill for a shell. The claim is persisted before terminal input so a crash can never cause a retry to type a second command into the same prompt.

func NormalizeName

func NormalizeName(name string) (string, error)

func ObserveLiveAtPath added in v1.11.0

func ObserveLiveAtPath(path, serverID string, live []Identity, now time.Time) (int, error)

ObserveLiveAtPath records that these shells are running under this tmux server, so a later cold restore can tell a shell that died with the server from one nobody had open.

It is the marker source open question 3 settles on, and it is deliberately parsimonious in two ways.

It writes only on a transition. A record already marked eligible under this same server id is left completely alone — not even its timestamp is touched — so the steady state is one write per shell per tmux-server lifetime rather than one per refresh cycle. That is the plan's rule that shell records are written on meaningful transitions and not on every capture, and it is the reason LastSeenAliveAt means "when this shell was first confirmed alive in this server" rather than "when it was last polled".

It takes the server as a caller-resolved "pid=N" id rather than an Incarnation, because the pid is the part that is safe to persist: the socket inode and ctime that Incarnation.String() carries are rewritten by tmux whenever the attached-client set changes, so a marker keyed on them would read as a server replacement every time a user attached a client.

It returns the number of records it changed, which is zero on the overwhelming majority of calls.

func ObserveRestoredLiveAtPath added in v1.15.0

func ObserveRestoredLiveAtPath(path, serverID string, live []Identity, now time.Time) (int, error)

ObserveRestoredLiveAtPath records the new server reached by a recovery transaction while retaining its durable prefill delivery marker. Ordinary live observations intentionally clear that marker for a genuinely new lifetime.

func RecordAgentKindAtPath added in v1.11.0

func RecordAgentKindAtPath(path string, id Identity, kind string) error

RecordAgentKindAtPath records which provider family a managed shell is running.

It exists because the bind-time kind gate above can only compare a report against a kind the record already names, and until this call there was exactly one moment that wrote one: shell creation with an explicit --agent. A shell created plain and then handed a provider by `sidecar agent start` — the sequence the coordinate-agents contract actually prescribes — recorded nothing, so the gate abstained for precisely the shells an agent drives.

The caller must have already proved the provider occupies the pane. That is what makes overwriting a differing recorded kind correct rather than destructive: process-ownership evidence beats a stale creation-time preference, which is the opposite of the report path, where the kind is an unverified claim and a disagreement is a refusal.

Both kind fields are written together, for the same reason BindSessionAtPath writes them together — a record that names two providers is a record whose meaning depends on which field a reader consults. And a changed kind drops the session binding: that reference is the *previous* provider's conversation, and keeping it is how a restore comes to offer one agent's conversation to another.

func RecordCandidateAtPath added in v1.15.0

func RecordCandidateAtPath(path string, id Identity, candidate *agentsession.Candidate) (bool, error)

RecordCandidateAtPath records or clears a provider-store recovery proposal. Candidate references are always downgraded to Reported=false at this trust boundary, and a reported binding always wins over discovery.

func RemoveAtPath added in v1.0.0

func RemoveAtPath(path string, id Identity) error

RemoveAtPath forgets one exact shell identity. A missing entry is already the requested state and therefore succeeds. The definition is moved to tombstones rather than dropped, so RestoreAtPath can put it back.

func RemoveIfUnchangedAtPath added in v1.0.0

func RemoveIfUnchangedAtPath(path string, id Identity, observedAt time.Time) error

RemoveIfUnchangedAtPath forgets one shell only when the entry on disk is still the incarnation the caller observed.

An auto-close decides a shell is dead, and then takes a moment to confirm it. A shell can be created under the same tmux name inside that moment — the global browser's create writes a fresh definition — and deleting the entry then would delete a live shell's identity (td-6a4100). The comparison runs inside the same exclusive lock the creating write takes, so the two orderings are the only two possible and both are correct: create-then-remove is refused, remove-then-create leaves the new entry alone.

A zero observedAt means the caller has no incarnation to check and accepts an unconditional removal.

func ResetTombstoneRetention added in v1.9.0

func ResetTombstoneRetention()

ResetTombstoneRetention drops the cached window so the next caller re-reads config.json.

func RestorePolicyOf added in v1.11.0

func RestorePolicyOf(def Definition) agentsession.Policy

RestorePolicyOf reports a record's effective per-shell policy.

func SessionHoldersAtPath added in v1.11.0

func SessionHoldersAtPath(path, project string) ([]agentsession.Holder, error)

SessionHoldersAtPath lists the session claims recorded in one manifest.

Deduplication is a global per-host question, so a caller collects these across every registered project and hands the whole set to agentsession.Dedup.

func SessionRefAtPath added in v1.11.0

func SessionRefAtPath(path string, id Identity) (agentsession.Ref, string, bool, error)

SessionRefAtPath returns the exact session reference bound to one shell.

It is the read half of BindSessionAtPath and the only supported way to get a reference back out: the transcript reader and the restore planner both go through it rather than unmarshalling shells.json themselves.

Being the one door is what lets it carry the reconciliation. A record poisoned before the bind-time kind gate existed still sits in users' manifests, and no migration can fix it — the healing report would have to come from a provider integration that does not ship. So the refusal happens on the way out, once, here, instead of in each of the callers that would otherwise each pick a field.

func SetRestorePolicyAtPath added in v1.11.0

func SetRestorePolicyAtPath(path string, id Identity, policy agentsession.Policy) (agentsession.Policy, error)

SetRestorePolicyAtPath sets one shell's per-shell restore policy.

PolicyInherit clears the stored value rather than storing the word "inherit", so a record that follows the machine default serializes no policy at all and a v2-shaped record stays byte-identical.

func SetTombstoneRetention added in v1.9.0

func SetTombstoneRetention(window time.Duration)

SetTombstoneRetention overrides the resolved window for this process. It is for tests and for a caller that has already loaded config and wants to skip the lazy read; it does not write config.json.

func TombstoneRetention added in v1.9.0

func TombstoneRetention() time.Duration

TombstoneRetention is how long a forgotten shell record stays restorable before the next write drops it, from `shells.tombstoneRetention` in config.json. Zero means forgotten records are never expired.

The config file is read once per process and cached: every manifest write asks this question, and one of those writes is on the startup path, where AGENTS.md §Startup Latency counts file opens.

Types

type AgentBinding added in v1.11.0

type AgentBinding struct {
	// Kind is the catalog family id, e.g. "codex".
	Kind string `json:"kind,omitempty"`
	// LaunchArgv is the structured launch, recorded only for catalog-built
	// provider launches. A configured free-form agentStart shell string is
	// deliberately never stored here: it is not safely replayable, and a field
	// that sometimes holds argv and sometimes holds a command line is a field
	// whose consumers will eventually run the wrong one.
	LaunchArgv []string `json:"launchArgv,omitempty"`
	// Session is the exact native conversation reference, when an official
	// integration has reported one.
	Session *agentsession.Ref `json:"session,omitempty"`
	// Candidate is a provider-store match proposed for human review. Its Ref is
	// never Reported and therefore never authorizes automatic resume.
	Candidate *agentsession.Candidate `json:"candidate,omitempty"`
}

AgentBinding is the structured agent metadata added in schema version 3.

AgentType above remains the v2 field and stays authoritative for everything that already reads it. Kind here is the same value; it is repeated inside the binding so the agent object is self-contained for a reader that has one, and the two are kept in step by the single writer that sets them.

type Definition

type Definition struct {
	TmuxName    string `json:"tmuxName"`
	DisplayName string `json:"displayName"`
	// Namespace is the resolved tmux socket path. Empty identifies a legacy
	// entry that a headless rename must never claim as a side effect.
	Namespace string    `json:"namespace,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
	AgentType string    `json:"agentType,omitempty"`
	SkipPerms bool      `json:"skipPerms,omitempty"`
	// WorkDir is the parent worktree path this shell was created in. Empty on
	// pre-td-4819be manifests; callers infer or treat empty as current workDir.
	WorkDir string `json:"workDir,omitempty"`
	// Agent is the schema-v3 structured agent binding: what provider is running
	// here, how it was launched, and which of its own conversations it is in.
	//
	// It is a pointer so a shell that has never run an agent serializes no key
	// at all, which keeps every existing v2 record byte-identical after a v3
	// binary rewrites it.
	Agent *AgentBinding `json:"agent,omitempty"`
	// Restore is the schema-v3 per-shell restore state and policy.
	Restore *RestoreState `json:"restore,omitempty"`
}

Definition contains all information needed to recreate a shell session.

func CarryForward added in v1.11.0

func CarryForward(prior, next Definition) Definition

CarryForward returns next with every field it does not model taken from prior.

It exists because shells.json has a second serializer. The workspace plugin builds a Definition from its own in-memory ShellSession, which models the v2 fields and nothing else, and then replaces the stored record wholesale. Before v3 that was lossless, because the two structs described the same thing. With v3 it silently destroyed the session binding -- and it did so on the shell revival path, which is exactly the cold-restore moment the binding exists to serve.

The honest fix is one serializer. Until the two locking implementations can be unified, this keeps the rule in the package that owns the schema rather than in the caller that keeps forgetting it: a writer that does not model a field must carry it, not drop it. A field added to Definition in a later schema version needs a line here, and the test that pins this is the reminder.

func ListAtPath added in v1.0.0

func ListAtPath(path string) ([]Definition, error)

ListAtPath returns every shell definition recorded in the manifest at path.

It exists so callers that need to decide *which* shells to act on — the worktree delete, which must forget the shells rooted in the directory it is about to remove — can read the manifest through this package instead of unmarshalling shells.json themselves. A missing manifest is an empty project, not an error.

The result is a copy; mutating it does not affect the file. Removal is still one exact Identity at a time, so a caller that lists and then removes must tolerate the manifest changing in between (RemoveAtPath treats an entry that is already gone as success).

func RecordServerLoss added in v1.15.0

func RecordServerLoss(def Definition, observedAt time.Time, evidence string) (Definition, bool)

RecordServerLoss is the shared transition used by both manifest serializers. observedAt is loss-observation time, never the record's CreatedAt identity.

func RestoreAtPath added in v1.6.0

func RestoreAtPath(path string, id Identity) (Definition, error)

RestoreAtPath moves a forgotten definition from tombstones back onto shells. Display name, agent type, skip-perms, and workdir are left intact.

A live record is already in that state (KindAlready). An identity that is in neither list is KindNotFound.

type Error

type Error struct {
	Kind ErrorKind
	Msg  string
	Err  error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind string
const (
	KindValidation ErrorKind = "validation"
	KindNotFound   ErrorKind = "not_found"
	KindAlready    ErrorKind = "already"
	KindAmbiguous  ErrorKind = "ambiguous"
	KindState      ErrorKind = "state"
)

type Identity added in v0.97.0

type Identity struct {
	TmuxName  string
	Namespace string
}

type LookupResult added in v0.97.0

type LookupResult struct {
	Shell string `json:"shell"`
	Name  string `json:"name"`
}

func LookupCurrent added in v0.97.0

func LookupCurrent(stateDir string, id Identity) (LookupResult, error)

LookupCurrent returns the display name of the current Sidecar project shell from the registered manifest. It does not create state or depend on process environment cues, so it works for shells created before SIDECAR_SHELL_NAME injection existed.

type OriginInfo added in v1.0.0

type OriginInfo struct {
	TmuxName    string `json:"tmuxName"`
	Namespace   string `json:"namespace"`
	ProjectKey  string `json:"projectKey"`
	WorkDir     string `json:"workDir"`
	DisplayName string `json:"displayName"`
}

func LookupOrigin added in v1.0.0

func LookupOrigin(stateDir string, id Identity) (OriginInfo, error)

LookupOrigin returns origin identity and workspace root for the current shell.

type ReapOutcome added in v1.11.0

type ReapOutcome string

ReapOutcome is what a liveness-driven write did to one record.

const (
	// ReapTombstoned means the record was moved to tombstones, recoverable by
	// `sidecar shell restore` for the retention window. This is the outcome for
	// a shell that exited inside a server that is still running.
	ReapTombstoned ReapOutcome = "tombstoned"
	// ReapPreserved means the record was kept and marked as a cold-restore
	// candidate, because it did not exit — its tmux server did.
	ReapPreserved ReapOutcome = "preserved"
	// ReapDeferred means the record was kept and NOT marked, because the
	// evidence did not support either conclusion.
	//
	// This is the outcome that keeps the other two honest. Tombstoning destroys
	// a durable identity and marking eligible arranges for a shell to be
	// recreated after the next restart; both are wrong to do on a guess, and
	// they are wrong in opposite directions, so there has to be a third answer
	// for "I cannot tell". Deferring costs only that the row stays visible and
	// unmarked until the next observation that does know something.
	ReapDeferred ReapOutcome = "deferred"
	// ReapAbsent means there was no such record to act on.
	ReapAbsent ReapOutcome = "absent"
)

func ForgetOrPreserveAtPath added in v1.11.0

func ForgetOrPreserveAtPath(path string, id Identity, observedAt time.Time, server ServerState, activityEvidence ...string) (ReapOutcome, error)

ForgetOrPreserveAtPath is the liveness path's write, and the whole point of it is the case where it declines to delete.

currentServer is the tmux server observed at the moment of the write, as a "pid=N" id, or empty when no server is running at all. Two conditions preserve the record instead of tombstoning it:

  • No tmux server is running. A shell cannot be shown to have exited by a server that is not there to be asked. This is the exact shape of the incident: the listing is empty for every shell simultaneously, and the honest reading is "the server is gone", not "they all died".
  • The record was last confirmed alive under a different server. The shell did not exit; it was destroyed along with the process that was hosting it, which is precisely what a cold restore exists to undo.

In both cases the record stays in the manifest and is marked eligible, so it appears in the restore plan rather than in the tombstone list. Only a shell that vanished inside a server that is still running is tombstoned, because that is a terminal someone closed.

The CreatedAt fence from RemoveIfUnchangedAtPath is preserved for the tombstone branch: a record rewritten since it was observed is a different shell wearing a reused name.

type RenameRequest

type RenameRequest struct {
	TmuxName  string
	Namespace string
	Name      string
}

type RenameResult

type RenameResult struct {
	Shell   string `json:"shell"`
	OldName string `json:"oldName"`
	Name    string `json:"name"`
	Changed bool   `json:"changed"`
}

func RenameAtPath

func RenameAtPath(path string, req RenameRequest) (RenameResult, error)

RenameAtPath performs a locked read-before-write mutation of one manifest.

func RenameCurrent

func RenameCurrent(stateDir string, req RenameRequest) (RenameResult, error)

RenameCurrent searches registered project manifests without creating state.

type RestoreState added in v1.11.0

type RestoreState struct {
	// Policy is inherit | shell | resume | never. Empty means inherit.
	Policy agentsession.Policy `json:"policy,omitempty"`
	// Eligible records that this shell was confirmed live in the tmux server
	// incarnation named below, which is what makes it a cold-restore candidate.
	Eligible bool `json:"eligible,omitempty"`
	// LastSeenServer is the tmux server incarnation the shell was last confirmed
	// alive in, in the same "pid=N" form the lifecycle store uses.
	LastSeenServer string `json:"lastSeenServer,omitempty"`
	// LastSeenAliveAt is when that confirmation happened.
	LastSeenAliveAt time.Time `json:"lastSeenAliveAt,omitzero"`
	// ServerLostAt is stamped once, when liveness evidence first proves that the
	// server hosting this shell disappeared or was replaced.
	ServerLostAt time.Time `json:"serverLostAt,omitzero"`
	// LastAgentActivity is the last privacy-safe activity evidence available at
	// the loss transition. It is presentation context, never restore authority.
	LastAgentActivity string `json:"lastAgentActivity,omitempty"`
	// PrefilledAt records the at-most-once transition before Sidecar types a
	// resume command. A retry therefore cannot append the command twice.
	PrefilledAt time.Time `json:"prefilledAt,omitzero"`
	// PrefillClaimedAt is written before terminal input. If Sidecar exits in the
	// narrow interval before PrefilledAt is written, a retry refuses to type a
	// possibly duplicated command and reports the incomplete attempt honestly.
	PrefillClaimedAt time.Time `json:"prefillClaimedAt,omitzero"`
}

RestoreState is the schema-v3 restore eligibility and policy for one shell.

type ServerState added in v1.11.0

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

ServerState is what a caller positively knows about the tmux server at the instant of a liveness write.

It exists because the previous signature took a plain "pid=N" string and read the empty string as "no server is running". That conflated two very different facts — tmux answering "no server running", and the caller simply not having resolved a pid — and the conflation was not theoretical: two of the three production reap paths passed a socket-only identity whose pid is always zero, so every call read as "the server died" and those surfaces never tombstoned anything. A shell the user deliberately closed was preserved, marked eligible, and recreated after the next tmux restart.

Making the three states distinct in the type is what stops that from being expressible. A caller that cannot identify the server can no longer accidentally claim the server is gone.

func ServerGone added in v1.11.0

func ServerGone() ServerState

ServerGone reports that tmux itself answered "no server running". This is positive evidence of death, not an absence of evidence.

func ServerRunning added in v1.11.0

func ServerRunning(id string) ServerState

ServerRunning reports a positively identified, live tmux server. An empty id is not a running server — it is an unidentified one, and it degrades to ServerUnknown rather than being trusted.

func ServerUnknown added in v1.11.0

func ServerUnknown() ServerState

ServerUnknown reports that the caller could not determine the server's state.

func (ServerState) ID added in v1.11.0

func (s ServerState) ID() string

ID is the running server's identity, empty when there is none or it is unknown.

func (ServerState) Known added in v1.11.0

func (s ServerState) Known() bool

Known reports whether the observation says anything at all.

func (ServerState) Running added in v1.11.0

func (s ServerState) Running() bool

Running reports a positively identified live server.

type SessionOutcome added in v1.11.0

type SessionOutcome struct {
	// Decision is recorded, rotated, cleared, unchanged, or ignored.
	Decision agentsession.Decision
	// Ref is the binding in force after the update.
	Ref *agentsession.Ref
	// Kind is the provider recorded on the shell.
	Kind string
}

SessionOutcome is what a fenced update did.

func BindSessionAtPath added in v1.11.0

func BindSessionAtPath(path string, id Identity, update SessionUpdate) (SessionOutcome, error)

BindSessionAtPath applies a fenced session report to one managed shell.

The whole operation happens inside the manifest lock, and that is the point: the generation fence is a read-decide-write, so evaluating it outside the lock would let two concurrent hook processes both read the same prior state and both believe they won. Reading the prior reference under the same lock that writes the new one makes the fence actually decisive.

A losing report is not an error to the caller's process — it returns DecisionIgnored with the refusal reason so a hook can exit 0 and stay out of the provider's way, which is the fail-open rule every reporting surface here follows.

type SessionUpdate added in v1.11.0

type SessionUpdate struct {
	// Ref is the reference to store. A zero Ref with Clear set removes the
	// binding.
	Ref agentsession.Ref
	// Clear removes the stored reference instead of setting one.
	Clear bool
	// Kind is the catalog family id the report came from.
	Kind string
	// Live is the provider generation currently occupying the pane, resolved by
	// the caller from live tmux — never from the report.
	Live string
	// Now stamps the acceptance. Nil means time.Now.
	Now func() time.Time
}

SessionUpdate is one integration's fenced attempt to change a shell's session binding.

It carries the already-validated reference rather than raw provider input: validation belongs to agentsession, persistence belongs here, and keeping the two apart is what stops this package from growing a second opinion about what a legal reference looks like.

type Snapshot added in v1.16.0

type Snapshot struct {
	// Version is the schema version of the file on disk. Every writer checks
	// it with CheckWritableVersion before rewriting, and stamps CurrentVersion
	// on the way out, which is how a v1 file upgrades in place.
	Version int          `json:"version"`
	Shells  []Definition `json:"shells"`
	// Tombstones is omitted by older binaries; see Tombstone.
	Tombstones []Tombstone `json:"tombstones,omitempty"`
}

Snapshot is the shared shells.json shape, independent of any surface.

func EditAtPath added in v1.16.0

func EditAtPath(path string, fallback *Snapshot, identityRemoval bool, apply func(*Snapshot) (bool, error)) (Snapshot, bool, error)

EditAtPath is the shared persistence boundary for a single snapshot edit. It rereads under the exclusive lock, checks the schema, expires tombstones, and atomically writes only when apply reports a change. The returned snapshot is the exact state considered by the edit, including on a successful no-op. identityRemoval permits a deliberate live-count reduction to be observed as such; it is true only for forgetting or reaping an exact shell record.

A nil fallback fails closed on unreadable state. The workspace compatibility handle supplies its previous snapshot to retain its historical recovery of a missing or corrupt manifest. An explicit newer schema always refuses writes. The callback must not call another manifest operation while holding this lock.

func SnapshotAtPath added in v1.16.0

func SnapshotAtPath(path string) (Snapshot, error)

SnapshotAtPath reads one coherent manifest using the same advisory lock as writers. Missing files return the current empty shape; other read failures remain errors so each caller can apply its own recovery policy.

type Tombstone added in v1.6.0

type Tombstone struct {
	Definition
	DeletedAt time.Time `json:"deletedAt"`
}

Tombstone is a forgotten shell definition kept so RestoreAtPath can move it back, for as long as TombstoneRetention says.

It arrived with schema version 2. An older binary — one that predates CurrentVersion being read at all — ignores the field on read and drops the key on its next write. That degradation is accepted and unavoidable in that direction; what version 2 buys is the other direction, where this build refuses to rewrite a manifest whose version it does not understand rather than dropping the fields it could not parse (see CheckWritableVersion).

func ExpireTombstones added in v1.9.0

func ExpireTombstones(tombs []Tombstone, now time.Time, window time.Duration) []Tombstone

ExpireTombstones drops forgotten records deleted longer ago than the retention window. A zero or negative window keeps everything, and a tombstone with no deletedAt (written before the field existed, or by hand) is kept rather than expired immediately — the failure mode of guessing is deleting a record nobody asked to delete.

Expiry is applied at every writer boundary rather than by a sweeper: a manifest only grows when something writes it, so sweeping on write is what bounds it, and no background job has to know where the file lives.

Letting a tombstone go also makes a still-running session of that name adoptable again (EnsureShells and mergeShellState both skip forgotten names). That is intended: after the window, Sidecar no longer remembers the forget, and a session that is genuinely running should come back as a row rather than stay invisible forever.

func ListTombstonesAtPath added in v1.6.0

func ListTombstonesAtPath(path string) ([]Tombstone, error)

ListTombstonesAtPath returns forgotten shell definitions still in the manifest. A missing file is an empty list, not an error.

Records past the retention window are filtered out even though the next write is what physically removes them, so a caller never offers a restore that the write behind it would refuse.

Jump to

Keyboard shortcuts

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