sessionrestore

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 16 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 sessionrestore decides what a cold restore would do, and says why.

The decision is a pure function. Everything the planner needs — which shells were confirmed live in the previous tmux server, which sessions exist now, whether each recorded working directory still exists, what the policy says, which providers can actually resume, and which conversations are claimed twice — arrives as data in an Input, and a Plan comes back. There is no tmux call, no filesystem walk, and no provider spawn in this package.

That shape is deliberate rather than aesthetic. A restore is the one moment when Sidecar recreates state it cannot see, after an event that destroyed the evidence, and the failure the plan is most concerned with is not a crash but a confident wrong answer: resuming a conversation into the wrong repository, starting a second copy of an agent that is already running, or replaying a command nobody asked to replay. Those are all decisions, not effects, so they are all testable here without a terminal.

The executor in this package's sibling file performs the plan, and rechecks every precondition again at the moment of mutation. The plan is what should happen; the recheck is what makes it safe to act on a plan built from a snapshot that may already be stale.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoBinding = errors.New("no session reference is bound to this shell")

ErrNoBinding reports that a shell has no exact session reference to resume.

View Source
var ErrServerReplaced = errors.New("the tmux server was replaced while restoring")

ErrServerReplaced aborts a run whose tmux server changed underneath it.

Functions

func ResumePlanFor

func ResumePlanFor(step Step, namespace string) (agentsession.ResumePlan, error)

ResumePlanFor re-reads a step's exact session binding and builds the resume.

It goes through shellstate rather than through the plan's own copy on purpose: this is the binding recheck the executor calls at the moment of resuming, and reading it from the manifest is what makes it a recheck rather than a restatement of what was already believed. An integration can have rotated or cleared the reference in between.

Types

type Action

type Action string

Action is the verdict for one managed shell. The vocabulary is the plan's: reattach, recreate-shell, resume-agent, manual, skip, refuse.

const (
	// ActionReattach means the tmux session is still live and the existing pane
	// layout will find it by name. Nothing is created.
	ActionReattach Action = "reattach"
	// ActionRecreateShell means a fresh shell will be created under the same
	// tmux session name and working directory, with no agent started.
	ActionRecreateShell Action = "recreate-shell"
	// ActionResumeAgent means the shell will be recreated and the exact bound
	// conversation resumed in it. This is the only action that runs an agent.
	ActionResumeAgent Action = "resume-agent"
	// ActionManual means the record is kept and recoverable, but Sidecar will not
	// act on it automatically. The user can recreate or resume it deliberately.
	ActionManual Action = "manual"
	// ActionSkip means policy or configuration says to leave this shell alone.
	ActionSkip Action = "skip"
	// ActionRefuse means restoring would require doing something unsafe — using a
	// directory that no longer exists, or taking a session name something else
	// currently holds. The record is kept and the reason is shown.
	ActionRefuse Action = "refuse"
)

type AgentStep

type AgentStep struct {
	// Kind is the provider family id.
	Kind string `json:"kind"`
	// RefKind is "id" or "path", or empty when there is no reference.
	RefKind string `json:"refKind,omitempty"`
	// Reported is whether an official integration vouched for the reference.
	Reported bool `json:"reported"`
	// Resume is whether this plan would actually resume the conversation.
	Resume bool `json:"resume"`
	// Reason explains the verdict either way.
	Reason Reason `json:"reason"`
	// ConflictWith names the shell that won deduplication, when this one lost.
	ConflictWith string `json:"conflictWith,omitempty"`
}

AgentStep is the resume verdict for one shell.

It deliberately carries the reference *kind* and whether it was reported, but never the reference value. A plan is printed, logged, and pasted into issues; M3 established that a conversation identifier written into a log cannot be unwritten, and a plan is exactly the kind of output that ends up there.

type Collector

