controller

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 10 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 controller owns the workspace domain types, the interfaces it consumes, snapshot assembly (Observe), pure planning (BuildPlan), and reconciliation (Ensure, Stop). It depends on interfaces rather than subprocess details; the adapters that satisfy them live in internal/tmux, internal/container, and internal/state.

Index

Constants

View Source
const (
	KeyWorkspaceID = "@dev_workspace_id"
	KeySlug        = "@dev_slug"
	KeyWorktree    = "@dev_worktree"
)

The tmux session-scoped identity keys, reused verbatim from the Phase 1 Bash implementation (design §7). Adoption of live Bash-created sessions depends on these exact spellings.

Variables

View Source
var ErrContainerActionUnsupported = errors.New(
	"this workspace requires container support, which is not implemented in this build")

ErrContainerActionUnsupported reports a plan requiring container support this controller was not given. The gate is capability-shaped rather than build-shaped: a controller constructed with a container actuator executes these actions instead of refusing, with no changes here. It fires when one was not supplied.

Functions

func SessionBelongsTo

func SessionBelongsTo(s LiveSession, ws resolve.Workspace) bool

SessionBelongsTo compares all three load-bearing identity keys (design §7): a session with the right workspace ID but a contradictory slug or repository root is evidence of corruption or collision, not a match. The CLI's status and attach verdicts reuse it so the rendered identity can never drift from planning's. LiveSession.Worktree keeps its name because it mirrors the tmux user option @dev_worktree, which is unchanged; the value it carries is now the repository root.

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock supplies the timestamps the store persists.

type ContainerAction

type ContainerAction string

ContainerAction is what the execution slice should do about the container.

const (
	ContainerActionNone       ContainerAction = "none"
	ContainerActionStart      ContainerAction = "start"
	ContainerActionProbeFirst ContainerAction = "probe-first"
	ContainerActionAcquire    ContainerAction = "acquire"
)

type ContainerActuator

type ContainerActuator interface {
	StartContainer(ctx context.Context, ws resolve.Workspace, cfg config.Config) (ContainerObservation, error)
	ExecCommand(binding state.ContainerBinding, command, relDir string, env map[string]string) string
	// StopContainer stops the bound container. Already-stopped and
	// removed containers are success: the goal state holds.
	StopContainer(ctx context.Context, containerID string) error
}

ContainerActuator performs container mutations and renders container execution requests (design §5). StartContainer is the idempotent devcontainer up; ExecCommand is pure rendering from the stored binding.

type ContainerObservation

type ContainerObservation struct {
	Kind          string
	ContainerID   string
	ContainerUser string
	Workdir       string
	Health        state.Health
}

ContainerObservation is a live observation from the container adapter, as opposed to state.ContainerObservation, which is the form the store records.

type ContainerObserver

type ContainerObserver interface {
	ProbeContainer(ctx context.Context, binding state.ContainerBinding) (ContainerObservation, error)
	DiscoverContainer(ctx context.Context, ws resolve.Workspace, cfg config.Config) (*ContainerObservation, error)
	// Applies reports whether a container applies to the workspace at
	// all — enabled true always applies; auto applies when a
	// devcontainer configuration exists on disk. Observe consults it
	// before probing stored bindings under auto, so removing the
	// configuration de-containerizes the workspace.
	Applies(ctx context.Context, ws resolve.Workspace, cfg config.Config) (bool, error)
}

ContainerObserver probes an existing binding or discovers a container for a workspace that has none — post-rebuild reacquisition and devcontainer.enabled "auto" both need the workspace and configuration.

DiscoverContainer returning (nil, nil) means no container applies to this workspace: "auto" resolved to none. Observe then treats the workspace exactly like enabled "false". ProbeContainer returns a value because a binding always applies.

type ContainerSnapshot

type ContainerSnapshot struct {
	Observed *ContainerObservation
	Err      error
}

