Documentation
¶
Overview ¶
Package supervisor runs the overmind control server and worker lifecycle.
Index ¶
- func NeedsRestart(info WorkerInfo, now time.Time, silence time.Duration) bool
- func SaveOverrides(path string, o Overrides) error
- func Stalled(info WorkerInfo, now time.Time, stallTimeout time.Duration) bool
- func Stranded(info WorkerInfo, now time.Time, stallTimeout time.Duration, ...) (bool, string)
- type ControlSender
- type Fleet
- func (f *Fleet) ApplyHello(h control.Hello, pid int, now time.Time)
- func (f *Fleet) ApplyStatus(agentID string, st control.Status, now time.Time)
- func (f *Fleet) ClearLeaving(agentID string)
- func (f *Fleet) ClearQuarantine(agentID string)
- func (f *Fleet) DrainProgress() (idle, total int, busy []string)
- func (f *Fleet) IsQuarantined(agentID string) bool
- func (f *Fleet) MarkLeaving(agentID string)
- func (f *Fleet) MarkRestart(agentID string)
- func (f *Fleet) MarkStallRestart(agentID string)
- func (f *Fleet) Quarantine(agentID, reason string)
- func (f *Fleet) Remove(agentID string)
- func (f *Fleet) Snapshot() []WorkerInfo
- type MembershipOp
- type MembershipRequest
- type Overrides
- type Server
- func (s *Server) Addr() string
- func (s *Server) Send(agentID string, env control.Envelope) error
- func (s *Server) Serve(ctx context.Context) error
- func (s *Server) SetAdminHook(h func(op control.Type, agentID string) control.AdminAck)
- func (s *Server) SetEventHook(h func(agentID string, ev control.Event))
- type SpawnFunc
- type Supervisor
- type WorkerInfo
- type WorkerSpec
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NeedsRestart ¶
NeedsRestart reports whether a worker has been silent past the timeout.
func SaveOverrides ¶
SaveOverrides writes the sidecar atomically (temp file + rename).
func Stalled ¶
Stalled reports whether a worker is heartbeating but frozen: undocked with no forward progress (system/POI/credits/docked unchanged) for longer than stallTimeout. This is the "healthy but stuck" state a heartbeat-only check cannot see — e.g. a shuttle stranded undocked in a station-less system, retrying dock forever (johnny_cab: 2.5 days). The guards keep it from firing on legitimate idle postures:
- Docked workers are exempt: a resident marketbot parked at its home station between scheduled captures, or a shuttle camping a hub for passengers, is docked and idle by design, not stuck.
- Drained workers are exempt: a drain (SIGUSR1) intentionally quiesces them.
- A zero LastProgress (never seen) or non-positive stallTimeout disables it.
stallTimeout is deliberately generous so a healthy mobile worker — which moves (system/POI change) or trades (credits change) well within the window — is never flagged; only a genuinely wedged worker trips it.
func Stranded ¶
func Stranded(info WorkerInfo, now time.Time, stallTimeout time.Duration, fuelFraction, fuelFloor float64, stallRestartLimit int) (bool, string)
Stranded reports whether a stalled worker is beyond what a restart can fix, and why. Two signals (spec 2026-07-03-stranded-worker-quarantine):
- fuel-dead: undocked + stalled + fuel below max(fuelFraction×MaxFuel, fuelFloor) — it cannot move, so respawning is futile. Assist-role workers are exempt (they legitimately run their tank down mid-rescue).
- escalation: stallRestartLimit consecutive stall-restarts produced no progress — whatever is wrong, restarting is not fixing it.
Types ¶
type ControlSender ¶
ControlSender delivers a control envelope to one connected worker. *Server satisfies it; tests inject fakes.
type Fleet ¶
type Fleet struct {
// contains filtered or unexported fields
}
Fleet is the thread-safe in-memory registry of all workers.
func (*Fleet) ApplyHello ¶
ApplyHello records a worker's identity on connect. A fresh (re)connect resets the progress clock: the worker just started, so it has not yet had a chance to stall.
func (*Fleet) ApplyStatus ¶
ApplyStatus records a heartbeat, advancing the progress clock whenever the new status shows forward motion relative to the last one.
func (*Fleet) ClearLeaving ¶
ClearLeaving clears the removal-in-progress flag (rolling update: the same agent relaunches, so its entry stays and must not keep the draining chip).
func (*Fleet) ClearQuarantine ¶
ClearQuarantine releases a worker for relaunch. Stall state is reset so the watchdog gives the rescued worker a fresh window before re-evaluating.
func (*Fleet) DrainProgress ¶
DrainProgress reports drain quiescence across currently-healthy workers: total healthy, how many last reported Drained, and the sorted ids of those still busy. A worker that is healthy but has not yet reported a heartbeat counts as busy (not drained).
func (*Fleet) IsQuarantined ¶
IsQuarantined reports whether the worker is currently pulled from the fleet.
func (*Fleet) MarkLeaving ¶
MarkLeaving flags a worker as being removed from the fleet (drain sent, stop pending). Creates the entry if absent so a booting worker can still be marked.
func (*Fleet) MarkRestart ¶
MarkRestart increments the restart counter and marks the worker unhealthy. It also zeroes LastProgress so the stall watchdog cannot re-fire on the fresh process before it reports in (Stalled is disabled on a zero LastProgress; ApplyHello restarts the clock).
func (*Fleet) MarkStallRestart ¶
MarkStallRestart records that the stall watchdog is restarting this worker.
func (*Fleet) Quarantine ¶
Quarantine flags a worker as pulled-from-fleet. Creates the entry if absent (the boot-time restore path runs before any Hello).
func (*Fleet) Remove ¶
Remove drops a worker from the registry entirely (membership removal complete). Unknown ids are a no-op — Remove must not create entries.
func (*Fleet) Snapshot ¶
func (f *Fleet) Snapshot() []WorkerInfo
Snapshot returns a copy of all worker infos, sorted by AgentID.
type MembershipOp ¶
type MembershipOp string
MembershipOp identifies a live-roster change.
const ( MembershipAdd MembershipOp = "add" MembershipRemove MembershipOp = "remove" MembershipUpdate MembershipOp = "update" )
Membership operations.
type MembershipRequest ¶
type MembershipRequest struct {
Op MembershipOp
Spec WorkerSpec
}
MembershipRequest asks the supervisor to change the roster for one agent. For MembershipRemove only Spec.AgentID is meaningful.
type Overrides ¶
type Overrides struct {
Removed []string `json:"removed"`
UpdatedAt string `json:"updated_at,omitempty"`
By string `json:"by,omitempty"`
}
Overrides is the dashboard-written membership sidecar: agents in Removed are subtracted from the yaml roster at boot and on SIGHUP. The fleet yaml itself is never machine-rewritten; this file is the only machine-written state.
func LoadOverrides ¶
LoadOverrides reads the sidecar. A missing file is an empty override set; a corrupt file returns empty plus the error so the caller can log loudly and proceed (never block a fleet on a bad sidecar).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the overmind side of the control channel.
func (*Server) SetAdminHook ¶
SetAdminHook installs the callback for admin membership envelopes.
type SpawnFunc ¶
SpawnFunc starts a worker process for spec, told to dial socket.
func DefaultSpawn ¶
DefaultSpawn returns a SpawnFunc that launches workerBin with flags. handoffQueuePath, when non-empty, is forwarded to every spawned worker as --handoff-queue so marketbot/craftsman workers share the same crafting-brain stock handoff queue file the overmind itself uses. An empty path forwards nothing, leaving the worker's own --handoff-queue default (disabled) in effect.
type Supervisor ¶
type Supervisor struct {
// SilenceTimeout is the heartbeat-gap tolerance for an established worker
// (one that has already sent Hello). Cold-start is covered by BootTimeout.
SilenceTimeout time.Duration
// StallTimeout bounds how long a worker may heartbeat while frozen (undocked,
// no system/POI/credit progress) before the stall watchdog restarts it — the
// safety net for a "healthy but stuck" worker that SilenceTimeout cannot see
// (e.g. a shuttle wedged undocked in a station-less system). A non-positive
// value disables the watchdog.
StallTimeout time.Duration
// DisconnectGrace bounds how long a worker that reports its game connection
// down (LastStatus.Disconnected) is left to the fleet-wide reconnect gate
// before the stall watchdog falls back to restarting it. A disconnected
// worker freezes (no progress) and would otherwise trip the stall watchdog,
// whose restart forces a fresh login — the exact login storm that trips and
// deepens a per-IP rate-limit block, turning a brief server hiccup into a
// multi-hour outage. The gate already reconnects gracefully (paced, honoring
// the block); only a worker still disconnected past this grace is treated as
// wedged and restarted. A non-positive value disables the exemption.
DisconnectGrace time.Duration
MaxRestarts int
// Stranded-quarantine tuning (see Stranded in fleet.go). OnQuarantine is
// invoked (from the reap goroutine) after a worker is quarantined so the
// host can enqueue a rescue; nil-safe.
FuelStrandFraction float64
FuelStrandFloor float64
StallRestartLimit int
OnQuarantine func(w WorkerInfo, reason string)
Sender ControlSender
RemoveDrainTimeout time.Duration
// StaggerInterval spaces initial worker launches to stay under the per-IP
// /login rate limit. BootTimeout bounds how long a worker may be alive but
// not yet have sent Hello before it is treated as wedged. KillGrace is the
// SIGTERM->SIGKILL escalation window.
StaggerInterval time.Duration
BootTimeout time.Duration
KillGrace time.Duration
// RestartBatch caps how many workers reapAndRestart may (re)launch in a
// single reap tick, so a mass restart (many workers dying at once) does not
// burst the per-IP /login limit. The reap loop runs every game.SleepMedium,
// so the default of 1 paces relaunches at the same ~12/min as the initial
// stagger. Empirically the per-IP connect throttle engages around ~25/min
// (see cmd/debug/login-probe), so 1-per-5s-tick keeps ~2x headroom. A
// non-positive value disables pacing (relaunch everything eligible at once).
RestartBatch int
// contains filtered or unexported fields
}
Supervisor spawns and keeps workers alive.
func NewSupervisor ¶
func NewSupervisor(server *Server, fleet *Fleet, specs []WorkerSpec, spawn SpawnFunc, logger *log.Logger) *Supervisor
NewSupervisor wires a supervisor. server may be nil in tests.
func (*Supervisor) EnqueueMembership ¶
func (s *Supervisor) EnqueueMembership(req MembershipRequest)
EnqueueMembership queues a roster change for the next reap tick. Safe from any goroutine.
func (*Supervisor) ReleaseQuarantine ¶
func (s *Supervisor) ReleaseQuarantine(agentID string)
ReleaseQuarantine schedules a quarantined worker for relaunch on the next reap tick (after its rescue record is done). Safe from any goroutine.
func (*Supervisor) Roster ¶
func (s *Supervisor) Roster() []WorkerSpec
Roster returns a copy of the current specs. Safe from any goroutine.
func (*Supervisor) Run ¶
func (s *Supervisor) Run(ctx context.Context) error
Run spawns each spec, then periodically restarts silent/dead workers.
func (*Supervisor) Tick ¶
func (s *Supervisor) Tick(ctx context.Context)
Tick runs one reap-and-restart pass: drains pending releases, restarts silent/dead/stalled workers, and quarantines newly-stranded ones. Run calls this on its own ticker; it is exported separately so callers outside this package (e.g. the cmd/overmind rejoin-glue tests) can drive a deterministic tick instead of waiting on Run's game.SleepMedium ticker. Not safe to call concurrently with Run or with itself: the pass mutates the unsynchronized restarts map, which Run's ticker goroutine owns.
type WorkerInfo ¶
type WorkerInfo struct {
AgentID string
Role string
Station string
PID int
// Version/Commit/BuiltAt/CodeDirty/Modified are the worker binary's build
// identity, reported in its Hello (buildinfo.Get). Empty Version = a
// pre-feature "legacy" worker. Modified is the raw vcs.modified cosmetic
// flag; CodeDirty is the color-relevant one (uncommitted code outside data/).
Version string
Commit string
BuiltAt string
CodeDirty bool
Modified bool
LastStatus control.Status
LastSeen time.Time
// LastProgress is the last time the worker's status showed forward motion
// (its system, POI, credits, or docked flag changed). LastSeen tracks that a
// heartbeat arrived at all; LastProgress tracks that the worker is actually
// doing something. A worker can heartbeat forever while frozen — this is how
// the stall watchdog tells "alive" from "making progress".
LastProgress time.Time
Healthy bool
Restarts int
// StallRestarts counts consecutive stall-watchdog restarts with no forward
// progress in between. Progress (ApplyStatus with a changed status) resets
// it. Reaching StallRestartLimit is the escalation signal for quarantine.
StallRestarts int
// Quarantined means the supervisor has pulled this worker from the fleet
// (stranded — a restart cannot fix it) pending rescue. A quarantined
// worker's process is stopped and it is never relaunched until
// ClearQuarantine.
Quarantined bool
QuarantineReason string
// Leaving means a membership-remove is in progress: the worker has been
// sent a drain and will be stopped and dropped from the fleet once idle
// (or after the remove-drain timeout). Surfaced to the dashboard as the
// "draining" chip.
Leaving bool
// DisconnectedSince is when the worker first reported its game-server
// connection down (LastStatus.Disconnected) without a reconnect since; zero
// when connected. A disconnected worker keeps heartbeating over the control
// socket, so the silence watchdog cannot see it — but its progress freezes,
// which would trip the stall watchdog. The supervisor leaves it to the
// reconnect gate for DisconnectGrace before restarting, because a restart's
// fresh login cannot succeed during a per-IP block and deepens it.
DisconnectedSince time.Time
}
WorkerInfo is the overmind's view of one worker.
type WorkerSpec ¶
type WorkerSpec struct {
AgentID string `yaml:"agent_id"`
Role string `yaml:"role"`
Station string `yaml:"station"`
// MissionCategories, when set, is forwarded to the worker as
// --mission-categories (comma-joined) so a mission-runner fleet can run
// beyond the delivery default — e.g. the learning pool's
// [delivery, exploration]. Empty leaves the worker's delivery-only default.
MissionCategories []string `yaml:"mission_categories,omitempty"`
// EnableFreight forwards --enable-freight, opting this worker into the
// /shipping carrier path (evaluated co-equally with the mission board).
// Default false = freight fully dormant. Canary one worker before any
// pool rollout — see the Rollout section of
// docs/superpowers/plans/2026-07-20-shipping-carrier-subproject-b.md.
EnableFreight bool `yaml:"enable_freight,omitempty"`
// FreightMaxPackages forwards --freight-max-packages, capping concurrent
// freight contracts (sub-project C multi-package trips). 0/1 = the v1
// single-contract behavior; canary fighter-4 runs 3. Layers UNDER the
// server/cargo headroom gates.
FreightMaxPackages int `yaml:"freight_max_packages,omitempty"`
// DisableFreightBootstrap forwards --freight-bootstrap=false, turning off the
// probationary loss-leader floor while leaving freight enabled. Zero value
// (false) keeps the CLI default (bootstrap on).
DisableFreightBootstrap bool `yaml:"disable_freight_bootstrap,omitempty"`
}
WorkerSpec is one roster entry the supervisor will spawn.
func LoadFleet ¶
func LoadFleet(path string) ([]WorkerSpec, error)
LoadFleet parses the fleet roster YAML at path.
func SubtractOverrides ¶
func SubtractOverrides(specs []WorkerSpec, o Overrides) []WorkerSpec
SubtractOverrides returns specs minus the override-removed agents.