type Collector struct {
	// StateDir is Sidecar's state root; project manifests live under
	// <StateDir>/projects/<key>/shells.json.
	StateDir string
	// Namespace is the tmux socket path this restore is scoped to. Records from
	// another namespace belong to a different tmux server and are not this
	// restore's business.
	Namespace string

	// LiveSessions returns the tmux session names that currently exist.
	LiveSessions func(context.Context) (map[string]bool, error)
	// ManagedSession reports whether a live session is a Sidecar-managed shell
	// rather than something else that happens to hold the name.
	ManagedSession func(context.Context, string) bool
	// ServerID returns the running tmux server as a "pid=N" id, empty when none.
	ServerID func() string
	// DirExists answers whether a recorded working directory still exists.
	DirExists func(string) bool
	// ProviderAvailable answers whether a provider binary is installed.
	ProviderAvailable func(string) bool
}

Collector reads the machine's restore candidates.

func (Collector) Collect

func (c Collector) Collect(ctx context.Context, cfg Config, req Request) (Input, error)

Collect builds the planner input.

A tmux listing that fails is reported as an error rather than as "nothing is live", because an empty inventory is what makes every shell look restorable, and acting on a listing that did not happen is how a restore would recreate shells that are running right now.

func (Collector) ManagedSessionOrDefault

func (c Collector) ManagedSessionOrDefault(ctx context.Context, session string) bool

ManagedSessionOrDefault answers whether a live session is a Sidecar-managed shell, using the collector's override when one is set and the real tmux question otherwise. The executor's rechecks go through it so that a test can drive the collision refusal without a tmux server.

func (Collector) ServerIDOrDefault

func (c Collector) ServerIDOrDefault() string

ServerIDOrDefault returns the running tmux server id, empty when none.

type Config

type Config struct {
	// RecreateShells recreates interactive managed shells that were confirmed
	// live in the previous tmux server. It defaults true.
	RecreateShells bool
	// ResumeAgents is off | ask | auto and defaults ask.
	ResumeAgents ResumeMode
}

Config is the machine default restore policy.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig is what a machine with no configuration gets.

type ConfigError

type ConfigError struct{ Value string }

ConfigError reports an unusable resumeAgents value.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type Deps

type Deps struct {
	// Live reports what currently holds a tmux session name. It is called again
	// immediately before every mutation, never read from the plan.
	Live func(session string) LiveState
	// CurrentServer returns the running tmux server id, empty when none. The
	// executor rechecks it before each mutation: if the server has been replaced
	// mid-run, everything already created is gone and continuing would build on
	// a foundation that no longer exists.
	CurrentServer func() string
	// CreateShell recreates one managed shell under its recorded name and
	// working directory. It must be idempotent on the session name.
	CreateShell func(context.Context, Step) error
	// ResumePlanFor re-reads the shell's exact session binding from the manifest
	// and builds the resume. Re-reading rather than trusting the plan is the
	// binding recheck: the reference can have been rotated or cleared by the
	// provider's own integration since the plan was built.
	ResumePlanFor func(Step) (agentsession.ResumePlan, error)
	// ResumeAgent runs the resume in the shell and returns once the provider is
	// identified and ready.
	ResumeAgent func(context.Context, Step, agentsession.ResumePlan) error
	// NoteLive records that this shell is now running under the current tmux
	// server. It is optional, and skipping it costs only accuracy in a later
	// restore.
	//
	// It exists because a restored shell's eligibility marker still named the
	// server it died in. If the user then closed that shell, its marker did not
	// match the running server, so the reap path read it as "died with its
	// server" and preserved it as a restore candidate — the same immortal
	// candidate the marker exists to prevent, reintroduced by the restore
	// itself. On a surface with a TUI the next liveness pass healed it; a
	// CLI-only workflow never did.
	NoteLive func(Step)
}

Deps are the effects the executor is allowed to have. Every one of them is injected so the crash-and-retry matrix can be driven without a tmux server.

func LocalDeps

func LocalDeps(opts LocalDepsOptions) Deps

LocalDeps binds the executor to real tmux, real shell creation, and real provider resume.

type Input