ContainerSnapshot is the container observation for this pass. Observed is nil when no observation applies (devcontainer disabled); Err is set when the observation failed, in which case Observed carries HealthUnknown.

type ContainerStartError

type ContainerStartError struct {
	ExitCode int
	Stderr   string
	TimedOut bool
	Reason   string
}

ContainerStartError preserves what design §9 requires the recorded operation to keep: the real exit status, a bounded stderr summary, and whether the start timed out. The container adapter returns it; the controller persists it.

func (*ContainerStartError) Error

func (e *ContainerStartError) Error() string

type ContainerStartOutcome

type ContainerStartOutcome string

ContainerStartOutcome classifies what StartRepositoryContainer did.

const (
	ContainerStarted        ContainerStartOutcome = "started"
	ContainerAlreadyRunning ContainerStartOutcome = "already-running"
	ContainerNoneApplies    ContainerStartOutcome = "none-applies"
)

type ContainerWindowError

type ContainerWindowError struct{ Window string }

ContainerWindowError reports a window demanding a container when none applies to the workspace.

func (*ContainerWindowError) Error

func (e *ContainerWindowError) Error() string

type Controller

type Controller struct {
	Store      Store
	Sessions   SessionObserver
	Containers ContainerObserver
	Clock      Clock
	// Actuator performs session mutations for Ensure. Nil in
	// observation-only wiring.
	Actuator SessionActuator
	// ContainerAct performs container mutations for Ensure. Nil refuses
	// any container action (the pre-adapter capability gate).
	ContainerAct ContainerActuator
}

Controller observes, plans, ensures, and stops a workspace. It depends on interfaces rather than subprocess details.

func (*Controller) Ensure

func (c *Controller) Ensure(ctx context.Context, d Desired, intents []WindowIntent, lockDir string, lockTimeout time.Duration) (EnsureResult, error)

Ensure is the design-§9 convergence loop: lock, register, final observation under the lock, plan, then at most one external mutation followed by re-observation and a transactional commit. It returns typed refusals and never mutates on uncertainty.

func (*Controller) Observe

func (c *Controller) Observe(ctx context.Context, d Desired) (Snapshot, error)

Observe assembles a snapshot. Observer failures become typed uncertainty inside the snapshot, never a guess in either direction; only a store failure aborts, because nothing can be decided without stored state.

func (*Controller) StartRepositoryContainer added in v0.5.0

func (c *Controller) StartRepositoryContainer(ctx context.Context, d RepoDesired, lockDir string, lockTimeout time.Duration) (ContainerStartOutcome, *ContainerObservation, error)

StartRepositoryContainer is autostart's engine: the container phase alone, under the repository lock. One row per repository is what keeps a shared container from being started once per session — the guarantee the dropped is_primary flag used to carry by filtering (spec §6.3). tmux is deliberately never consulted: at boot there is no tmux server, and going through Observe/BuildPlan would let the global session-unknown refusal block every container start (spec §3).

func (*Controller) Stop

func (c *Controller) Stop(ctx context.Context, d Desired, opts StopOptions, lockDir string, lockTimeout time.Duration) (StopResult, error)

Stop is the destructive counterpart of Ensure and deliberately idempotent: absent sessions and unbound containers are success, and nothing is ever destroyed on uncertainty. It targets only the identity-matched session, performs no registration, and records operations only for workspaces that already have a record.

type Desired

type Desired struct {
	Workspace resolve.Workspace
	Config    config.Config
	Digest    string
}

Desired is everything the configuration and resolver slices established about what should exist.

type EnsureAction

type EnsureAction string

EnsureAction classifies what Ensure did about the session.

const (
	EnsureCreated        EnsureAction = "created"
	EnsureAdopted        EnsureAction = "adopted"
	EnsureAlreadyRunning EnsureAction = "already-running"
)

type EnsureResult

type EnsureResult struct {
	Action                EnsureAction
	Session               string
	Drifted               bool
	Container             *ContainerObservation // nil when no container is in play
	ContainerWindowsStale bool
}

