Agent Supervisor Process Supervision Design Profile
Status
- Status: Delivered (2026-10-10, S1/S2/S3 all delivered; the S3 delivery record is at the end). S1 landed §3.3 sampling, §3.5 report piggybacking, §4's panel read-only parts, and §5's snapshot endpoints; S2 landed §3.4 backoff auto-restart and circuit breaking (
BACKOFF/BROKENstates enabled,restartBackoffInitial/Max/restartBreakerLimitconfigs, success criterion = surviving longer than the backoff cap), §3.6 event-log dual channels (agent-local rotating file in full + metrics-piggybacked server in-memory ring of 500 events/agent with seq-based incremental dedup), the panel action column (start/stop/restart) and the event-log tab, and the event-fetch and log-download endpoints (GET /api/v1/ops/agents/:agentId/supervisor/events,GET /api/v1/ops/agents/:agentId/supervisor/logs); S3 landed the light-tiersnapshotProfilespawn injection + the medium-tier core_pattern read-only hint + detect_down artifact registration. The original Proposed profile (2026-10-08, chartered as OPEN-ISSUES #67) is retained in full below; where it has drifted from the implementation, the implementation is authoritative - S3 decision record (2026-10-10, user-delegated): ① the light-tier
snapshotProfilefield (none|go|node|python|jvmexplicit declaration) — agreed, landed with S3; ② the medium tier's core_pattern host operation = agent read-only hints — scan the host's current state + show the suggested command in the panel/logs for ops to copy; the agent does not write host config directly (permission/security boundary); ③ retention/quota/download permissions still pending decision (survey §8.4). - S1 implementation increments (two points the profile did not foresee): snapshot coverage is "config surface ∪ instance surface" (a configured-but-never-started process appears in the supervision view as STOPPED, while ListProcesses keeps the instance-surface definition unchanged);
monitorProcessgained an instance-ownership guard (fixing a pre-existing defect where after RestartProcess the old monitor flipped RUNNING back to FAILED — mandatory because the S1 panel exposes state to users for the first time) - Scope: the five supervision elements for agent-managed processes — liveness/uptime/restart count, resource sampling with over-limit flags, crash auto-restart with circuit breaking, panel columns and process detail, report piggybacking; the crash-time memory-snapshot capture plan is in the crash capture survey (a separate survey whose tiered plan and four decidable items were approved by the user as "follow the survey's tiered plan"; S3 landed the light/medium tiers)
- Related: current code
internal/app/agent/ops_server.go(the managedProcess embryo) ·internal/app/agent/ops_config.go·proto/croupier/ops/v1/ops.proto·internal/api/ops/(server proxy) - Related update (2026-10-09): the supervised side's runtime contract (signal discipline / exit-code semantics / heartbeat ticks) has been merged into the agent-core profile §3 "supervised-object contract" — the supervision protocol's sole sources remain this profile + ops.proto, and core-family agents ship as fully compliant supervised objects out of the box; agent naming in the Agent inventory (sidecar-agent / devops-agent / capture-agent; the supervision surface (supervisor) belongs to sidecar-agent)
1. Current-State Inventory (code facts)
The agent side already has half a supervision skeleton; this design is evolution, not construction:
| Capability | Current state |
|---|---|
| Managed-process registration | OpsConfig.ManagedProcesses map[name]ManagedProcessConfig (command/args/workingDir/env/gracefulTimeout) — explicit config declaration; the agent manages only processes it starts itself |
| Manual start/stop/restart | OpsServer.StartProcess/StopProcess/RestartProcess (RPC-triggered, gated by the Enabled+AllowRestart double switch); the restarts counter and lastStart already exist |
| Exit detection | The monitorProcess goroutine holds sole ownership of cmd.Wait() (the waitDone reaping protocol) — this is exactly the hook for auto-restart |
| State model | The ProcessState enum: UNSPECIFIED/RUNNING/STOPPED/FAILED/STARTING/STOPPING (ops.proto:162) — missing the two states "backing off" and "breaker open" |
| Resource sampling | MetricsCollector (gopsutil v4 already a dependency): agent-level CPU/Memory/Disk/Network, MetricsReport reported per interval; per-process sampling not wired (the processes field 7 sits empty) |
| Server proxy | /ops/agents/:agentId/processes list + restart/stop/start already work (routes.go:549-552); the metrics in-memory history MetricsStore.GetHistory is the precedent |
| Panel | The Ops/Nodes page has NodeDetailDrawer/CronJobsDrawer, no process view |
| Crash snapshot | None |
2. Requirements → Gap Mapping
| User requirement | Current gap | Design home |
|---|---|---|
| ① Liveness detection / uptime / restart count | pid/state/lastStart/restarts exist; uptime needs deriving; heartbeat timestamp missing | §3.1/§3.2 |
| ② RSS/CPU% sampling, over-threshold flagging | gopsutil process sampling not wired; no threshold fields | §3.3 |
| ③ Hang → auto-restart (configurable) or flag red; consecutive-failure circuit breaking | No action on exit; no backoff; no breaker | §3.4 |
| ④ Agent-list supervisor column (status light/memory/CPU) + detail | Server has APIs, the panel has no view; detail page/event log missing | §4 |
| ⑤ Sample reporting piggybacked on heartbeat (/proc or go-psutil style) | MetricsReport.processes field empty; gopsutil already in the dependency tree | §3.5 |
| Addendum: full-journey event log (time/event/pid/exit code/count, panel-queryable + file-downloadable, with context and OOM-suspect flags) | All missing | §3.6 |
3. Design
3.1 Supervised Objects and Config Additions (OpsConfig.ManagedProcesses[x])
New fields (yaml/json tags follow the lowerCamelCase config contract; OpsConfig's existing snake_case legacy keys are not retroactively changed, new keys are always canonical, examples use the new keys):
| Field | Type/default | Semantics |
|---|---|---|
autoRestart | bool / false | Crash auto-restart switch — default off, matching the AllowRestart safety posture; enabling also requires AllowRestart=true (double gate) |
restartBackoffInitial | duration / 1s | Backoff sequence start (1s→2s→4s…) |
restartBackoffMax | duration / 60s | Backoff cap |
restartBreakerLimit | int / 5 | Consecutive-failure breaker threshold; 0 = never break (not recommended) |
memThresholdBytes | int64 / 0 = off | RSS over-limit flag threshold |
cpuThresholdPercent | double / 0 = off | CPU% over-limit flag threshold (mean over the sampling period) |
3.2 State Model Additions (the ProcessState enum, proto appended)
PROCESS_STATE_BACKOFF = 6— exited, waiting out the backoff before auto-restart (with the next restart time attached).PROCESS_STATE_BROKEN = 7— breaker open: consecutive failures reachedrestartBreakerLimit; restarts stopped, flagged red awaiting manual action.- Liveness determination reuses monitorProcess's Wait semantics (process-handle level, not polling); the heartbeat timestamp = the most recent successful sampling time (§3.3), from which the panel's "last report" column derives.
- Uptime = now − lastStart (a derived value, no new field); the restart count reuses
restarts.
3.3 Resource Sampling (gopsutil process, cross-platform)
- Every
MetricsInterval(default 30s), sample managed processes withstate=RUNNING:process.Process.MemoryInfo().RSSandprocess.CPUPercent()(gopsutil v4; Windows/Linux/macOS isomorphic, never writing /proc directly). - Over threshold → flag the instance
flags[](mem_over_limit/cpu_over_limit) and emit an event (§3.6), never killing the process automatically (disposition is a human decision; flags only expose).
3.4 Auto-Restart and Circuit Breaking (monitorProcess extension)
Wait returns
├─ deliberate stop (stopCh closed / StopProcess RPC) → state STOPPED, chain ends
└─ non-deliberate exit (crash)
├─ autoRestart=false → state=FAILED + event(exit_code/signal) → await manual action
└─ autoRestart=true
├─ consecutive failures < limit → state=BACKOFF, sleep the backoff, then restart
│ └─ restart success → backoff reset, consecutive failures zeroed, event(old pid/new pid)
└─ consecutive failures ≥ limit → state=BROKEN + breaker event (with reason) → restarts stopped- The "success" criterion = the new process survives longer than
restartBackoffMax(not immediately killed again) — prevents a crash-on-start process from churning through the whole backoff sequence. - Manual
StartProcessremains available for BROKEN instances (the reset path after human repair); success clears the breaker count. - The backoff sleep must be interruptible by
stopCh(no dangling goroutines when supervision stops).
3.5 Report Piggybacking (wire increment, proto appended, old fields untouched)
MetricsReport adds field 9:
message SupervisedProcessSnapshot {
string name = 1; // the ManagedProcesses logical name
int32 pid = 2; // 0 = not running
ProcessState state = 3; // includes the new BACKOFF/BROKEN states
int64 uptime_seconds = 4;
int32 restart_count = 5;
int64 rss_bytes = 6;
double cpu_percent = 7;
repeated string flags = 8; // mem_over_limit / cpu_over_limit / oom_suspect / breaker_tripped
int64 last_event_unix = 9; // most recent event time (drives the panel's incremental polling)
}
repeated SupervisedProcessSnapshot supervised_processes = 9;- Reuses the existing
StartReportingchannel and the server-sideMetricsStorepattern: on receipt the server updates each agent's supervisor snapshot (in-memory, with the same lifecycle policy as metrics history); when an agent goes offline the snapshot keeps the last value + the panel marks "data stale". ManagedProcess(the ListProcesses response) gains the derived fields uptime/flags/next_restart_at in sync, so readers get everything in one call.
3.6 Event Log (dual channels)
The event-type closed set: detect_down / auto_restart / restart_failed / breaker_tripped / resource_over_limit / manual_start / manual_stop / schedule_fire (§10.6) / schedule_paused / schedule_resumed (§10.2 pause & resume) / update_applied / update_rolled_back (§10.4).
| Channel | Carrier and semantics |
|---|---|
| Agent-local file | A supervisor-dedicated rotating log (reusing the lumberjack shape: directory/maxSize/maxBackups/maxAge configurable, keys ops.supervisorLog.*) — the full ground truth; not lost when the agent is offline |
| Report piggyback | Every MetricsReport carries recent events (incremental from last_event_unix); the server's in-memory ring keeps the latest N=500 events/agent — used by the panel list |
| Download | GET /ops/agents/:agentId/supervisor/logs goes through the existing ops proxy chain back to the agent to fetch the file (size-capped); the panel's "download logs" button uses it directly |
Event structure: {ts, agent_id, process, event, old_pid, new_pid, exit_code, signal, restart_count, message, context{last_heartbeat, last_error, oom_suspect, last_rss_bytes}}.
- The
oom_suspectdetermination (best-effort, honestly labeled heuristic): the exit was SIGKILL-class + the latest RSS sample exceeded 90% of the system's available memory — no precision promised, a triage lead only. - A
breaker_trippedevent must carrymessage(a summary of the consecutive-failure reason chain), displayed directly with a red panel flag.
4. Panel (web)
- Agent-list supervisor column: an aggregated status light (all green = everything RUNNING; yellow = any BACKOFF/over-limit flag; red = any FAILED/BROKEN) + per-process RSS/CPU micro-text; data comes from the list endpoint's supervisor snapshot aggregation — zero extra requests.
- Process detail drawer (a new tab inside NodeDetailDrawer or a standalone SupervisorDrawer, isomorphic with CronJobsDrawer):
- Process card: state light/pid/uptime/restarts/RSS/CPU/flags badges/BROKEN red flag + reason;
- Event-log list: reverse-chronological, event-type filter, expandable context fields such as
oom_suspect; - Actions: manual start/stop/restart (through the existing proxy endpoints, shown/hidden by the
ops:operatepermission) + "download logs".
- Polling follows the Ops page's current cadence (30s or the page's existing refresh interval); no push introduced.
- §10 increments wired into the panel (2026-10-15): the process card gained the
kind=probe-adapteradapter:<id>badge (§10.1) and thefp:<first 12 fingerprint chars>badge (§10.4, for aligning with update records by (process, time)); a new "Schedule" column (next trigger time + action tag, §10.6 visible in advance; the paused state overrides it with a "schedule paused" tag); the action column gained pause/resume schedule (viaschedule/pause|resume; pause uses a Popconfirm — freezing a cron is medium-risk; resume is a direct click — resuming automation is the intent; paused rows disable pause, processes without schedule entries disable pause, and success re-pulls the snapshot); the event closed set gained localized labels and tag colors for the five typesschedule_fire/schedule_paused/schedule_resumed/update_applied/update_rolled_back(the type-filter dropdown uses the same closed set). Web-sideSupervisedProcesstypes and normalization were completed with all server DTO fields (lastEventUnix/nextRestartAtUnix/kind/adapterId/nextScheduleAtUnix/nextScheduleAction/fingerprint/scheduleSuspended), defaulting to zero values — zero drift for legacy-agent snapshots. §10.4 same-day gap fix: the action column gained an "Update" button → Modal collectingstagedPath+expectedSha256(fail-closed identically front and back: a blank path or a non-64-char lowercase-hex sha blocks the request); success re-pulls the snapshot, failure keeps the Modal open for correction and resubmission — see §10.4 "panel wiring". §10.5 same-day gap fix:NodeDetailDrawer's basic-info area gained two rows — Agent version + Agent binary fingerprint (truncated display + copyable full text; failure renders an empty state without throwing) — see §10.5 "panel wiring".
5. Server API Additions (through the existing ops proxy chain; permissions reuse the ops family)
| Endpoint | Semantics |
|---|---|
GET /ops/agents/:agentId/supervisor/events?since=&limit= | Fetch events from the in-memory ring (default 100, max 500) |
GET /ops/agents/:agentId/supervisor/logs | Proxy back to the agent to fetch the rotating log file (streamed, size-capped) |
- The existing list/action endpoints are unchanged (ListProcesses response gains additive, backward-compatible fields).
- The response contract follows the platform norm (success returns the business JSON directly; errors
{error,message,details}).
6. Security and Boundaries
- Everything off by default:
autoRestartdefaults false, and auto-restart additionally requiresEnabled+AllowRestart(any one off → detect and flag only, no restart). - The breaker is the hard gate against runaway restarts: a backoff cap + a consecutive-failure ceiling, with no "infinite restart" path.
- Sampling cost: gopsutil per-process once per 30s × process count — the same order as the existing agent-level sampling; not a new load point.
- Snapshots and events do not enter the server DB (in-memory ring + agent-local files); a server restart loses the recent event ring — an honest boundary. If persistence is needed, a DB table can be evaluated then (via a numbered migration per the migration contract).
- The crash memory snapshot is not in this phase: the plan depends on the crash-capture survey's tiered recommendation and the user's decision (size/sensitive data/production switches); once decided it merges into P3.
7. proto / Config-Key Change List
proto/croupier/ops/v1/ops.proto:ProcessStategains values 6/7; addSupervisedProcessSnapshot;MetricsReportadds field 9;ManagedProcessadds uptime/flags/next_restart_at (appenditive numbering). Generation viamake proto(local protoc 34.x).OpsConfig: §3.1's six keys + theops.supervisorLog.*rotation keys, all tags lowerCamelCase;configs/examples synced.- Zero DB table changes (events never stored); zero migrations.
8. Phased Implementation Plan
| Phase | Content | Acceptance |
|---|---|---|
| S1 | Read-only monitoring: sampling wiring (§3.3) + MetricsReport piggyback (§3.5) + server snapshot storage and API + the panel column and detail drawer's read-only parts (§4) — delivered 2026-10-09 | The panel shows real RSS/CPU/state; proto generation is wire-compatible (an old server receiving new reports does not break) |
| S2 | Auto-restart and circuit breaking (§3.4) + event-log dual channels and download (§3.6) + detail-page action buttons | The crash→backoff→breaker full chain has tests (injected fake processes); event context complete; the download endpoint's rate limit works |
| S3 | Crash memory snapshot (per the crash-capture survey's decision; tiered plan landed) — delivered 2026-10-10: the snapshotProfile closed set (none/go/node/python/jvm) + spawn injection + snapshotDir (default logs/snapshots, 0700) + detect_down artifact registration + the core_pattern read-only hint event snapshot_hint; retention/quota/download permissions undecided and not done | Production default-off, per-process opt-in; snapshot artifacts land on disk and are visible in panel events; the download chain awaits the §8.4 decision |
Each phase is an independent commit with a message describing the change; gates follow the delivery definition of done (tsc/go test/guard + the release chain for anything rendering).
9. S3 Delivery Record (2026-10-10)
- proto increments (wire-compatible, all old fields untouched):
SupervisorEvent+snapshot_dir/snapshot_files(detect_down carries crash artifacts best-effort);SupervisedProcessSnapshot+snapshot_profile; the event closed-set comment +snapshot_hint. make proto regenerated all four ways (protoc 34.1/25.1). - Agent (
internal/app/agent/):ManagedProcessConfig.SnapshotProfile(closed-set validation intoOpsConfig.Validate; an illegal value errors at load) +OpsConfig.SnapshotDir(defaultlogs/snapshots); the newops_supervisor_snapshot.gomodule —snapshotEnv(go/python/jvm env injection; the profile takes precedence over existing env), node-profile argv prepending (NODE_OPTIONSdisallows those two flags),ensureProcessSnapshotDir(0700; failure does not block startup),readCorePattern(/proc read-only; a package-level variable for testability),snapshotHintNeeded/snapshotHintEvent(when any process enables the light profile and core_pattern is not pipe mode, one host-level hint is emitted;sync.Onceagainst spam),collectSnapshotArtifacts(the snapshot directory in full + node reports within WorkingDir, mtime-descending, ≤5);startProcesswires the injection;superviseExitfills artifacts into detect_down. - Server (
internal/api/ops/): the snapshot DTO passes throughsnapshotProfile/snapshotDir/snapshotFiles; incidentally fixed an S2-era pre-existing defect — the event DTO gainedtsUnix(the web readtsUnixwhile the server only sent the formattedts, so event times always showed "-"). - Web: the drawer's flags column gained the
snapshot:<profile>badge; the event-detail pane renders the snapshot directory and artifacts; thesnapshot_hintevent gets a "snapshot hint" label (purple) and enters the filter closed set; zh/en locales. - Race fixes (covering two pre-existing windows exposed by the batch's -race runs; mandatory because S3's new write paths made them reproducible):
StartProcess's response re-readp.pidoutside the lock → now uses thenewPIDcaptured inside the lock;superviseExitreadp.stopChoutside the lock racing with RestartProcess's stopCh swap → the determination moved inside p.mu. - Known boundaries: where the Go profile's core lands depends on the host's core_pattern (the medium tier's precondition); node reports land in WorkingDir (cwd); artifact download/retention/quota undecided and not done (survey §8.4);
JAVA_TOOL_OPTIONShas the "Picked up" stderr side effect (commented). - Tests: 10 agent-package S3 cases (closed set/env/argv/directory 0700/classification/hint closed set/artifact registration/detect_down integration/once/profile sampling passthrough) + the whole package green under -race; 2 api/ops mapping cases; 15 web Drawer cases (including the snapshot badge and artifact rendering); guard PASSED.
10. Unified Lifecycle Model (2026-10-14, informed by three external reviews; no code touched; adoption verdicts in the review files)
Sources: the agent-lifecycle review (中文) and the probe-adapter review (both 2026-10-14, external advice verified and adopted by this repo). Their relationship to this profile's delivered S1–S3: S1–S3 are the existing implementation of this section's run-state surface and process recovery loop; what follows is the unified model's increment.
10.1 The Unified Managed Object: ManagedProcess (no external new term)
The external reviews' ManagedProgram and this repo's OpsConfig.ManagedProcesses[x] (§3.1) are the same concept — the existing term ManagedProcess is kept. The unified model: one managed object representing both game helper programs and external probe adapters (a new kind: program | probe-adapter), so the two managed-object classes no longer build separate lifecycles.
Implemented (2026-10-15): ManagedProcessConfig gained the kind closed-set field (program / probe-adapter, default program — zero drift for existing configs) + the adapter inventory fields (adapterId / adapterVersion / adapterProtocol / adapterCapabilities; the protocol defaults to croupier-probe-jsonl-v1); Validate() rejects unknown kinds (aligning with the snapshotProfile closed-set precedent) and kind=probe-adapter missing identity; kind and adapterId travel up with the supervisor snapshot to the panel (SupervisedProcessSnapshot.kind / adapter_id, proto appended 12/13, wire-compatible). kind=probe-adapter goes through exactly the same lifecycle as program (boot autostart / crash recovery / breaker / snapshot profile / desired state) — no special-case branches.
10.2 Lifecycle Capability Table (adopted; not implemented)
| Capability | Owned | Notes |
|---|---|---|
| Install, start, stop, restart | Yes | Unified process management (S1/S2 already have monitoring + restart) |
| Boot autostart and crash recovery | Yes | Distinguish program crashes from deliberate stops (otherwise spurious starts); deliberate stops surviving restarts have landed (§10.3's first management-state block) |
| Scheduled start, stop, restart | Yes | Unified scheduler (§10.6) |
| Update binaries | Yes | §10.4's five requirements |
| Update config files | Yes | Versioning, validation, atomic publish (the configsync precedent); unimplemented, no design draft (verified against the ledger 2026-10-15, see below) |
| Modify probe frequency | Yes | Desired config (same lineage as sampling policy, profile §13.3) |
| Pause and resume | Yes | Name the paused object: schedule / program / probing; v1 delivered schedule pause (under §10.6) |
| Health probing | Yes | Reuse core/healthprobe (already in this repo) |
| Failure recovery policy | Yes | Restart, backoff, breaker, manual intervention (S2 has it) |
| View logs, versions, run state | Yes | Report uniformly to the Server (S1 has it) |
| Arbitrary remote shell execution | Not open by default | §10.7 hard boundary |
Pause & resume v1 implemented (2026-10-15, paused object = the schedule): POST /api/v1/ops/agents/:agentId/processes/:name/schedule/pause (or .../resume; both routes share one handler and suspend is fixed by the route rather than the request body, preventing path/body semantic divergence) → wire MsgSchedulePauseRequest/Response (0x040125/26, appended numbers) → the agent's SetSchedulePause. What pauses is the declared cron triggers; the process's run state is untouched (no stop, no effect on the recovery loop, no change to the process's desired state). Persisted at logs/supervisor/schedule_pause_state.json (map[process]paused, same directory and atomic-write pattern as desired state desired_state.json; survives agent restarts — a maintenance-window intent is not auto-cleared by an agent restart); a missing/corrupt file fail-opens to an empty map (a missing record = not paused — better to miss blocking a misfire than to refuse assembly over a broken state file). Trigger side: scheduleTick skips paused processes (the continue sits before slot dedup, so paused slots do not write schedFired — after resume, the next matching slot fires normally; slots missed during the pause are not made up, crond semantics). Gate: the same double switch as manual start/stop/restart (ops.enabled + allowRestart both explicitly on; no separate config key) — it is a remote ops action. This does not contradict §10.6's "scheduled triggering itself is not gated by allowRestart" (the gate is on the remote switch, not on local config intent). Pausing a process with no schedule entries is an idempotent no-op (the intent is persisted; the snapshot renders no field). Snapshot uplink SupervisedProcessSnapshot.schedule_suspended (proto appended 17); event types schedule_paused / schedule_resumed (§3.6 closed set appended). Honest boundaries: pausing the program and pausing probing are not done — program pause is semantically ≈ "manual stop + remember to resume" (this repo's manual stop already persists desired state and suppresses the recovery loop, so the increment is weak); probe pause is likewise ≈ "suppress health alerts during a maintenance window", better done with the alert-policy surface (§8/§13); if the object semantics become clear then, a v2 can be chartered separately — no speculative implementation.
Updating config files: unimplemented, no design draft (verified against the ledger 2026-10-15): the mechanism precedent is core/configsync's versioned fetcher (Versioned[T] + Fetch/Apply + an OnApply callback), but production only wires the agent's own config (probe sampling policy, probe target downlink, plugin sync) — a config-file distribution chain for managed processes (game/helper programs) does not exist, and this capability-table row must not be counted as delivered merely because a precedent exists. Five questions must be decided before chartering (no speculative implementation before the decision): ① path safety — letting the agent write arbitrary paths on its host ≈ weakened RCE; the write scope must be sandboxed to the managed process's directory (or an explicit per-file allowlist); absolute paths reaching anywhere are forbidden; ② validation definition — config formats vary by game and the platform ships no business schema; define what the platform validates (syntax / signature / compatibility matrix) and the failure disposition (reject / stage / alert); ③ atomicity and restart coupling — whether applying requires a process restart and who triggers it (how it shares the action funnel with §10.6 scheduling/§10.4 updates), and whether failure auto-rolls back (aligning with §10.4's "rollback on failed start"); ④ size and bandwidth — whole file vs diff, compression, chunking; large configs via storage relay or straight over the wire; ⑤ approval gate — config writes are a high-risk operation surface; do they join the two-person rule and the audit chain (aligning with §10.7's source typing for execution audit)?
10.3 The Four States (adopted; all four have landed their first block — run = the S1 snapshot, management = desired state (below), schedule = pause v1 (under §10.6), update = §10.4 v1)
Run state / management state / schedule state / update state — the four must be kept apart; conflating them misreads "updating" as "stopped". Their relationship to §3.2's ProcessState: ProcessState is the existing enum of the run-state surface; management/schedule/update are new enums of the desired-state coordination surface (the Reconciler question was verified: a completion of existing mechanisms, no new component — see data-flow §6.2).
The management state's first block is implemented (the first block of the managed-program lifecycle): ops manual stop/start persists the desired state into the supervisor log directory as desired_state.json (internal/app/agent/ops_desired_state.go) — a missing record means desired running (aligning with the existing boot-autostart semantics; zero behavior drift); a missing/corrupt file fail-opens to an empty map (better to miss blocking a spurious start than to refuse to start processes over a broken state file); atomic writes (tmp+rename). The boot-autostart gate (Start()): AutoRestart=true and no desired record → start as before; a process ops deliberately stopped (desired stopped) stays stopped across agent restarts — §10.2's "distinguish program crashes from deliberate stops (otherwise spurious starts)" lands here. Manual start/restart persists desired running. A write failure only alerts and never rolls back the operation (the desired state is a persistence hint; the operation itself already succeeded).
10.4 Updating Binaries: Five Requirements + the Fingerprint Hard Requirement (adopted; v1 implemented 2026-10-15, boundaries below)
The five requirements: distribution from trusted sources; content-hash and signature verification; handling running processes and file locks (stop-then-swap or atomic directory switch); database/config compatibility checks; rollback when the new version fails to start — atomically swapping one binary is not update safety.
Managed scope (user follow-up, 2026-10-14): the update capability covers the game process itself (not just helper programs and probe adapters) — ManagedProcess was always a generic managed-process model, and a game process is just another kind. But game-process updates carry extra preconditions: swapping the package while players are online is an incident, so it must satisfy (a) a maintenance window or online players below a threshold (online data from the health review §13.2 online metrics), (b) pausing scheduling and new-connection intake (§10.2 "pausing must name the object" — probes keep running during the update, otherwise failure is invisible), and (c) fingerprint records + rollback on failure. The concrete shape of the traffic-intake gate depends on game-side cooperation — unverified, to be settled with the first real game integration.
The v1 landing surface (internal/app/agent/ops_update.go): HTTP POST /ops/agents/:agentId/processes/:name/update (stagedPath + expectedSha256 required; 64-char lowercase hex fail-closed) → wire MsgUpdateProcessRequest/Response (0x040123/24) → the agent's UpdateProcess. Flow: hash pinning (staged sha256 ≠ expected → reject without touching the running state) → quiet core stop-then-swap (coreStop/coreStart emit no manual_* intermediate events) → the old binary renamed to a <target>.croupier-bak backup → install (rename preferred; EXDEV falls back to a same-directory temp file to stay atomic) → start → stability window (default 5s): an exit within the window (waitDone closing) rolls back to the old version and leaves an update_rolled_back event; an exit after the window is run-state business for the existing recovery loop. The backup is kept after success as last-known-good (rolling overwrite in the same directory; manual rollback as the last resort). The update action's own start = an explicit run intent (desired=true, same as a manual restart).
Fingerprint records (hard requirement, zero new tables): the event surface's update_applied / update_rolled_back (message carries old→new fingerprints); the persistent-query main entry = server-side execlog audit (source=process_update, every attempt recorded including client-unavailable, with the full request/response payload including fingerprints and rolledBack); the snapshot's SupervisedProcessSnapshot.fingerprint (proto appended 16) rides metrics uplink — a running instance's fingerprint = the sha256 of the binary content cached at spawn (the file being swapped does not change it, until a restart swaps the instance); panel drill-down and alert timelines align by (target, time).
Panel wiring (2026-10-15 gap fix; the backend route/DTO had long been delivered with zero web-side wiring): the action column gained an "Update" button → a Modal collecting stagedPath (a file path already staged on the agent host) and expectedSha256; front and back fail-closed identically — a blank path or a sha that is not 64-char lowercase hex (uppercase/short strings) blocks the request, aligning with the first gate of "hash pinning". On success the snapshot is re-pulled (the fingerprint column's fp:<first 12> reflects the new value, aligned with update records by (process, time, fingerprint)); on failure the Modal and entered inputs are kept for correction and resubmission, and the snapshot is not re-pulled (failure must not rewrite the view state).
Panel wiring (2026-10-15 gap fix; the backend data surface had long been delivered with zero web-side wiring): NodeDetailDrawer's basic-info area gained two rows — Agent version (system-info's agentVersion first, falling back to the node list's version) and Agent binary fingerprint (agentBinarySha256, the first 12 chars in monospace + copyable carrying the full text: connection-loss triage needs the full string to compare against execlog §10.4 queries). Fetching uses the existing four-level fallback chain (cache → tunnel live RPC → registry labels → the DB last-known anchor); a fetch failure renders an empty state rather than throwing — the triage surface must not fail wholesale over one unreadable field; empty values get a Tooltip explaining (a legacy agent or an unreadable binary). When node is empty no request is sent, and switching agents clears it to prevent cross-display (an in-effect cancelled flag guards against stale responses writing back).
Honest boundaries (v1 not done): ① signature verification unimplemented — content hash only (a signature changes with key rotation; the hash is the stable queryable anchor; source trust is guaranteed by the distribution channel); ② database/config compatibility checks unimplemented — game-side knowledge, owned by the caller (config versions linked via ConfigVersion); ③ game-process maintenance window / online-player threshold / traffic-intake gate unverified — to be settled with the first real game integration (see above); ④ a first install (no old version to roll back to) failing produces no event (the event closed set has only applied/rolled_back); the record lives in execlog audit.
The fingerprint is a hard requirement (user, 2026-10-14: "every update must record the fingerprint to make logs queryable"):
- What is fingerprinted: the binary content's sha256 hash (hex). Signature-verification results are recorded as a separate boolean (signatures change with key rotation; only the hash is stable and queryable); config does not enter the fingerprint — config already has versioned ground truth (ConfigVersion revision) as a linked field; the version string is display linkage.
- Recorded fields: target identity (ManagedProcess id), execution location (agentID), old fingerprint → new fingerprint, timestamp, operator/source (server-issued = the operator user / scheduled = the scheduler / rollback = recovery), verification results (hashMatch / signatureVerified / compatibility check), and outcome (success / failed / rolled_back, with the rollback recording rolledBackTo = the old fingerprint — the rollback path leaves records too).
- Where it lands (reusing two existing surfaces, zero new tables): an update is a managed-program lifecycle event → the supervisor event closed set appends
update_applied/update_rolled_back(following the detect_down-class event precedent: local timeline + in-memory ring, §3.6); an update is also an authorized action (§10.7) → the action audit enters execlog (every execution on every agent leaves an audit record — the existing agents-inventory §5.2 norm), with the full request/result including fingerprints — the persistent-query main entry is execlog. - Query definition: search execlog by "target + time + fingerprint"; one log's reverse lookup of the version = the execlog detail's own fingerprint + version string. Integration with metrics/alerts:
SupervisedProcessSnapshot(§3.5) gains a fingerprint field riding the snapshot uplink (proto appended; the wire-compatible precedent is §7) — alert/probe timelines align with update records by (target, time), locating "which update started the alarms"; the panel drills down on both axes side by side.
10.5 Agent Self-Upgrade Designed Separately (adopted; v0.1 draft 2026-10-15, unimplemented — four pending decisions below)
A failed self-upgrade = a lost agent — a different risk surface from ordinary managed programs (nothing above it restarts it), so §10.4's flow cannot be reused — its "stop-then-swap + stability-window rollback" assumes some role still observes the new binary and disposes of failure; during self-upgrade not even that observer exists. Key invariant: the self-upgrade path must keep the "survive without being replaced" retreat — the worst case of failure is the agent restarting on the old version, not bricking.
The four pending decisions (the user must decide before implementation; this draft gives recommendations):
- Upgrade source: (a) server-side staged relay (the server receives and stages the package → distributes; the same shape as §10.4's stagedPath, reusing the existing wire and audit surfaces); (b) the agent fetches an external URL directly (needs a TLS + signature trust chain); (c) config-version pinning (the server issues targetVersion; the agent fetches itself). Recommended (a): the upgrade surface is naturally covered by the authorization and audit surfaces, introducing no second trust chain.
- Trigger model: (a) manual API (in the authorized double-switch family; an independent key alongside allowUpdate); (b) ConfigVersion config hot-update (the version surface gains a field and distributes); (c) reuse §10.6 cron scheduling. Recommended to start with (a): self-upgrade is the highest-risk action and must not happen silently with config; batch upgrades layer batch orchestration on top of (a).
- Restart mechanism (the core difficulty): (a) an external supervisor re-launches (agent exit ≠ death; guaranteed by the systemd/k8s deployment surface); (b) fork+exec subprocess handover (the classic Unix self-update: fork a child that waits for the swap then execs the new path while the parent exits — self-consistent even with no external supervisor); (c) dual-process alternation (shadow process; high complexity). Recommended (b): self-consistent on deployment surfaces without a supervisor; with a supervisor, (b)'s parent exit naturally degrades into exit-restart — one code path for both deployment shapes.
- Failure posture and rollback: a failed self-upgrade = loss of contact; rollback can only be out-of-band (supervisor restart / manual login). Design constraints: the old binary is renamed as a backup, never deleted (§10.4's same last-known-good); the new version must survive the stability window (aligning with §10.4's default 5s; longer recommended for self-upgrade) before success is declared; a death within the window = the supervisor restarts per its existing policy (the backup is there → the old version returns) or a human intervenes. Fingerprint records follow §10.4's three landing surfaces (the event closed set + execlog audit
source=agent_self_upgrade+ the report surface).
The fingerprint landed first (delivered 2026-10-15; independent of the decisions above): the agent binary content's sha256 rides the version report uplink — SystemInfo.agent_binary_sha256 (proto 11, wire-compatible precedent §7), cached once per process lifecycle agent-side (run-instance fingerprint semantics, same as §10.4: the file being swapped does not change the value until a restart swaps the instance); the server's GET /ops/agents/:agentId/system-info data surface (SystemInfoCache last-known → tunnel live RPC backfill → registry-label degraded view) carries agentBinarySha256 throughout, and the cache copy switched to proto.Clone to cure the hand-written field-list drift (a new field would have silently dropped under the old copy code).
The persistent "last-known fingerprint" anchor is delivered (2026-10-15): on every registration the agent writes the running binary's fingerprint into its registration labels (labels.AgentBinarySHA256 = "agentBinarySha256", the single authoritative key in internal/common/labels; config/dynamic labels cannot override it — the fingerprint is injected after merging and is a computed fact, not configuration; an unreadable value never fabricates an empty anchor), which rides the existing label upsert persistence into agent_sessions.labels. The read side's system-info data surface went from three levels to four: cache → live RPC → registry-label degraded view (fingerprint included) → the DB last-known anchor (registry.AgentSessionModel.LastKnownIdentity, read Unscoped — the row survives the session's soft-delete expiry; the anchor outlives the session TTL and server restarts). The implementation deviates from the original record: the original note said "needs an agent_sessions column extension (numbered migration)" — the landing used the registration-label channel instead: labels are already part of the session row (no migration), the agent self-reports at every registration so there is no Upsert(UpdateAll) overwrite hazard (a standalone column would be zeroed by every heartbeat upsert unless the registration hot path's column-set semantics changed), and the fingerprint also enters the node page's label filter surface. Honest boundaries: labels are subject to sanitizeAgentLabels limits (≤32 labels, keys ≤64, values ≤256, sha256 hex 64 chars included) — platform keys are exempt from the limits (a 2026-10-15 hardening: the original implementation broke out at a full 32 by luck and could drop the fingerprint; now agentBinarySha256 goes through the exempt channel without consuming quota, so agents with >32 labels no longer silently lose the anchor); anchor freshness = the last registration (not a live heartbeat value — if the agent swaps its binary without re-registering, the old fingerprint is read; ground truth is the live RPC and execlog update records); the fingerprint label is visible on the node page's label surface (the agentBinarySha256 key); whether self-upgrade implementation should take a dedicated wire channel can be revisited then (a standalone column then would not conflict with this work).
Known boundaries (draft state): Windows has no fork — shape (b) needs its own plan (subprocess spawn + wait); multi-agent batch upgrade ordering (standbys before primaries, in batches); the supervision blind window for all of an agent's managed programs during its upgrade (the recovery loop/probes stop with the agent; server-side metrics-stale alerting should distinguish "upgrading" from "lost contact").
10.6 Scheduled Jobs and Health Recovery: a Unified Schedule Model, Unmerged Execution Logic (adopted; the schedule state implemented 2026-10-15)
The scheduling entry is unified (one schedule model), but scheduled triggers and the recovery loop are two execution paths — consistent with this repo's structural facts: the recovery loop is driven only by process-exit events (ops_server.go:426-439), and probe windows never feed restarts (health review §5.2 constraint 2).
The schedule state is implemented (2026-10-15): ManagedProcessConfig.schedule[] (the action closed set start/stop/restart + a five-field cron) — cron parsing shares internal/tasks/scheduler.ParseCron with server-side task scheduling (one schedule model), and Validate rejects illegal actions/expressions at config load. Triggering goes through the same explicit-action funnel (doStart/doStop/doRestart: desired-state persistence and supervisor events flow along), so a scheduled stop carries the same signal as a manual stop (stopCh close) and the recovery loop never mistakes a scheduled stop for a crash restart (locked by TestScheduledStopRecordsDesiredStateAndBlocksAutoRestart). A 30s minute-slot scan + (process, action, slot) dedup idempotency; no make-up runs (slots missed while the agent was down are not re-triggered — crond semantics). Event type schedule_fire (typed apart from manual_*, so the four state classes are distinguishable in the event stream); the snapshot adds next_schedule_at_unix=14 / next_schedule_action=15 (the schedule state visible in advance; zero values and zero drift with no schedule). Boundary: schedule is an agent-local config intent (same trust root as autoRestart/boot autostart) and is not gated by allowRestart (allowRestart gates the remote operation surface); stop on a nonexistent instance is an idempotent skip, and start/restart materialize through the same StartProcess path. The only runtime gate on triggering is the schedule pause (§10.2 pause & resume v1): a paused process is skipped before slot dedup (schedFired not written), the next matching slot fires normally after resume, and paused slots are not made up.
10.7 Remote Shell Not Open by Default (Hard Boundary)
Updating binaries/config ≠ permission for arbitrary remote command execution; program operations are modeled as explicit, authorized actions (aligning with §6's existing "everything off by default + double switch" norm), and no generic command-execution entry point is opened. Independent authorization, an allowlist, and audit are the mandatory trio.
The boundary is materialized (2026-10-15): the existing allowExec remote-command surface (the agent's OpsServer.ExecuteCommand; the server's HTTP POST /ops/agents/:agentId/exec + the local TCP entry) had its trio checked and closed —
| Precondition | Before materialization | After |
|---|---|---|
| Double switch (existing) | ops.enabled + allowExec both default false | Unchanged (existing norm) |
| Allowlist | execAllowedCommands empty = allow everything (fail-open) | fail-closed: an empty list rejects everything; OpsConfig.Validate() blocks it at the config surface, and ExecuteCommand enforces it at runtime for programmatically constructed paths |
| Audit | Zero records across the chain (no execlog writes in the logic layer) | Every attempt (success / business failure / client unavailable) writes execution_logs with source=agent_exec, recording operator+command+arguments+exit code in the audit payload; if the audit surface is missing it fail-opens and does not block the main path |
Settled boundary: the panel still exposes no generic shell entry — program operations always go through the managed processes' explicit actions (start/stop/restart); Validate() was not wired into the agent startup path (config loading never called it — a legacy gap), so the runtime fail-closed check is the actual enforcement point and the config-surface validation is the contract declaration.
10.8 The Config Model's Sole Authoritative Definition (merged from three reviews; three coexisting models are not allowed)
- Run surface:
ManagedProcess(this profile §3.1, extended with kind) — owns "run it and keep it under control" (schedule/recovery/state). - Probe surface:
probe.targets+probe.policy(health review §4.2/§13.3) — owns "what to probe, at what frequency, from whose perspective". - Adapter inventory: the probe-adapter review's
ProbeAdaptermanifest is not a third independent config model — it is an attached description (executable/protocol/capabilities) of a ManagedProcess withkind=probe-adapter, referenced byprobe.targets; game addresses/frequency/authorization/credential references stay in the probe-surface config and are not hardcoded into the inventory (the review's own constraint). Landing shape (2026-10-15): the inventory fields are embedded inManagedProcessConfig(adapterId/adapterVersion/adapterProtocol/adapterCapabilities) rather than a separate file —executablereuses the existingcommand/args, avoiding two entry declarations for one process; whether to split into a file is re-evaluated when theprobe.targetsreference surface (which depends on the IPC contract) lands. - Contract essentials (
croupier-probe-jsonl-v1; adopted but unverified — the field spec is the review's own "pending"): an independent process + versioned IPC; the process is resident and reused — never a new process per probe (launch cost would dominate the probe period); external adapters only probe and never control the platform (the capability-ownership table: control stays with the Agent/Server); build one reference adapter + contract tests before discussing distribution/signing.