type Input struct {
	Config Config
	// CurrentServer identifies the tmux server running now, in the same "pid=N"
	// form the manifest stores. Empty means no server is running.
	CurrentServer string
	// Live reports the current tmux inventory, keyed by tmux session name.
	// A name absent from the map is LiveAbsent.
	Live map[string]LiveState
	// Shells are the candidate records across every project.
	Shells []Shell
	// DirExists answers whether a recorded working directory is still there. It
	// is injected so the planner stays pure and so the test matrix can describe a
	// deleted worktree without deleting one.
	DirExists func(path string) bool
	// ProviderAvailable answers whether a provider's binary is installed. Nil
	// means "assume available", which is only correct in tests.
	ProviderAvailable func(kind string) bool
	// Request is the caller's ask.
	Request Request
}

Input is everything the planner is allowed to know.

type LiveState

type LiveState string

LiveState is what the current tmux server says about one session name.

const (
	// LiveAbsent means no session holds the name.
	LiveAbsent LiveState = "absent"
	// LiveManaged means the name is held by this managed shell — either it
	// survived, or a previous restore attempt already recreated it.
	LiveManaged LiveState = "managed"
	// LiveForeign means the name is held by something that is not this managed
	// shell. The restore refuses; it never kills a live session to take a name.
	LiveForeign LiveState = "foreign"
)

type LocalDepsOptions

type LocalDepsOptions struct {
	// Namespace is the tmux socket path the restore is scoped to.
	Namespace string
	// ShellReady bounds the wait for a recreated shell to settle before a
	// resume is sent into it. Zero uses a sensible default.
	ShellReady time.Duration
	// ResumeReady bounds the wait for the provider to identify itself and
	// become ready. Zero uses a sensible default. There is no implicit
	// unbounded wait anywhere in this path.
	ResumeReady time.Duration
}

LocalDepsOptions tunes the timeouts of the local binding.

type Outcome

type Outcome struct {
	Step   Step   `json:"-"`
	Status Status `json:"status"`
	Reason Reason `json:"reason"`
	Detail string `json:"detail"`
	// Err is the underlying failure, if any. It is never a reason to remove a
	// shell record: a failed restore leaves exactly the state a retry needs.
	Err error `json:"-"`
}

Outcome is the executed result for one shell.

type Plan

type Plan struct {
	// ServerChanged reports that the tmux server running now is not the one the
	// candidate shells were last confirmed alive in. It is what distinguishes a
	// cold restore from an ordinary Sidecar restart, and it is evidence rather
	// than a claim: it is derived from the recorded and observed server identity.
	ServerChanged bool `json:"serverChanged"`
	// CurrentServer is the running tmux server, empty when none is running.
	CurrentServer string `json:"currentServer,omitempty"`
	// PriorServers are the distinct servers the candidates were last seen in.
	PriorServers []string `json:"priorServers,omitempty"`
	// Steps are ordered by project then session name, so two runs over the same
	// state produce the same document.
	Steps []Step `json:"steps"`
}

Plan is the ordered set of verdicts plus the server evidence behind them.

func Build

func Build(in Input) Plan

Build computes the plan. It performs no I/O.

func (Plan) Executable

func (p Plan) Executable() []Step

Executable reports the steps the executor would actually perform.

func (Plan) PendingConfirmation

func (p Plan) PendingConfirmation() []Step

PendingConfirmation reports the steps held only by a missing confirmation.

func (Plan) WouldExecuteAgents

func (p Plan) WouldExecuteAgents() bool

WouldExecuteAgents reports whether performing this plan runs any agent.

type Reason

type Reason string

Reason is the stable machine code explaining an Action.

These are codes, not sentences, for the same reason agentcontrol's error codes are: a caller that has to match on prose is a caller that breaks when the prose improves. The human sentence travels alongside in Detail.