EnsureResult reports a successful Ensure. Drifted mirrors the digest comparison at observation time; a fresh creation is never drifted.

type LiveSession

type LiveSession struct {
	ID          string
	Name        string
	WorkspaceID string
	Slug        string
	Worktree    string
}

LiveSession is one live tmux session and whatever identity keys it carries; the strings are empty when the key is absent. ID is the server-assigned tmux session ID (e.g. "$3") — unlike Name, it can never be reused by a replacement session, so destructive actions target it when present.

type PaneIntent added in v0.2.0

type PaneIntent struct {
	Name    string
	Command string // empty => shell pane
	RelDir  string // config cwd, relative; "" => the window's directory
	Focus   bool
}

PaneIntent is one additional pane as configuration describes it. Panes have no location of their own: they inherit the window's.

type PaneSpec added in v0.2.0

type PaneSpec struct {
	Name    string
	Command string
	Dir     string
	Focus   bool
}

PaneSpec is one additional pane the actuator creates alongside the window's primary pane. An empty Command means the default shell; Dir is absolute. Focus marks the pane left active within its window.

type Plan

type Plan struct {
	Session    SessionAction
	RecordName bool
	Container  ContainerAction
	Reapply    bool
	Refusal    string
}

Plan is the typed outcome of one planning pass. Refusal is non-empty exactly when Session is SessionActionRefuse, and a refusing plan is global: it carries no mutating action of any kind (spec §5), so the execution slice may act on any non-refusing plan field without re-checking session state.

func BuildPlan

func BuildPlan(snap Snapshot) Plan

BuildPlan compares desired configuration, stored metadata, and observations to decide the next required actions. It is pure: same snapshot, same plan. (The spec names this operation Plan(snapshot); the Go function is BuildPlan because the result type claims the name.)

type RefusalError

type RefusalError struct{ Reason string }

RefusalError carries a refusal out of Ensure or attach; the CLI maps it to exit 6. Refusals are conflicts or uncertainty — retrying blindly is wrong, which is why they are distinguishable from generic failure.

func (*RefusalError) Error

func (e *RefusalError) Error() string

type RepoDesired added in v0.5.0

type RepoDesired struct {
	Repository state.Repository
	Config     config.Config
	Digest     string
}

RepoDesired is the container phase's input. A container belongs to a repository, so starting one needs no session and reads no workspace row (spec §6.3).

type SessionAction

type SessionAction string

SessionAction is what the execution slice should do about the session.

const (
	SessionActionNone   SessionAction = "none"
	SessionActionAdopt  SessionAction = "adopt"
	SessionActionCreate SessionAction = "create"
	SessionActionRefuse SessionAction = "refuse"
)

type SessionActuator

type SessionActuator interface {
	CreateSession(ctx context.Context, spec SessionSpec) error
	// KillSession ends one session. The target is the observed tmux
	// session ID when available ("$"-prefixed, immune to name reuse)
	// and the exact session name otherwise. A session that vanished
	// before the kill is success: stop is idempotent.
	KillSession(ctx context.Context, target string) error
}

SessionActuator creates the workspace session. It is the mutating counterpart of SessionObserver; adapters implement both.

type SessionObservation

type SessionObservation struct {
	ByIdentity *LiveSession
	ByName     []LiveSession
}

SessionObservation reports both halves of the query. The identity session, when live under a candidate name, also appears in ByName.

type SessionObserver

type SessionObserver interface {
	ObserveSession(ctx context.Context, q SessionQuery) (SessionObservation, error)
}

SessionObserver reports live tmux sessions. Its granularity is provisional until the tmux adapter slice exists.

type SessionQuery

type SessionQuery struct {
	WorkspaceID    string
	CandidateNames []string
}

SessionQuery asks the observer for the session carrying the workspace's identity keys and for any session occupying a candidate name, so planning can distinguish adoption from a foreign session squatting on a name this workspace would use.

type SessionSnapshot

type SessionSnapshot struct {
	State      SessionState
	ByIdentity *LiveSession
	ByName     []LiveSession
	Err        error
}

SessionSnapshot is tri-state session knowledge. Err is set exactly when State is SessionUnknown.

type SessionSpec

type SessionSpec struct {
	Name        string
	WorkspaceID string
	Slug        string
	Worktree    string
	Env         map[string]string
	Windows     []WindowSpec
}

SessionSpec is everything CreateSession needs. Env carries the workspace's configured environment: it is part of the digested desired document and must reach every window (open/attach spec §4). Windows is never empty — derivation supplies an implicit shell window.

type SessionState

type SessionState string

SessionState is tri-state knowledge about the workspace's tmux session. Unknown means observation failed: a tmux outage is not absence, and no mutating action may be derived from it.

const (
	SessionLive    SessionState = "live"
	SessionAbsent  SessionState = "absent"
	SessionUnknown SessionState = "unknown"
)

type Snapshot

type Snapshot struct {
	Desired   Desired
	Stored    *state.Record
	Session   SessionSnapshot
	Container ContainerSnapshot
}

Snapshot is one observation pass: desired state, stored state (nil when unregistered), and tri-state knowledge about the session and container.

type StopOptions added in v0.5.0

type StopOptions struct {
	Container bool
	Force     bool
}

StopOptions selects a stop's destructive scope. Force overrides the shared-container refusal below and nothing else.

type StopResult

type StopResult struct {
	SessionStopped   bool
	SessionName      string
	ContainerStopped bool
	ContainerID      string
}

StopResult reports what Stop actually did. On error it still carries what succeeded before the failure, so the CLI can report a partial stop honestly (spec §1).

type Store

type Store interface {
	RegisterWorkspace(ws resolve.Workspace, desiredDigest string, now time.Time) error
	AllocateSessionName(workspaceID string, now time.Time) (string, error)
	AdoptSessionName(workspaceID, name string, now time.Time) error
	RecordContainerObservation(repositoryID string, obs state.ContainerObservation, now time.Time) error
	RecordOperation(workspaceID string, op state.Operation, now time.Time) error
	CommitReconciliation(workspaceID string, r state.ReconciliationResult, now time.Time) error
	Workspace(id string) (state.Record, error)
	Workspaces() ([]state.Record, error)
	Repository(id string) (state.Repository, error)
	Repositories() ([]state.Repository, error)
}

Store is the slice of the state store the controller uses. *state.Store satisfies it; fakes mirror its semantics for tests.

RecordContainerObservation takes a repository ID because a container belongs to a repository and is shared by every session on it, while the operation and reconciliation calls stay keyed on the workspace: an operation is performed by a session (spec §5.2).

type WindowIntent

type WindowIntent struct {
	Name     string
	Command  string // empty => shell window
	RelDir   string // config cwd, relative; "" => workspace root
	Focus    bool
	Location WindowLocation
	Panes    []PaneIntent
}

WindowIntent is a window as configuration describes it, before the container binding is known. Ensure renders intents into concrete WindowSpecs after its container phase.

type WindowLocation

type WindowLocation string

WindowLocation is a window's configured placement. The zero value is auto: container when one applies to the workspace, host otherwise.

const (
	WindowAuto      WindowLocation = ""
	WindowHost      WindowLocation = "host"
	WindowContainer WindowLocation = "container"
)

type WindowSpec

type WindowSpec struct {
	Name    string
	Command string
	Dir     string
	Focus   bool
	Panes   []PaneSpec
}

WindowSpec is one window the actuator creates. An empty Command means the default shell; Dir is absolute (derivation resolves relative cwds against the worktree).

Directories

Path Synopsis
Package fake provides in-memory implementations of the controller's interfaces for tests in this and later slices.
Package fake provides in-memory implementations of the controller's interfaces for tests in this and later slices.

Jump to

Keyboard shortcuts

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