const (
	// ReasonAlreadyLive — the tmux session survived; there is nothing to restore.
	ReasonAlreadyLive Reason = "already_live"
	// ReasonNotPriorLive — the shell was not confirmed live in the previous tmux
	// server incarnation, so it is not a cold-restore candidate.
	ReasonNotPriorLive Reason = "not_prior_live"
	// ReasonDiedInThisServer — the shell's last confirmed server is the one
	// running now, so it exited on its own rather than dying with the server.
	// Recreating it would be reviving something the user or a program closed.
	ReasonDiedInThisServer Reason = "died_in_this_server"
	// ReasonPolicyNever — this shell's per-shell policy is never.
	ReasonPolicyNever Reason = "policy_never"
	// ReasonRecreateDisabled — recreateShells is off in configuration.
	ReasonRecreateDisabled Reason = "recreate_disabled"
	// ReasonMissingWorkDir — the recorded working directory does not exist. This
	// is a refusal and never a fallback to some other directory.
	ReasonMissingWorkDir Reason = "missing_workdir"
	// ReasonNoWorkDir — the record predates working-directory capture, so there
	// is no directory to recreate it in.
	ReasonNoWorkDir Reason = "no_workdir"
	// ReasonNameCollision — something that is not this managed shell already
	// holds the tmux session name. Never resolved by killing it.
	ReasonNameCollision Reason = "name_collision"
	// ReasonNotSelected — a --shell target was given and this is not it.
	ReasonNotSelected Reason = "not_selected"
	// ReasonRecreatable — the shell will be recreated; used on the agent verdict
	// when the shell part succeeds but no agent is involved.
	ReasonRecreatable Reason = "recreatable"

	// ReasonNoSessionRef — no official integration ever reported a conversation
	// for this shell, so there is nothing exact to resume.
	ReasonNoSessionRef Reason = "no_session_ref"
	// ReasonUnreportedRef — a reference exists but no official integration
	// vouched for it. A same-cwd guess is a suggestion, not a command.
	ReasonUnreportedRef Reason = "unreported_ref"
	// ReasonProviderNoResume — the provider has no native resume command.
	ReasonProviderNoResume Reason = "provider_no_resume"
	// ReasonProviderUnavailable — the provider's binary is not installed here.
	ReasonProviderUnavailable Reason = "provider_unavailable"
	// ReasonProviderRejectedRef — the provider cannot resume from this kind of
	// reference, or the catalog refused to build the argv.
	ReasonProviderRejectedRef Reason = "provider_rejected_ref"
	// ReasonDuplicateRef — another managed shell claims the same conversation and
	// won deduplication. This one restores as a plain shell.
	ReasonDuplicateRef Reason = "duplicate_ref"
	// ReasonResumeOff — resumeAgents is off, or the per-shell policy is shell.
	ReasonResumeOff Reason = "resume_off"
	// ReasonNeedsConfirmation — the effective policy is ask and no confirmation
	// has been given. Nothing is executed until it is.
	ReasonNeedsConfirmation Reason = "needs_confirmation"
	// ReasonAgentsNotRequested — the caller did not ask for agent resumes.
	ReasonAgentsNotRequested Reason = "agents_not_requested"
	// ReasonPolicyResume — the resume is authorized and will run.
	ReasonPolicyResume Reason = "policy_resume"
	// ReasonKindDisagreement — the record names two different providers, so
	// which CLI would be handed the conversation is not knowable from it. The
	// shell is recreated; the conversation is not resumed by either.
	//
	// This is a refusal rather than a preference on purpose. A reader that picks
	// a field is a reader that will eventually run `claude --resume` on a grok
	// conversation id, which is the exact defect that produced these records.
	ReasonKindDisagreement Reason = "kind_disagreement"
)

type Request

type Request struct {
	// OnlyShell limits the plan to one tmux session name. Other shells are
	// reported as not_selected rather than omitted, so the output still accounts
	// for every record.
	OnlyShell string
	// Agents is the --agents flag: the caller is asking for eligible resumes.
	// Without it a CLI restore does shells only, whatever the policy allows.
	Agents bool
	// Confirmed records that a human confirmed — --yes, or a TUI confirmation.
	// It is what turns an ask-policy resume from planned into executable.
	Confirmed bool
	// Startup marks the automatic post-first-frame restore, which follows
	// configuration rather than an explicit request and so implies Agents.
	Startup bool
}

Request is what the caller asked for, as distinct from what is configured.

type Result

type Result struct {
	Plan     Plan
	Outcomes []Outcome
}

Result is the whole execution.

func Execute

func Execute(ctx context.Context, plan Plan, deps Deps) Result

Execute performs a plan, rechecking every precondition at the moment of use.

It never kills a live session to take its name, never deletes or rewrites a shell record on failure, and stops the run rather than continuing across a tmux server replacement.

func (Result) Counts

func (r Result) Counts() map[Status]int

Counts summarises the result for a grouped summary line.

func (Result) Failed

func (r Result) Failed() []Outcome

Failed reports the retryable failures.

type ResumeMode

type ResumeMode string

ResumeMode is the machine-wide resumeAgents setting.

const (
	// ResumeOff never resumes a conversation automatically.
	ResumeOff ResumeMode = "off"
	// ResumeAsk restores shells and layout, then asks once before running any
	// agent. It is the default, because a resume can cost money and can mutate a
	// repository, and neither should follow from a reboot alone.
	ResumeAsk ResumeMode = "ask"
	// ResumeAuto is explicit standing authorization for exact, officially
	// reported references only.
	ResumeAuto ResumeMode = "auto"
)

func ParseResumeMode

func ParseResumeMode(value string) (ResumeMode, error)

ParseResumeMode accepts a mode name. Empty means the default, ask.

func ResumeModes

func ResumeModes() []ResumeMode

ResumeModes lists the vocabulary in a stable order.

type Shell

type Shell struct {
	// Project is the project key whose manifest holds the record.
	Project string
	// ProjectRoot is that project's working tree, which is where a recreated
	// shell's record already says it belongs. It is never used as a fallback
	// directory for a shell whose own WorkDir has gone: that case is a refusal.
	ProjectRoot string
	// ManifestPath is where the record lives, so the executor can write the
	// outcome back without re-deriving the path.
	ManifestPath string
	// Def is the stored record.
	Def shellstate.Definition
}

Shell is one candidate record with the project it belongs to.

type Status

type Status string

Status is what execution did to one shell.

const (
	// StatusReattached means the session was already live and nothing was done.
	StatusReattached Status = "reattached"
	// StatusRestored means a shell was created under its own name and cwd.
	StatusRestored Status = "restored"
	// StatusResumed means the shell was restored and its exact conversation
	// resumed. It is the only status that implies an agent process was run.
	StatusResumed Status = "resumed"
	// StatusConverged means the work was already done — by a previous
	// interrupted run, another Sidecar, or the user. Nothing was created.
	StatusConverged Status = "converged"
	// StatusSkipped means the plan did not call for action here.
	StatusSkipped Status = "skipped"
	// StatusRefused means acting would have required something unsafe.
	StatusRefused Status = "refused"
	// StatusFailed means the action was attempted and did not succeed. The shell
	// record is untouched and the step is retryable.
	StatusFailed Status = "failed"
)

type Step

type Step struct {
	Project string `json:"project"`
	// Session is the tmux session name, which is also the idempotency key: the
	// executor's every recheck is keyed on it, so a crashed and retried restore
	// converges on one shell rather than creating a second.
	Session string `json:"session"`
	Name    string `json:"name,omitempty"`
	WorkDir string `json:"workDir,omitempty"`

	// ProjectRoot is the project's working tree, carried for the executor.
	ProjectRoot string `json:"projectRoot,omitempty"`

	Action Action `json:"action"`
	Reason Reason `json:"reason"`
	// Detail is the human sentence for the same verdict.
	Detail string `json:"detail"`
	// ExternalExecution is true when performing this step would run an agent
	// process — the thing that can cost money and mutate a repository. The plan
	// requires status and dry-run to say this per shell, so a reader can answer
	// "will this spend anything" without decoding the policy matrix themselves.
	ExternalExecution bool `json:"externalExecution"`
	// NeedsConfirmation is true when a resume is otherwise authorized and only a
	// human confirmation is missing.
	NeedsConfirmation bool `json:"needsConfirmation,omitempty"`
	// Agent is the resume verdict, present whenever the shell has agent metadata.
	Agent *AgentStep `json:"agent,omitempty"`
	// contains filtered or unexported fields
}

Step is the ordered verdict for one managed shell.

func (Step) ManifestPath

func (s Step) ManifestPath() string

ManifestPath is where the executor writes this step's outcome.

Jump to

Keyboard shortcuts

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