Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(daemon): converge on out-of-band multica and agent CLI version changes (MUL-3269)

beast31cd51ae2fa2
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 9d35af47d8..0dcf987a9a 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -109,6 +109,34 @@ To run in the foreground (useful for debugging):
multica daemon start --foreground
```
+#### Following a replaced binary
+
+A CLI-launched daemon periodically compares its own compile-time version against
+the `--version` output of the `multica` binary it would re-exec. When they differ
+— `brew upgrade multica`, a re-download, a local `make build` — it waits for any
+running task to finish, then restarts into the new binary. A running task is
+never interrupted; if the daemon is busy the restart is deferred to the next
+check, and `multica daemon status` shows why it's still on the old version.
+
+This is separate from the GitHub self-update poller: disabling that does not stop
+the daemon from following a binary you installed yourself. To turn it off:
+
+```bash
+MULTICA_DAEMON_AUTO_RELOAD=0 multica daemon start
+# or
+multica daemon start --no-auto-reload
+# or persist it
+multica config set disable_auto_reload true
+```
+
+Agent CLIs (codex, claude, ...) are handled differently: when one of them is
+upgraded in place, the daemon re-probes its version and re-registers the runtime
+**without restarting**, so subsequent tasks pick up the new CLI while Multica's
+availability stays independent of a third party's release cadence.
+
+Desktop-managed daemons ignore both, because the Desktop app owns its bundled
+CLI's lifecycle.
+
### Stop
```bash
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 87f2399e6e..0bd46523cb 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -205,6 +205,7 @@ API key と base URL の両方が空の場合、サーバーサイド LLM 生成
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 起動ハンドシェイクの上限 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud は `true`、セルフホストは `false` | CLI の更新を自動でチェックして適用するか |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 更新チェックの間隔 |
+| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 帯域外で置き換えられた `multica` バイナリ(`brew upgrade`、再ダウンロード、ローカルビルド)へ再起動して追従するかどうか。`MULTICA_DAEMON_AUTO_UPDATE` とは独立 |
| `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` | タスク作業ディレクトリのルート |
| `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | デバッグ用にタスクディレクトリを保持 |
@@ -243,6 +244,7 @@ multica config show
| `codex_handshake_timeout` | `30s` | Codex app-server ハンドシェイクの上限 |
| `disable_auto_update` | 環境に従う | `true` で自動更新を無効化。`false` はローカルの上書きをクリアし、環境変数またはデフォルトに戻します |
| `auto_update_check_interval` | `6h` | 更新チェックの間隔 |
+| `disable_auto_reload` | 環境に従う | `true` でディスク上の置き換えへの追従を停止。`false` はローカルの上書きをクリア。`disable_auto_update` とは別に解決されます |
値のルール:
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index eedf4052c5..9afefa53fb 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -205,6 +205,7 @@ API key와 base URL이 모두 비어 있으면 서버 측 LLM 생성이 꺼지
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 시작 handshake 상한 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`, 자체 호스팅 `false` | CLI 자동 확인 및 업데이트 여부 |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 업데이트 확인 간격 |
+| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 외부에서 교체된 `multica` 바이너리(`brew upgrade`, 재다운로드, 로컬 빌드)로 재시작할지 여부. `MULTICA_DAEMON_AUTO_UPDATE`와 독립적 |
| `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` | 실행 태스크 작업 디렉터리의 루트 |
| `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | 디버깅을 위해 실행 태스크 디렉터리 유지 |
@@ -243,6 +244,7 @@ multica config show
| `codex_handshake_timeout` | `30s` | Codex app-server handshake 상한 |
| `disable_auto_update` | 환경을 따름 | `true`는 자동 업데이트를 끔. `false`는 로컬 덮어쓰기를 지우고 환경 변수 또는 기본값으로 복귀 |
| `auto_update_check_interval` | `6h` | 업데이트 확인 간격 |
+| `disable_auto_reload` | 환경을 따름 | `true`는 디스크에서 교체된 바이너리 추적을 끔. `false`는 로컬 덮어쓰기를 지움. `disable_auto_update`와 별도로 해석됨 |
값에는 다음 규칙이 적용됩니다.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index d2cc744730..ec14722d0a 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -205,6 +205,7 @@ The variables below are read on the computer that runs your agents, not in the A
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server startup handshake ceiling |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`; self-hosted `false` | Whether to check for and apply CLI updates automatically |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | Update check interval |
+| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | Whether to restart into a `multica` binary replaced on disk out of band (`brew upgrade`, a re-download, a local build). Independent of `MULTICA_DAEMON_AUTO_UPDATE` |
| `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` | Root directory for task working directories |
| `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | Keep task directories for debugging |
@@ -243,6 +244,7 @@ Supported keys:
| `codex_handshake_timeout` | `30s` | Codex app-server handshake ceiling |
| `disable_auto_update` | follows environment | `true` turns auto-update off; `false` clears the local override and returns to the env var or default |
| `auto_update_check_interval` | `6h` | Update check interval |
+| `disable_auto_reload` | follows environment | `true` stops the daemon following a binary replaced on disk; `false` clears the local override. Resolved separately from `disable_auto_update` |
A few value rules:
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index b937aa8e41..9d2cf760f6 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -205,6 +205,7 @@ API key 与 base URL 都为空时,服务端 LLM 生成关闭,调用方会使
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 启动握手上限 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`;自托管 `false` | 是否自动检查并更新 CLI |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 检查更新的间隔 |
+| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 是否在 `multica` 二进制被带外替换(`brew upgrade`、重新下载、本地构建)后重启到新二进制。与 `MULTICA_DAEMON_AUTO_UPDATE` 相互独立 |
| `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` | 执行任务工作目录的根目录 |
| `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | 保留执行任务目录用于调试 |
@@ -243,6 +244,7 @@ multica config show
| `codex_handshake_timeout` | `30s` | Codex app-server 握手上限 |
| `disable_auto_update` | 跟随环境 | `true` 关闭自动更新;`false` 清除本地覆盖,回到环境变量或默认 |
| `auto_update_check_interval` | `6h` | 检查更新的间隔 |
+| `disable_auto_reload` | 跟随环境 | `true` 让守护进程不再跟随磁盘上被替换的二进制;`false` 清除本地覆盖。与 `disable_auto_update` 分开解析 |
几条取值规则:
diff --git a/server/cmd/multica/cmd_config.go b/server/cmd/multica/cmd_config.go
index dd38ca80d0..69321a6ba3 100644
--- a/server/cmd/multica/cmd_config.go
+++ b/server/cmd/multica/cmd_config.go
@@ -41,6 +41,7 @@ var configSetSupportedKeys = []string{
"codex_handshake_timeout",
"disable_auto_update",
"auto_update_check_interval",
+ "disable_auto_reload",
}
var configSetCmd = &cobra.Command{
@@ -51,20 +52,21 @@ var configSetCmd = &cobra.Command{
"device_name, runtime_name, max_concurrent_tasks, poll_interval, " +
"heartbeat_interval, agent_timeout, " +
"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +
- "disable_auto_update, auto_update_check_interval.\n\n" +
+ "disable_auto_update, auto_update_check_interval, disable_auto_reload.\n\n" +
"The daemon keys (device_name, runtime_name, max_concurrent_tasks, " +
"poll_interval, heartbeat_interval, agent_timeout, " +
"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +
- "disable_auto_update, auto_update_check_interval) mirror their " +
+ "disable_auto_update, auto_update_check_interval, disable_auto_reload) mirror their " +
"--flag / env counterparts and are read by `daemon start` when " +
"neither the flag nor the env var is set. " +
"Precedence: --flag > MULTICA_… env > config.json > built-in default. " +
"Duration keys take a positive Go duration (e.g. '10s', '500ms', '1m30s'); " +
"'0s' and negative values are rejected — except agent_timeout, where " +
"'0s' is meaningful and explicitly disables the wall-clock cap. " +
- "disable_auto_update takes 'true' or 'false' (single-direction: setting " +
- "it to 'true' turns auto-update off, 'false' clears the override so " +
- "env/default decides). Pass an empty string to clear a persisted " +
+ "disable_auto_update and disable_auto_reload take 'true' or 'false' " +
+ "(single-direction: setting one to 'true' turns that behavior off, " +
+ "'false' clears the override so env/default decides). Pass an empty " +
+ "string to clear a persisted " +
"value (e.g. `config set poll_interval \"\"`).",
Args: exactArgs(2),
RunE: runConfigSet,
@@ -100,6 +102,7 @@ func runConfigShow(cmd *cobra.Command, _ []string) error {
fmt.Fprintf(os.Stdout, "%-34s %s\n", "codex_handshake_timeout:", valueOrDefault(cfg.CodexHandshakeTimeout, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %t\n", "disable_auto_update:", cfg.DisableAutoUpdate)
fmt.Fprintf(os.Stdout, "%-34s %s\n", "auto_update_check_interval:", valueOrDefault(cfg.AutoUpdateCheckInterval, "(not set)"))
+ fmt.Fprintf(os.Stdout, "%-34s %t\n", "disable_auto_reload:", cfg.DisableAutoReload)
return nil
}
@@ -210,25 +213,38 @@ func applyConfigSet(cfg *cli.CLIConfig, key, value string) error {
return err
}
case "disable_auto_update":
- if value == "" {
- cfg.DisableAutoUpdate = false
- return nil
- }
- b, err := strconv.ParseBool(value)
- if err != nil {
- return fmt.Errorf("disable_auto_update must be 'true' or 'false' (got %q)", value)
+ if err := assignBool(&cfg.DisableAutoUpdate, key, value); err != nil {
+ return err
}
- cfg.DisableAutoUpdate = b
case "auto_update_check_interval":
if err := assignPositiveDuration(&cfg.AutoUpdateCheckInterval, key, value); err != nil {
return err
}
+ case "disable_auto_reload":
+ if err := assignBool(&cfg.DisableAutoReload, key, value); err != nil {
+ return err
+ }
default:
return fmt.Errorf("unknown config key %q (supported: %s)", key, joinKeys(configSetSupportedKeys))
}
return nil
}
+// assignBool parses value as a strict bool into dst. Shared by the
+// disable_* toggles. Empty string clears the field (false).
+func assignBool(dst *bool, key, value string) error {
+ if value == "" {
+ *dst = false
+ return nil
+ }
+ b, err := strconv.ParseBool(value)
+ if err != nil {
+ return fmt.Errorf("%s must be 'true' or 'false' (got %q)", key, value)
+ }
+ *dst = b
+ return nil
+}
+
// assignPositiveDuration parses value as a strictly-positive Go duration
// and writes the raw string into dst. Shared by every persisted daemon
// duration knob except agent_timeout, whose zero value is meaningful.
diff --git a/server/cmd/multica/cmd_config_test.go b/server/cmd/multica/cmd_config_test.go
index 2879e295e6..266967b63c 100644
--- a/server/cmd/multica/cmd_config_test.go
+++ b/server/cmd/multica/cmd_config_test.go
@@ -70,6 +70,7 @@ func TestRunConfigShowIncludesProfileAndDefaults(t *testing.T) {
"codex_handshake_timeout:",
"disable_auto_update:",
"auto_update_check_interval:",
+ "disable_auto_reload:",
} {
if !strings.Contains(out, key) {
t.Fatalf("runConfigShow output missing %q:\n%s", key, out)
@@ -116,6 +117,7 @@ func TestApplyConfigSetSupportsDaemonKeys(t *testing.T) {
{"codex_handshake_timeout", "45s"},
{"disable_auto_update", "true"},
{"auto_update_check_interval", "12h"},
+ {"disable_auto_reload", "true"},
}
for _, p := range pairs {
if err := applyConfigSet(&cfg, p.key, p.val); err != nil {
@@ -130,7 +132,8 @@ func TestApplyConfigSetSupportsDaemonKeys(t *testing.T) {
cfg.CodexSemanticInactivityTimeout != "15m" ||
cfg.CodexHandshakeTimeout != "45s" ||
cfg.DisableAutoUpdate != true ||
- cfg.AutoUpdateCheckInterval != "12h" {
+ cfg.AutoUpdateCheckInterval != "12h" ||
+ cfg.DisableAutoReload != true {
t.Fatalf("cfg after set = %+v", cfg)
}
}
@@ -234,6 +237,7 @@ func TestApplyConfigSetRejectsBadValues(t *testing.T) {
{"agent_timeout negative", "agent_timeout", "-1s", ">= 0"},
{"disable_auto_update bad bool", "disable_auto_update", "maybe", "true"},
{"auto_update_check_interval zero", "auto_update_check_interval", "0s", "positive"},
+ {"disable_auto_reload bad bool", "disable_auto_reload", "maybe", "true"},
}
for _, tc := range cases {
tc := tc
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 9bf070bb59..33387f1f92 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -104,6 +104,7 @@ func init() {
f.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")
f.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")
f.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")
+ f.Bool("no-auto-reload", false, "Disable restarting when the multica binary on disk changes version (env: MULTICA_DAEMON_AUTO_RELOAD=false)")
daemonLogsCmd.Flags().BoolP("follow", "f", false, "Follow log output")
daemonLogsCmd.Flags().IntP("lines", "n", 50, "Number of lines to show")
@@ -124,6 +125,7 @@ func init() {
rf.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")
rf.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")
rf.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")
+ rf.Bool("no-auto-reload", false, "Disable restarting when the multica binary on disk changes version (env: MULTICA_DAEMON_AUTO_RELOAD=false)")
df := daemonDiskUsageCmd.Flags()
df.Bool("by-workspace", false, "Aggregate output by workspace instead of by task")
@@ -647,6 +649,9 @@ func buildDaemonStartArgs(cmd *cobra.Command) []string {
if d, _ := cmd.Flags().GetDuration("auto-update-interval"); d > 0 {
args = append(args, "--auto-update-interval", d.String())
}
+ if b, _ := cmd.Flags().GetBool("no-auto-reload"); b {
+ args = append(args, "--no-auto-reload")
+ }
// Forward global persistent flags.
if v, _ := cmd.Flags().GetString("server-url"); v != "" {
@@ -780,9 +785,16 @@ func runDaemonForeground(cmd *cobra.Command) error {
// treated as an override signal here — LoadConfig honors the raw env
// itself for the affirmative case.
noAutoUpdateFlag, _ := cmd.Flags().GetBool("no-auto-update")
- if resolveDaemonDisableAutoUpdate(noAutoUpdateFlag, "MULTICA_DAEMON_AUTO_UPDATE", fileCfg.DisableAutoUpdate) {
+ if resolveDaemonDisableSignal(noAutoUpdateFlag, "MULTICA_DAEMON_AUTO_UPDATE", fileCfg.DisableAutoUpdate) {
overrides.DisableAutoUpdate = true
}
+ // Same single-direction shape for the on-disk version watcher, resolved
+ // through its own env var: turning off GitHub polling must not also stop the
+ // daemon from following a binary the operator replaced by hand.
+ noAutoReloadFlag, _ := cmd.Flags().GetBool("no-auto-reload")
+ if resolveDaemonDisableSignal(noAutoReloadFlag, "MULTICA_DAEMON_AUTO_RELOAD", fileCfg.DisableAutoReload) {
+ overrides.DisableAutoReload = true
+ }
autoUpdateFlag, _ := cmd.Flags().GetDuration("auto-update-interval")
autoUpdateOverride, err := resolveDaemonDurationOverride(autoUpdateFlag, "MULTICA_DAEMON_AUTO_UPDATE_INTERVAL", fileCfg.AutoUpdateCheckInterval)
if err != nil {
@@ -1103,6 +1115,11 @@ func printDaemonStatusReport(w io.Writer, label string, health map[string]any) {
if version, ok := health["cli_version"].(string); ok && version != "" {
rows = append(rows, row{"Version", version})
}
+ // Only present while a confirmed on-disk version change is waiting for the
+ // daemon to go idle, so it reads as an explanation rather than a status line.
+ if reason, ok := health["reload_pending_reason"].(string); ok && reason != "" {
+ rows = append(rows, row{"Restart pending", reason})
+ }
if agents, ok := health["agents"].([]any); ok && len(agents) > 0 {
parts := make([]string, len(agents))
for i, a := range agents {
@@ -1290,8 +1307,9 @@ func resolveDaemonAgentTimeoutOverride(cmd *cobra.Command, envName string, cfgVa
return &parsed, nil
}
-// resolveDaemonDisableAutoUpdate resolves the single-direction disable
-// signal for auto-update. Precedence:
+// resolveDaemonDisableSignal resolves a single-direction disable signal —
+// auto-update (--no-auto-update) and auto-reload (--no-auto-reload) share the
+// shape. Precedence, using auto-update as the example:
//
// 1. --no-auto-update flag passed -> disable.
// 2. MULTICA_DAEMON_AUTO_UPDATE explicitly set to a falsy value ->
@@ -1301,7 +1319,7 @@ func resolveDaemonAgentTimeoutOverride(cmd *cobra.Command, envName string, cfgVa
// 3. config.json disable_auto_update=true (only when both flag and env
// are silent) -> disable.
// 4. Otherwise -> leave the override off; LoadConfig picks the default.
-func resolveDaemonDisableAutoUpdate(flagValue bool, envName string, cfgValue bool) bool {
+func resolveDaemonDisableSignal(flagValue bool, envName string, cfgValue bool) bool {
if flagValue {
return true
}
diff --git a/server/cmd/multica/cmd_daemon_precedence_test.go b/server/cmd/multica/cmd_daemon_precedence_test.go
index 4a06c36178..6c008fbac7 100644
--- a/server/cmd/multica/cmd_daemon_precedence_test.go
+++ b/server/cmd/multica/cmd_daemon_precedence_test.go
@@ -204,11 +204,12 @@ func TestResolveDaemonAgentTimeoutOverridePrecedence(t *testing.T) {
}
}
-// TestResolveDaemonDisableAutoUpdatePrecedence pins the single-direction
-// disable signal: flag OR falsy env OR persisted cfg=true all disable
-// auto-update; a truthy env leaves the override off so LoadConfig honors
-// the raw env; missing signals return false so the default wins.
-func TestResolveDaemonDisableAutoUpdatePrecedence(t *testing.T) {
+// TestResolveDaemonDisableSignalPrecedence pins the single-direction disable
+// signal shared by --no-auto-update and --no-auto-reload: flag OR falsy env OR
+// persisted cfg=true all disable; a truthy env leaves the override off so
+// LoadConfig honors the raw env; missing signals return false so the default
+// wins.
+func TestResolveDaemonDisableSignalPrecedence(t *testing.T) {
const envName = "TEST_MULTICA_DAEMON_AUTO_UPDATE"
cases := []struct {
@@ -234,7 +235,7 @@ func TestResolveDaemonDisableAutoUpdatePrecedence(t *testing.T) {
} else {
t.Setenv(envName, "")
}
- got := resolveDaemonDisableAutoUpdate(tc.flag, envName, tc.cfg)
+ got := resolveDaemonDisableSignal(tc.flag, envName, tc.cfg)
if got != tc.want {
t.Fatalf("got %v, want %v", got, tc.want)
}
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index 136cfc4483..963ac063c5 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -11,6 +11,7 @@ import (
"path/filepath"
"strings"
"testing"
+ "text/template"
"time"
"github.com/spf13/cobra"
@@ -83,6 +84,63 @@ func TestBuildDaemonStartArgsForwardsCodexHandshakeTimeout(t *testing.T) {
}
}
+// TestBuildDaemonStartArgsForwardsNoAutoReload matters because `daemon start`
+// re-execs itself as a foreground child: a flag the parent parsed but doesn't
+// forward is silently dropped, so the opt-out would appear to work and not.
+func TestBuildDaemonStartArgsForwardsNoAutoReload(t *testing.T) {
+ cmd := &cobra.Command{}
+ cmd.Flags().Bool("no-auto-reload", false, "")
+ if err := cmd.Flags().Set("no-auto-reload", "true"); err != nil {
+ t.Fatalf("set flag: %v", err)
+ }
+
+ args := buildDaemonStartArgs(cmd)
+ want := []string{"daemon", "start", "--foreground", "--no-auto-reload"}
+ if strings.Join(args, " ") != strings.Join(want, " ") {
+ t.Fatalf("buildDaemonStartArgs() = %q, want %q", args, want)
+ }
+}
+
+// TestNoAutoReloadFlagRegisteredOnBothDaemonCommands: `daemon restart` mirrors
+// every `daemon start` flag, and a knob registered on only one of them fails at
+// parse time for users who restart rather than start.
+func TestNoAutoReloadFlagRegisteredOnBothDaemonCommands(t *testing.T) {
+ t.Parallel()
+
+ for _, cmd := range []*cobra.Command{daemonStartCmd, daemonRestartCmd} {
+ if cmd.Flags().Lookup("no-auto-reload") == nil {
+ t.Errorf("daemon %s is missing --no-auto-reload", cmd.Name())
+ }
+ }
+}
+
+// TestPrintDaemonStatusExplainsDeferredRestart: when the daemon has confirmed a
+// version change but is still busy, `daemon status` is where a user finds out.
+// The row is absent otherwise so it reads as an explanation, not a status line.
+func TestPrintDaemonStatusExplainsDeferredRestart(t *testing.T) {
+ t.Parallel()
+
+ base := map[string]any{
+ "status": "running",
+ "pid": float64(1234),
+ "uptime": "1h2m3s",
+ "cli_version": "0.3.7",
+ }
+
+ var idle bytes.Buffer
+ printDaemonStatusReport(&idle, "Daemon", base)
+ if strings.Contains(idle.String(), "Restart pending") {
+ t.Errorf("status output = %q, want no restart row when nothing is pending", idle.String())
+ }
+
+ base["reload_pending_reason"] = "multica binary on disk reports 0.3.8, running 0.3.7"
+ var pending bytes.Buffer
+ printDaemonStatusReport(&pending, "Daemon", base)
+ if !strings.Contains(pending.String(), "0.3.8") {
+ t.Errorf("status output = %q, want the pending restart reason", pending.String())
+ }
+}
+
// TestPrintDaemonStatusOmitsVersionWhenMissing pins the back-compat contract:
// when the daemon doesn't report cli_version (older daemon paired with a newer
// CLI) or reports an empty string, the CLI must skip the line entirely instead
@@ -741,3 +799,29 @@ func writeDiskUsageFile(t *testing.T, path string) {
t.Fatal(err)
}
}
+
+// TestVersionTemplateMatchesDaemonProbe pins a contract that spans two packages
+// and would otherwise break in silence.
+//
+// The daemon's auto-reload check runs `<binary> --version` and parses the result
+// back into a version string it compares against its own compile-time version
+// (MUL-3269). That only works while cobra's version template keeps rendering
+// "multica <version> ..." as its first line — a reasonable-looking edit here
+// would leave the daemon reading a version that never matches, restarting on
+// every check, and nothing else in the suite would notice.
+func TestVersionTemplateMatchesDaemonProbe(t *testing.T) {
+ tmpl, err := template.New("version").Parse(rootCmd.VersionTemplate())
+ if err != nil {
+ t.Fatalf("parse version template: %v", err)
+ }
+ var rendered bytes.Buffer
+ if err := tmpl.Execute(&rendered, rootCmd); err != nil {
+ t.Fatalf("render version template: %v", err)
+ }
+
+ if got := daemon.ParseSelfVersion(rendered.String()); got != version {
+ t.Fatalf("daemon.ParseSelfVersion(%q) = %q, want the build version %q — "+
+ "the --version template and the auto-reload probe have diverged",
+ rendered.String(), got, version)
+ }
+}
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index c59e9a6fb6..3dae2d2d34 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -111,6 +111,15 @@ type CLIConfig struct {
// env, this field, DefaultAutoUpdateCheckInterval.
AutoUpdateCheckInterval string `json:"auto_update_check_interval,omitempty"`
+ // DisableAutoReload, when true, stops the daemon from restarting into a
+ // multica binary that was replaced on disk out of band. Single-direction
+ // like DisableAutoUpdate, and separate from it on purpose: "don't pull
+ // new versions from GitHub" and "don't follow the binary I installed
+ // myself" are different decisions. Resolution precedence:
+ // --no-auto-reload flag, MULTICA_DAEMON_AUTO_RELOAD=false env, this
+ // field, default (enabled).
+ DisableAutoReload bool `json:"disable_auto_reload,omitempty"`
+
// Backends contains per-backend overrides for users who want to point
// the daemon at non-default tool installations (e.g. an OpenClaw bundled
// inside another desktop app, or multiple isolated profiles on the same
diff --git a/server/internal/cli/update.go b/server/internal/cli/update.go
index 72e96e9dee..4c57997096 100644
--- a/server/internal/cli/update.go
+++ b/server/internal/cli/update.go
@@ -6,6 +6,7 @@ import (
"bufio"
"bytes"
"compress/gzip"
+ "context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -311,8 +312,14 @@ func IsBrewInstall() bool {
}
// GetBrewPrefix returns the Homebrew prefix by running `brew --prefix`, or empty string.
+// Bounded: a wedged brew (broken shellenv, unreachable network home) must not
+// park the caller — the daemon's reload loop reaches here periodically.
func GetBrewPrefix() string {
- out, err := exec.Command("brew", "--prefix").Output()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "brew", "--prefix")
+ cmd.WaitDelay = 2 * time.Second
+ out, err := cmd.Output()
if err != nil {
return ""
}
diff --git a/server/internal/daemon/agent_path_selfheal_test.go b/server/internal/daemon/agent_path_selfheal_test.go
index 6edbea5f91..60ed3857be 100644
--- a/server/internal/daemon/agent_path_selfheal_test.go
+++ b/server/internal/daemon/agent_path_selfheal_test.go
@@ -319,3 +319,65 @@ func TestResolveAgentEntry_NoCommandNoHeal(t *testing.T) {
t.Fatalf("entry with empty Command was rewritten: got %q, want %q", got.Path, entry.Path)
}
}
+
+// TestRefreshHealedVersion_KeepsHealedPairCurrentAfterInPlaceUpgrade covers the
+// gap the hot-refresh path opened.
+//
+// resolveAgentEntry deliberately returns healed.version, NOT the shared
+// agentVersions cache, whenever a previous self-heal is still live — that is the
+// MUL-4486 guarantee that a reader seeing the healed path sees the version
+// detected for it. But a re-probe only wrote agentVersions, so once the healed
+// binary was itself replaced in place, the daemon reported the new version to
+// the server while every task kept launching under the version captured at heal
+// time (runTask's Codex sandbox policy reads exactly this value).
+func TestRefreshHealedVersion_KeepsHealedPairCurrentAfterInPlaceUpgrade(t *testing.T) {
+ d := newSelfHealTestDaemon()
+ healed := filepath.Join(t.TempDir(), "codex")
+ writeExecStub(t, healed)
+
+ // State after a self-heal: path + the version detected for it at that time.
+ d.resolvedPaths["codex"] = healedAgent{path: healed, version: "1.0.0"}
+ d.setAgentVersion("codex", "1.0.0")
+
+ entry := AgentEntry{Path: "/gone/codex", Command: "codex"}
+ if _, version := d.resolveAgentEntry(context.Background(), "codex", entry); version != "1.0.0" {
+ t.Fatalf("baseline version = %q, want 1.0.0", version)
+ }
+
+ // The healed binary is now overwritten in place — same path, new version.
+ // This is what a re-probe observes and publishes.
+ d.setAgentVersion("codex", "2.0.0")
+ d.refreshHealedVersion("codex", healed, "2.0.0")
+
+ gotEntry, version := d.resolveAgentEntry(context.Background(), "codex", entry)
+ if version != "2.0.0" {
+ t.Errorf("resolveAgentEntry version = %q, want 2.0.0 — tasks would still run the old version's policy", version)
+ }
+ if gotEntry.Path != healed {
+ t.Errorf("resolveAgentEntry path = %q, want the healed path %q", gotEntry.Path, healed)
+ }
+}
+
+// TestRefreshHealedVersion_LeavesOtherPairingsAlone: a heal that has since moved
+// the provider to a different binary owns its own {path, version} pairing, and a
+// blank detection is never a version.
+func TestRefreshHealedVersion_LeavesOtherPairingsAlone(t *testing.T) {
+ d := newSelfHealTestDaemon()
+ d.resolvedPaths["codex"] = healedAgent{path: "/current/codex", version: "2.0.0"}
+
+ d.refreshHealedVersion("codex", "/stale/codex", "9.9.9")
+ if got := d.resolvedPaths["codex"]; got.version != "2.0.0" || got.path != "/current/codex" {
+ t.Errorf("pairing for a different path was modified: %+v", got)
+ }
+
+ d.refreshHealedVersion("codex", "/current/codex", "")
+ if got := d.resolvedPaths["codex"].version; got != "2.0.0" {
+ t.Errorf("healed version = %q, want 2.0.0 — a blank detection is not a version", got)
+ }
+
+ // A provider that was never healed must not gain an entry.
+ d.refreshHealedVersion("claude", "/usr/bin/claude", "3.0.0")
+ if _, ok := d.resolvedPaths["claude"]; ok {
+ t.Error("refreshHealedVersion invented a heal record for a provider that was never healed")
+ }
+}
diff --git a/server/internal/daemon/agent_version_refresh_test.go b/server/internal/daemon/agent_version_refresh_test.go
new file mode 100644
index 0000000000..918ba62da2
--- /dev/null
+++ b/server/internal/daemon/agent_version_refresh_test.go
@@ -0,0 +1,1657 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// newVersionRefreshFixture brings up a daemon with one registered codex runtime
+// in two workspaces, which is the steady state refreshAgentVersions is for:
+// nothing is missing, so the converge path never runs and the version the
+// daemon (and the server) knows about is frozen at registration.
+func newVersionRefreshFixture(t *testing.T) *batchFixture {
+ t.Helper()
+ return newVersionRefreshFixtureWith(t, nil)
+}
+
+// newVersionRefreshFixtureWith is newVersionRefreshFixture with a hook to
+// configure the fixture BEFORE the first registration, for the settings that
+// only mean anything if they were in place when the rows were created.
+func newVersionRefreshFixtureWith(t *testing.T, configure func(fx *batchFixture)) *batchFixture {
+ t.Helper()
+ fx := newBatchFixture(t)
+ if configure != nil {
+ configure(fx)
+ }
+ fx.daemon.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}
+ fx.setWorkspaces(
+ WorkspaceInfo{ID: "ws-1", Name: "one"},
+ WorkspaceInfo{ID: "ws-2", Name: "two"},
+ )
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})
+ if err := fx.daemon.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := fx.daemon.agentVersion("codex"); got != "9.9.9" {
+ t.Fatalf("registered codex version = %q, want 9.9.9", got)
+ }
+ return fx
+}
+
+// TestRefreshAgentVersions_HotRefreshesWithoutRestart is the review's second
+// product decision: an agent CLI upgrading is not a reason to bounce the daemon.
+// The user needs subsequent tasks to run under the new version — which means the
+// cached version (read back through resolveAgentEntry to key policy such as the
+// Codex sandbox) and the version the server displays, both refreshed in place.
+func TestRefreshAgentVersions_HotRefreshesWithoutRestart(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ restarts := trackRestarts(t, d)
+ callsBefore := fx.registerCallCount()
+
+ // The user runs `npm i -g @openai/codex`: same path, new binary.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := d.agentVersion("codex"); got != "10.0.0" {
+ t.Errorf("cached codex version = %q, want 10.0.0 — version-keyed policy would still use the old rules", got)
+ }
+ for _, workspaceID := range []string{"ws-1", "ws-2"} {
+ if got := fx.registeredVersionFor(workspaceID, "codex"); got != "10.0.0" {
+ t.Errorf("%s registered codex version = %q, want 10.0.0", workspaceID, got)
+ }
+ }
+ if got := fx.registerCallCount() - callsBefore; got != 2 {
+ t.Errorf("made %d Register calls, want 2 (one per tracked workspace)", got)
+ }
+ if restarts.Load() != 0 {
+ t.Errorf("scheduled %d restarts; an agent CLI upgrade must refresh, not restart", restarts.Load())
+ }
+ if got := d.RestartBinary(); got != "" {
+ t.Errorf("restart binary = %q, want empty", got)
+ }
+}
+
+// TestRefreshAgentVersions_UpdatesTheVersionTasksActuallyRead is the end-to-end
+// half of the healed-pair fix. The unit test covers refreshHealedVersion; this
+// one proves the refresh path reaches it, which is the part that was missing.
+//
+// For a provider that has been self-healed — the version-manager population most
+// likely to upgrade in place again — resolveAgentEntry returns healed.version,
+// not the shared cache. Refreshing only the cache told the server a new version
+// while every task kept launching under the old one.
+func TestRefreshAgentVersions_UpdatesTheVersionTasksActuallyRead(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+
+ // A real on-disk binary, since resolveAgentEntry gates the healed path on it
+ // actually being present.
+ healedPath := filepath.Join(t.TempDir(), "codex")
+ writeExecStub(t, healedPath)
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: healedPath, Command: "codex"}}
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: healedPath, Command: "codex"}})
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // Pretend a self-heal previously adopted this binary at 9.9.9. (freshDaemon
+ // leaves resolvedPaths nil, like a daemon that has never healed anything.)
+ d.resolvedPathsMu.Lock()
+ d.resolvedPaths = map[string]healedAgent{"codex": {path: healedPath, version: "9.9.9"}}
+ d.resolvedPathsMu.Unlock()
+
+ entry := d.cfg.Agents["codex"]
+ if _, version := d.resolveAgentEntry(context.Background(), "codex", entry); version != "9.9.9" {
+ t.Fatalf("baseline resolveAgentEntry version = %q, want 9.9.9", version)
+ }
+
+ // codex is upgraded in place at the same path.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if _, version := d.resolveAgentEntry(context.Background(), "codex", entry); version != "10.0.0" {
+ t.Errorf("resolveAgentEntry version = %q, want 10.0.0 — this is the value runTask keys the Codex "+
+ "sandbox policy off, so tasks would still run under the old version's rules", version)
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Errorf("ws-1 registered codex version = %q, want 10.0.0", got)
+ }
+}
+
+// TestRefreshAgentVersions_ReachesWorkspacesAnotherPathDidNotRegister covers the
+// hole in treating the version cache as a record of what the server knows.
+//
+// Every path that registers probes through setAgentVersion — the converge round,
+// a new workspace's sync, a runtime_gone re-register, a self-heal at task launch
+// — and each of them tells only the workspaces it happened to be working on, or
+// none at all. Whichever writer lands first leaves the cache matching what is on
+// disk, so a before/after diff of the cache sees nothing to do, and every
+// workspace that writer skipped keeps the old version until the daemon restarts.
+//
+// The population most exposed is the one this feature exists for: a version
+// manager upgrading in place deletes the pinned path, so the next task launch
+// self-heals and advances the cache before any refresh round runs.
+func TestRefreshAgentVersions_ReachesWorkspacesAnotherPathDidNotRegister(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // codex is upgraded, and something other than the refresh round probes it
+ // first. detectBuiltinRuntimes is exactly what those paths call.
+ fx.setProbeVersion("10.0.0")
+ if _, belowMin, _ := d.detectBuiltinRuntimes(context.Background()); len(belowMin) != 0 {
+ t.Fatalf("below-minimum = %v, want none", belowMin)
+ }
+ if got := d.agentVersion("codex"); got != "10.0.0" {
+ t.Fatalf("cached codex version = %q, want the other path to have advanced it to 10.0.0", got)
+ }
+
+ d.refreshAgentVersions(context.Background())
+
+ for _, workspaceID := range []string{"ws-1", "ws-2"} {
+ if got := fx.registeredVersionFor(workspaceID, "codex"); got != "10.0.0" {
+ t.Errorf("%s registered codex version = %q, want 10.0.0 — the cache moving first must not "+
+ "swallow the change for the workspaces nothing re-registered", workspaceID, got)
+ }
+ }
+
+ // And it settles rather than re-registering every round from here on.
+ calls := fx.registerCallCount()
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registerCallCount() - calls; got != 0 {
+ t.Errorf("made %d Register calls after settling, want 0", got)
+ }
+}
+
+// TestRefreshAgentVersions_BlankToRealVersionReRegisters covers a provider that
+// registered while its version probe was failing: the server shows a blank
+// version for it, and nothing else will ever fix that.
+//
+// Converge only looks at providers MISSING a runtime and this one has one, so it
+// never revisits it. And the ordering inside a refresh round hides it from the
+// refresh too — detectBuiltinRuntimes calls setAgentVersion with the real
+// version before the comparison runs, so by the next round the cache already
+// matches and there is no change to see. Blank -> real has exactly one chance to
+// be reported.
+func TestRefreshAgentVersions_BlankToRealVersionReRegisters(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})
+
+ // Register while the CLI reports no version at all.
+ fx.setProbeVersion("")
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "" {
+ t.Fatalf("registered codex version = %q, want blank for this setup", got)
+ }
+
+ // The probe recovers.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Errorf("registered codex version = %q, want 10.0.0 — a blank version would stay on the server forever", got)
+ }
+
+ // And it settles: no further rounds re-register.
+ calls := fx.registerCallCount()
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registerCallCount() - calls; got != 0 {
+ t.Errorf("made %d Register calls after settling, want 0", got)
+ }
+}
+
+// TestRefreshAgentVersions_DemotesRuntimeDowngradedBelowMinimum is the downgrade
+// case nothing reacted to.
+//
+// probeBuiltinRuntime drops a below-minimum provider from the payload, so there
+// is no version left to compare; the runtime row survives because the built-in
+// merge is additive; and the provider is absent from providersMissingRuntimes
+// precisely because it still holds that runtime. Every path looks idle while the
+// daemon keeps routing tasks to a binary it has already verified is too old.
+func TestRefreshAgentVersions_DemotesRuntimeDowngradedBelowMinimum(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Fatalf("providers before downgrade = %v, want [codex]", got)
+ }
+
+ // The CLI is downgraded in place to a version below the minimum.
+ origCheck := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = origCheck })
+ checkAgentMinVersion = func(_, version string) error {
+ if version == "0.0.1" {
+ return &agent.BelowMinimumError{AgentType: "codex", Detected: version, Minimum: "1.0.0"}
+ }
+ return nil
+ }
+ fx.setProbeVersion("0.0.1")
+
+ d.refreshAgentVersions(context.Background())
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Errorf("providers after downgrade = %v, want none — a binary confirmed below the minimum "+
+ "must stop accepting work", got)
+ }
+ if got := fx.deregisteredCount(); got == 0 {
+ t.Error("runtimes were dropped locally but the server was never told, so it would keep routing tasks")
+ }
+ // Recovery needs no new machinery: with no runtime it is missing again, so
+ // the converge path owns bringing it back after an upgrade.
+ if missing := d.providersMissingRuntimes(); len(missing) != 1 || missing[0] != "codex" {
+ t.Errorf("providersMissingRuntimes = %v, want [codex] so converge can restore it after an upgrade", missing)
+ }
+}
+
+// TestRefreshAgentVersions_DemotesWhenTheDowngradeMovedThePath is the same
+// downgrade through the shape a version manager actually produces: the pinned
+// path is deleted rather than overwritten, so the daemon reaches the too-old
+// binary through the self-heal instead of a direct probe.
+//
+// The heal refuses to adopt it, which is right — it must never be launched — but
+// the refusal is also the verdict. Swallowed, the probe falls back to the
+// vanished path and can only report "version detection failed", which by design
+// leaves the runtime alone; the daemon then keeps claiming tasks for a CLI that
+// fails at launch, every time.
+func TestRefreshAgentVersions_DemotesWhenTheDowngradeMovedThePath(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+
+ pinned := filepath.Join(t.TempDir(), "codex")
+ writeExecStub(t, pinned)
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: pinned, Command: "codex"}}
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: pinned, Command: "codex"}})
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Fatalf("providers before the downgrade = %v, want [codex]", got)
+ }
+
+ // The downgrade: the pinned path is gone, and the command now resolves on
+ // PATH to an older install that the gate rejects.
+ missing, _ := vanishedPinnedPath(t)
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: missing, Command: "codex"}}
+ d.agentsAvailable.Store(&map[string]AgentEntry{"codex": {Path: missing, Command: "codex"}})
+ // A probe of the deleted path has to fail the way it does in production, or
+ // the test quietly exercises the direct below-minimum branch instead of the
+ // self-heal one and passes with the verdict still swallowed.
+ fx.setProbeErr(func(path string, _ int) error {
+ if !agentExecutablePresent(path) {
+ return errors.New("fork/exec: no such file or directory")
+ }
+ return nil
+ })
+ origCheck := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = origCheck })
+ checkAgentMinVersion = func(_, version string) error {
+ if version == "0.0.1" {
+ return &agent.BelowMinimumError{AgentType: "codex", Detected: version, Minimum: "1.0.0"}
+ }
+ return nil
+ }
+ fx.setProbeVersion("0.0.1")
+
+ d.refreshAgentVersions(context.Background())
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Errorf("providers after the downgrade = %v, want none — the daemon has verified this binary "+
+ "cannot run and must stop accepting work for it", got)
+ }
+ if got := fx.deregisteredCount(); got == 0 {
+ t.Error("runtime was dropped locally but the server was never told, so it would keep routing tasks")
+ }
+}
+
+// TestRefreshAgentVersions_KeepsRuntimeWhenTheProbeMerelyFailed is the other half
+// of that rule. An unreadable version is transient — the CLI was busy or
+// mid-upgrade — and tearing down a working runtime over one is the mistake
+// refreshAgentAvailability's one-directional rule exists to avoid.
+func TestRefreshAgentVersions_KeepsRuntimeWhenTheProbeMerelyFailed(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ fx.setProbeErr(func(string, int) error { return errors.New("fork/exec: text file busy") })
+
+ d.refreshAgentVersions(context.Background())
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Errorf("providers after a failed probe = %v, want [codex] kept", got)
+ }
+ if got := fx.deregisteredCount(); got != 0 {
+ t.Errorf("deregistered %d runtimes over a probe failure, want 0", got)
+ }
+}
+
+// TestDemoteBelowMinimumRuntimes_DoesNotRaceTheHealthHandler pins why the filter
+// allocates instead of reusing the slice.
+//
+// healthHandler copies each workspace's runtimeIDs header under d.mu and
+// serializes it after releasing the lock, so filtering in place writes into a
+// slice another goroutine is reading — a genuine data race even when the value
+// written is identical. removeStaleRuntime already follows the same rule.
+//
+// The assertion is the race detector; the demotion assertion below only proves
+// the loop did the work it was supposed to be racing on.
+func TestDemoteBelowMinimumRuntimes_DoesNotRaceTheHealthHandler(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ handler := d.healthHandler(time.Now())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for i := 0; i < 100; i++ {
+ handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/health", nil))
+ }
+ }()
+ for i := 0; i < 100; i++ {
+ d.demoteBelowMinimumRuntimes(context.Background(), map[string]string{"codex": "0.0.1"})
+ }
+ <-done
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "claude" {
+ t.Errorf("providers after demotion = %v, want [claude]", got)
+ }
+}
+
+// TestRefreshAgentVersions_DoesNotDisturbTheRuntimeSet pins the "scoped so one
+// provider's update doesn't disturb other providers or workspaces" criterion.
+//
+// Re-registration carries the whole built-in set because that is the shape the
+// endpoint upserts, which means every provider's runtime comes back through
+// mergeBuiltinRegisterResponse. The invariant the daemon owns is that the
+// workspace still holds exactly one runtime per provider afterwards — a
+// server-side ID rotation must be swapped in place, not accumulated as a
+// duplicate that would double the provider's heartbeats.
+func TestRefreshAgentVersions_DoesNotDisturbTheRuntimeSet(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 {
+ t.Fatalf("providers before refresh = %v, want [claude codex]", got)
+ }
+
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ got := registeredProviders(t, d, "ws-1")
+ if len(got) != 2 || got[0] != "claude" || got[1] != "codex" {
+ t.Errorf("providers after refresh = %v, want exactly [claude codex] — one runtime per provider, no duplicates", got)
+ }
+}
+
+// TestRefreshAgentVersions_NoopWhenNothingChanged keeps the steady state quiet:
+// a round that finds the same versions must not re-register, or the daemon would
+// send one Register call per workspace every few minutes forever.
+func TestRefreshAgentVersions_NoopWhenNothingChanged(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ callsBefore := fx.registerCallCount()
+
+ fx.daemon.refreshAgentVersions(context.Background())
+
+ if got := fx.registerCallCount() - callsBefore; got != 0 {
+ t.Errorf("made %d Register calls with no version change, want 0", got)
+ }
+}
+
+// TestRefreshAgentVersions_ProbeFailureIsNotAVersionChange mirrors the self-
+// reload rule on the agent side. detectBuiltinRuntimes drops a provider whose
+// version it cannot read, so the previous version must survive rather than being
+// overwritten with a blank and re-registered as such.
+func TestRefreshAgentVersions_ProbeFailureIsNotAVersionChange(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ callsBefore := fx.registerCallCount()
+ fx.setProbeErr(func(string, int) error { return errors.New("fork/exec: text file busy") })
+
+ d.refreshAgentVersions(context.Background())
+
+ if got := d.agentVersion("codex"); got != "9.9.9" {
+ t.Errorf("cached codex version = %q, want the previous 9.9.9 preserved across a failed probe", got)
+ }
+ if got := fx.registerCallCount() - callsBefore; got != 0 {
+ t.Errorf("made %d Register calls off a failed probe, want 0", got)
+ }
+
+ // A later round with a working probe still catches the real upgrade.
+ fx.setProbeErr(nil)
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := d.agentVersion("codex"); got != "10.0.0" {
+ t.Errorf("cached codex version = %q, want 10.0.0 once the probe recovered", got)
+ }
+}
+
+// TestRefreshAgentVersions_BlankVersionKeepsThePreviousOne closes a hole the
+// minimum-version gate leaves open: agent.CheckMinVersion returns nil for any
+// provider with no MinVersions entry, so a CLI whose `--version` succeeds but
+// prints nothing lands in the registration payload with a blank version.
+// Treating that as a change would replace a version the server had with nothing.
+func TestRefreshAgentVersions_BlankVersionKeepsThePreviousOne(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ callsBefore := fx.registerCallCount()
+
+ fx.setProbeVersion("")
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registerCallCount() - callsBefore; got != 0 {
+ t.Errorf("made %d Register calls off a blank version, want 0", got)
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "9.9.9" {
+ t.Errorf("ws-1 registered codex version = %q, want the previous 9.9.9 intact", got)
+ }
+ // The half that actually mattered and was missed the first time: the probe
+ // runs setAgentVersion BEFORE refreshAgentVersions gets to inspect anything,
+ // so protecting only the payload leaves the daemon's own cache wiped — and
+ // that cache, not the payload, is what version-keyed policy reads.
+ if got := d.agentVersion("codex"); got != "9.9.9" {
+ t.Errorf("cached codex version = %q, want the previous 9.9.9 — a blank probe must not wipe the cache "+
+ "every version-keyed policy reads", got)
+ }
+}
+
+// TestRefreshAgentVersions_KeepsRuntimeWhenTheVersionGoesBlank runs a blank
+// probe through the REAL minimum-version gate, where codex has a floor.
+// CheckMinVersion fails on a blank for two very different reasons — the version
+// parsed and is genuinely too old, or it could not be parsed at all — and only
+// the first is a verdict. Classifying the parse failure as below-minimum would
+// demote a healthy, online runtime because one probe printed nothing.
+func TestRefreshAgentVersions_KeepsRuntimeWhenTheVersionGoesBlank(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ stubProbeRetry(t, time.Millisecond, time.Second)
+ origCheck := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = origCheck })
+ checkAgentMinVersion = agent.CheckMinVersion
+
+ fx.setProbeVersion("")
+ d.refreshAgentVersions(context.Background())
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Errorf("providers after a blank probe = %v, want [codex] — an unreadable version is transient "+
+ "and must never tear down a working runtime", got)
+ }
+ if got := fx.deregisteredCount(); got != 0 {
+ t.Errorf("deregistered %d runtimes off a blank version, want 0", got)
+ }
+ if got := d.agentVersion("codex"); got != "9.9.9" {
+ t.Errorf("cached codex version = %q, want the previous 9.9.9 preserved", got)
+ }
+}
+
+// TestRefreshAgentVersions_BlankProbeDoesNotWipeAnUnflooredProvidersVersion is
+// the other direction of the same gap. A provider with no MinVersions floor
+// passes the gate with a blank version, and the payload is rebuilt from probe
+// results — so a NEIGHBOUR's legitimate upgrade re-sends the whole built-in
+// set and would carry the blank to the server, wiping a version it already
+// knows while the daemon's own cache (protected by setAgentVersion) still
+// holds it. The payload must reuse the last known version instead.
+func TestRefreshAgentVersions_BlankProbeDoesNotWipeAnUnflooredProvidersVersion(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // claude's `--version` starts exiting 0 while printing nothing; the fixture
+ // gate has no floor, so the blank sails through to the payload builder.
+ origDetect := detectAgentVersion
+ t.Cleanup(func() { detectAgentVersion = origDetect })
+ detectAgentVersion = func(ctx context.Context, path string) (string, error) {
+ if strings.Contains(path, "claude") {
+ return "", nil
+ }
+ return origDetect(ctx, path)
+ }
+
+ // codex upgrades, which re-registers the whole built-in set — claude rides
+ // along in the same payload.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Fatalf("codex registered version = %q, want 10.0.0", got)
+ }
+ if got := fx.registeredVersionFor("ws-1", "claude"); got != "9.9.9" {
+ t.Errorf("claude registered version = %q, want 9.9.9 — one provider's upgrade must not carry "+
+ "its neighbour's blank to the server", got)
+ }
+ if got := d.agentVersion("claude"); got != "9.9.9" {
+ t.Errorf("cached claude version = %q, want 9.9.9", got)
+ }
+}
+
+// TestReregisterAfterRuntimeGone_KeepsRuntimeWhoseProbeFailed covers the
+// authoritative half of the unavailable/below-minimum split. The runtime_gone
+// recovery re-registers the whole workspace and applies the response as the
+// complete runtime set — but a provider dropped from the payload because its
+// probe FAILED is absent by accident, not by decision. Treating the response
+// as authoritative for it deletes a healthy runtime over one transient probe
+// failure (mid-upgrade, ETXTBSY) — the exact case the verdict split promises
+// to leave alone. Only a below-minimum verdict may take runtimes down.
+func TestReregisterAfterRuntimeGone_KeepsRuntimeWhoseProbeFailed(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 {
+ t.Fatalf("providers before recovery = %v, want [claude codex]", got)
+ }
+
+ // codex is mid-upgrade: its --version fails while the recovery runs.
+ stubProbeRetry(t, time.Millisecond, time.Second)
+ fx.setProbeErr(func(path string, _ int) error {
+ if strings.Contains(path, "codex") {
+ return errors.New("fork/exec: text file busy")
+ }
+ return nil
+ })
+
+ if err := d.reregisterWorkspaceAfterRuntimeGone(context.Background(), "ws-1"); err != nil {
+ t.Fatalf("reregisterWorkspaceAfterRuntimeGone: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "claude" || got[1] != "codex" {
+ t.Errorf("providers after recovery = %v, want [claude codex] — a transient probe failure must not "+
+ "evict a healthy runtime from an authoritative re-register", got)
+ }
+}
+
+// TestProfileDriftRefresh_KeepsRuntimeWhoseProbeFailed is the same contract on
+// the drift path, which is sharper-edged: it Deregisters whatever the
+// authoritative apply drops, so without the preserve the transient failure
+// would not just untrack the healthy runtime locally but proactively take it
+// offline server-side, failing its in-flight tasks via the offline sweeper.
+func TestProfileDriftRefresh_KeepsRuntimeWhoseProbeFailed(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ var codexID string
+ d.mu.Lock()
+ for _, id := range d.workspaces["ws-1"].runtimeIDs {
+ if rt := d.runtimeIndex[id]; rt.Provider == "codex" {
+ codexID = id
+ }
+ }
+ d.mu.Unlock()
+ if codexID == "" {
+ t.Fatal("codex runtime not registered in setup")
+ }
+
+ // The drift: a profile appears server-side. Its command_name is blank, so
+ // it changes the profile signature without entering the payload — the
+ // register carries built-ins only.
+ fx.mu.Lock()
+ fx.profiles["ws-1"] = []RuntimeProfile{{
+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Broken",
+ ProtocolFamily: "codex", Visibility: "workspace", Enabled: true,
+ }}
+ fx.mu.Unlock()
+ stubProbeRetry(t, time.Millisecond, time.Second)
+ fx.setProbeErr(func(path string, _ int) error {
+ if strings.Contains(path, "codex") {
+ return errors.New("fork/exec: text file busy")
+ }
+ return nil
+ })
+
+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {
+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "claude" || got[1] != "codex" {
+ t.Errorf("providers after drift refresh = %v, want [claude codex]", got)
+ }
+ for _, id := range fx.deregisteredIDs() {
+ if id == codexID {
+ t.Errorf("codex runtime %s was Deregistered — the drift path took a healthy runtime offline "+
+ "over a failed probe", id)
+ }
+ }
+}
+
+// TestProfileDriftRefresh_DoesNotConvergeToZeroOnFailedProbes guards the
+// sharpest corner of the same gap: when EVERY builtin probe fails in the same
+// round, the register payload is empty and the drift path used to read that as
+// "this daemon hosts nothing here" — deregistering every healthy runtime the
+// workspace has. An empty payload only proves convergence-to-zero when every
+// probe actually concluded.
+func TestProfileDriftRefresh_DoesNotConvergeToZeroOnFailedProbes(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ fx.mu.Lock()
+ fx.profiles["ws-1"] = []RuntimeProfile{{
+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Broken",
+ ProtocolFamily: "codex", Visibility: "workspace", Enabled: true,
+ }}
+ fx.mu.Unlock()
+ stubProbeRetry(t, time.Millisecond, time.Second)
+ fx.setProbeErr(func(string, int) error { return errors.New("fork/exec: text file busy") })
+
+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {
+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Errorf("providers after drift refresh = %v, want [codex] — an all-probes-failed round must not "+
+ "converge the workspace to zero", got)
+ }
+ if got := fx.deregisteredCount(); got != 0 {
+ t.Errorf("deregistered %d runtimes off failed probes, want 0", got)
+ }
+}
+
+// TestConcurrentRegisters_SameWorkspaceSerializedSoRecordMatchesServer pins the
+// workspaceRegisterLock contract: the per-workspace version record must follow
+// the SERVER's processing order. Two concurrent registers for one workspace
+// whose HTTP responses complete in the opposite order from the server's
+// processing would otherwise record the newer payload while the server kept
+// the older one — a mismatch the refresh round cannot see, precisely because
+// the record is what it compares against, so it would persist until the next
+// version change or restart.
+func TestConcurrentRegisters_SameWorkspaceSerializedSoRecordMatchesServer(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // Make every register linger, so unserialized sends would overlap.
+ fx.setRegisterDelay(30 * time.Millisecond)
+ payloads := [][]map[string]string{
+ {{"name": "Codex", "type": "codex", "version": "1.0.0", "status": "online"}},
+ {{"name": "Codex", "type": "codex", "version": "2.0.0", "status": "online"}},
+ }
+ var wg sync.WaitGroup
+ for _, p := range payloads {
+ p := p
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ // Through the wrapper, because that is the production contract: the
+ // Locked entry points assume their caller took the workspace's
+ // register lock for the whole send → apply → cleanup sequence.
+ _ = d.withWorkspaceRegisterLock("ws-1", func() error {
+ if _, err := d.registerBuiltinRuntimesForWorkspaceLocked(context.Background(), "ws-1", p); err != nil {
+ t.Errorf("register: %v", err)
+ }
+ return nil
+ })
+ }()
+ }
+ wg.Wait()
+
+ if got := fx.maxRegisterInFlight(); got != 1 {
+ t.Errorf("max concurrent Register calls for one workspace = %d, want 1 — unserialized sends let "+
+ "the record contradict the server's processing order", got)
+ }
+ serverHas := fx.registeredVersionFor("ws-1", "codex")
+ d.mu.Lock()
+ recorded := d.workspaces["ws-1"].builtinVersions["codex"]
+ d.mu.Unlock()
+ if recorded != serverHas {
+ t.Errorf("recorded version %q != server's final version %q — the refresh round would never "+
+ "re-register this workspace", recorded, serverHas)
+ }
+}
+
+// TestRefreshAgentVersions_RevisitsWorkspaceRegisteredByAnOlderConcurrentRound
+// pins the interleave that breaks any GLOBAL acknowledgement: registration
+// entry points are not serialized, so a register that probed before an upgrade
+// can land after a refresh round already brought every workspace it could see
+// up to date. A global "done" cleared at that moment would strand the late
+// workspace on the old version forever. Scoped per workspace, the late call
+// simply records what it sent, the record disagrees with the next probe round,
+// and that round revisits exactly the workspace that fell behind.
+func TestRefreshAgentVersions_RevisitsWorkspaceRegisteredByAnOlderConcurrentRound(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // codex upgrades; the refresh round brings both workspaces to 10.0.0.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registeredVersionFor("ws-2", "codex"); got != "10.0.0" {
+ t.Fatalf("ws-2 registered codex version = %q, want 10.0.0", got)
+ }
+
+ // A register that probed BEFORE the upgrade lands now, exactly as the
+ // production entry points would send it: the server holds 9.9.9 for ws-2
+ // again, and the daemon records what that call carried.
+ stale := []map[string]string{{"name": "Codex", "type": "codex", "version": "9.9.9", "status": "online"}}
+ resp, err := d.registerBuiltinRuntimesForWorkspaceLocked(context.Background(), "ws-2", stale)
+ if err != nil {
+ t.Fatalf("late register: %v", err)
+ }
+ if _, _, ok := d.mergeBuiltinRegisterResponse("ws-2", resp); !ok {
+ t.Fatal("merge of the late register response failed")
+ }
+ if got := fx.registeredVersionFor("ws-2", "codex"); got != "9.9.9" {
+ t.Fatalf("ws-2 registered codex version = %q, want the stale 9.9.9 (interleave precondition)", got)
+ }
+
+ // The next round must notice ws-2 fell behind and bring it back — without
+ // dragging ws-1 through another register to do it.
+ _, ws1Calls := fx.registrationFor("ws-1")
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-2", "codex"); got != "10.0.0" {
+ t.Errorf("ws-2 registered codex version = %q, want 10.0.0 — a workspace registered by an older "+
+ "concurrent round must be revisited, or it is stuck on the old version forever", got)
+ }
+ if _, calls := fx.registrationFor("ws-1"); calls != ws1Calls {
+ t.Errorf("ws-1 received %d extra Register calls, want 0 — only the workspace that fell behind "+
+ "needs revisiting", calls-ws1Calls)
+ }
+}
+
+// TestRefreshAgentVersions_RetriesAfterRegisterFailure closes the hole the
+// version cache creates: setAgentVersion has already moved on by the time the
+// register call fails, so a cache diff would see no change on the next round.
+// The per-workspace record only advances on a register the server accepted, so
+// the failed workspace stays behind and is retried — without dragging the
+// workspaces that succeeded back through another register.
+func TestRefreshAgentVersions_RetriesAfterRegisterFailure(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+ fx.failRegisterFor("ws-2", true)
+
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-2", "codex"); got == "10.0.0" {
+ t.Fatal("ws-2 register was supposed to fail")
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Fatalf("ws-1 registered codex version = %q, want 10.0.0 — one workspace failing must not block the others", got)
+ }
+
+ fx.failRegisterFor("ws-2", false)
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-2", "codex"); got != "10.0.0" {
+ t.Errorf("ws-2 registered codex version = %q after the retry, want 10.0.0", got)
+ }
+ // And it settles: the retry advanced ws-2's record, so nothing is behind.
+ calls := fx.registerCallCount()
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registerCallCount() - calls; got != 0 {
+ t.Errorf("made %d Register calls after settling, want 0", got)
+ }
+}
+
+// TestRefreshAgentVersions_ObligationSurvivesAnIncompletePayload is why the
+// per-workspace record is merged per provider rather than replaced with each
+// payload.
+//
+// codex's new version fails to register, then codex's probe fails on the next
+// round while claude's succeeds. That round registers a payload with no codex in
+// it at all. Counting that success as covering codex too would strand it — its
+// cache already holds the new version, so no cache diff would ever report a
+// change again and the server would keep showing the old version indefinitely.
+func TestRefreshAgentVersions_ObligationSurvivesAnIncompletePayload(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // Round 1: both upgrade, the register fails, so the server still holds the
+ // versions the initial sync registered.
+ fx.failRegister(true)
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "9.9.9" {
+ t.Fatalf("registered codex version after failed register = %q, want the original 9.9.9", got)
+ }
+
+ // Round 2: register recovers, but codex's probe now fails, so codex is
+ // dropped from the payload while claude registers fine.
+ fx.failRegister(false)
+ fx.setProbeErr(func(path string, _ int) error {
+ if strings.Contains(path, "codex") {
+ return errors.New("fork/exec: text file busy")
+ }
+ return nil
+ })
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-1", "claude"); got != "10.0.0" {
+ t.Errorf("claude registered version = %q, want 10.0.0 — a dropped provider must not block the others", got)
+ }
+
+ // Round 3: codex's probe recovers. Its cache already reads 10.0.0, so
+ // nothing here is a "change" — the per-workspace record still saying 9.9.9
+ // is the only reason the server ever learns about it.
+ fx.setProbeErr(nil)
+ d.refreshAgentVersions(context.Background())
+
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Errorf("codex registered version = %q, want 10.0.0 once its probe recovered", got)
+ }
+ // And it settles.
+ calls := fx.registerCallCount()
+ d.refreshAgentVersions(context.Background())
+ if got := fx.registerCallCount() - calls; got != 0 {
+ t.Errorf("made %d Register calls after settling, want 0", got)
+ }
+}
+
+// TestRefreshAgentVersions_UnreachableProviderDoesNotStormTheServer guards the
+// regression the per-workspace record invites: an entry can outlive its
+// provider.
+//
+// refreshAgentAvailability is deliberately one-directional, so an uninstalled
+// CLI is never dropped from the availability set — it just keeps failing its
+// probe and never reappears in the payload, leaving its record permanently
+// behind. Retrying on "any record disagrees" rather than "a version this
+// round's payload actually carries disagrees" would turn that into one
+// register call per workspace every few minutes for the life of the daemon.
+func TestRefreshAgentVersions_UnreachableProviderDoesNotStormTheServer(t *testing.T) {
+ fx := newBatchFixture(t)
+ d := fx.daemon
+ d.cfg.Agents = map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ })
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // Both upgrade; the register fails, so both are pending.
+ fx.failRegister(true)
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ // codex is then uninstalled — its probe fails from here on, permanently.
+ fx.failRegister(false)
+ fx.setProbeErr(func(path string, _ int) error {
+ if strings.Contains(path, "codex") {
+ return errors.New("executable file not found")
+ }
+ return nil
+ })
+
+ // The round that can still advance claude registers once.
+ d.refreshAgentVersions(context.Background())
+ settled := fx.registerCallCount()
+ if got := fx.registeredVersionFor("ws-1", "claude"); got != "10.0.0" {
+ t.Fatalf("claude registered version = %q, want 10.0.0 — the reachable provider must still advance", got)
+ }
+
+ // Every later round can confirm nothing, so it must issue no requests at all.
+ for i := 0; i < 5; i++ {
+ d.refreshAgentVersions(context.Background())
+ }
+ if got := fx.registerCallCount() - settled; got != 0 {
+ t.Errorf("made %d Register calls across 5 rounds that could confirm nothing, want 0 — "+
+ "a permanently unreachable provider must not become a request storm", got)
+ }
+}
+
+// TestRefreshAgentVersions_NotStarvedByAStuckProvider guards against an
+// optimization that looks free and isn't: skipping the round while the converge
+// half has work to do.
+//
+// A provider permanently below the minimum supported version never leaves
+// providersMissingRuntimes — deliberately, so it recovers on its own after an
+// upgrade. Yielding to that would let one stuck CLI silently disable version
+// refresh for every healthy provider on the machine, forever.
+func TestRefreshAgentVersions_NotStarvedByAStuckProvider(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // A second CLI is installed but permanently rejected by the version gate,
+ // so it stays in the missing set no matter how often converge retries.
+ setProbe := stubAgentProbe(t, map[string]AgentEntry{"codex": {Path: "/fake/codex"}})
+ setProbe(map[string]AgentEntry{
+ "codex": {Path: "/fake/codex"},
+ "claude": {Path: "/fake/claude-ancient"},
+ })
+ d.refreshAgentAvailability()
+ origCheck := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = origCheck })
+ checkAgentMinVersion = func(provider, _ string) error {
+ if provider == "claude" {
+ return errors.New("version too old")
+ }
+ return nil
+ }
+ d.convergeRuntimeRegistrations(context.Background())
+ if missing := d.providersMissingRuntimes(); len(missing) == 0 {
+ t.Fatal("claude should still be missing a runtime; the starvation setup is wrong")
+ }
+
+ // codex nevertheless upgrades, and must still be picked up.
+ fx.setProbeVersion("10.0.0")
+ d.refreshAgentVersions(context.Background())
+
+ if got := d.agentVersion("codex"); got != "10.0.0" {
+ t.Errorf("cached codex version = %q, want 10.0.0 — a stuck provider must not starve the healthy ones", got)
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Errorf("ws-1 registered codex version = %q, want 10.0.0", got)
+ }
+}
+
+// TestAgentDiscoveryLoop_PicksUpAnInPlaceCLIUpgrade is the loop-level wiring:
+// the converge half only ever looks at providers *missing* a runtime, so without
+// the version ticker an in-place upgrade stays invisible until a daemon restart.
+func TestAgentDiscoveryLoop_PicksUpAnInPlaceCLIUpgrade(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ origDiscovery, origVersion := agentDiscoveryInterval, agentVersionRefreshInterval
+ t.Cleanup(func() {
+ agentDiscoveryInterval = origDiscovery
+ agentVersionRefreshInterval = origVersion
+ })
+ // Discovery stays long so only the version ticker can drive this test.
+ agentDiscoveryInterval = time.Hour
+ agentVersionRefreshInterval = 5 * time.Millisecond
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan struct{})
+ go func() {
+ d.agentDiscoveryLoop(ctx)
+ close(done)
+ }()
+
+ fx.setProbeVersion("10.0.0")
+ waitFor(t, func() bool { return d.agentVersion("codex") == "10.0.0" },
+ "agentDiscoveryLoop never refreshed the agent CLI version")
+ waitFor(t, func() bool { return fx.registeredVersionFor("ws-1", "codex") == "10.0.0" },
+ "agentDiscoveryLoop never re-registered with the new version")
+
+ cancel()
+ <-done
+}
+
+// trackRestarts installs a cancelFunc that counts restart kicks, so a test can
+// assert that a code path did NOT bounce the daemon.
+func trackRestarts(t *testing.T, d *Daemon) *atomic.Int32 {
+ t.Helper()
+ var calls atomic.Int32
+ prev := d.cancelFunc
+ t.Cleanup(func() { d.cancelFunc = prev })
+ d.cancelFunc = func() { calls.Add(1) }
+ return &calls
+}
+
+// stubBelowMinimumAt makes checkAgentMinVersion reject exactly one version, so a
+// test can move the probe onto it and produce a CONFIRMED below-minimum verdict.
+func stubBelowMinimumAt(t *testing.T, rejected string) {
+ t.Helper()
+ orig := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = orig })
+ checkAgentMinVersion = func(_, version string) error {
+ if version == rejected {
+ return &agent.BelowMinimumError{AgentType: "codex", Detected: version, Minimum: "1.0.0"}
+ }
+ return nil
+ }
+}
+
+// TestDemoteBelowMinimumRuntimes_LateRegisterResponseCannotReviveTheProvider
+// pins the interleave that deleting the rows does not survive on its own.
+//
+// Registration entry points are not serialized against the refresh loop, so a
+// register whose payload was built while the CLI was still acceptable can still
+// be in flight when the downgrade is confirmed and the provider demoted. Its
+// response lands afterwards describing the provider as healthy, and every apply
+// path treats a response as fresh truth — so the runtime goes back into
+// runtimeIndex while the server's upsert puts the row back online. The demotion
+// is undone by the answer to a question asked before it, and the too-old CLI
+// keeps taking work until the next refresh tick notices.
+//
+// Both sides now run under d.mu, which gives them a total order: either the
+// demotion wins and the late response is rejected, or the apply wins and the
+// demotion removes the row it just added. This drives the first ordering.
+func TestDemoteBelowMinimumRuntimes_LateRegisterResponseCannotReviveTheProvider(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // A register sent while codex was still acceptable. Its response is held
+ // here and applied after the demotion, which is what "in flight across the
+ // verdict" means for a deterministic test.
+ inFlight := []map[string]string{{"name": "Codex", "type": "codex", "version": "9.9.9", "status": "online"}}
+ staleResp, err := d.registerBuiltinRuntimesForWorkspaceLocked(context.Background(), "ws-1", inFlight)
+ if err != nil {
+ t.Fatalf("in-flight register: %v", err)
+ }
+
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Fatalf("providers after downgrade = %v, want none (demotion precondition)", got)
+ }
+ deregsBefore := fx.deregisteredCount()
+
+ // The older register's response finally lands.
+ newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", staleResp)
+ if !ok {
+ t.Fatal("merge of the late register response failed")
+ }
+ if len(newIDs) != 0 {
+ t.Errorf("late response added runtimes %v; a provider confirmed below the minimum must not come "+
+ "back through a reply to a register sent before the verdict", newIDs)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Errorf("providers after the late response = %v, want none", got)
+ }
+ // Local rejection is only half the fix: the server upserted that row back to
+ // online, so it would keep listing the runtime and routing work to a daemon
+ // that no longer tracks it — those tasks sit unclaimed until the stale sweep.
+ if len(rejectedIDs) == 0 {
+ t.Fatal("late response was rejected locally but reported no runtime ID to deregister, so the " +
+ "server would still believe the runtime is online")
+ }
+ d.deregisterRevivedRuntimes(context.Background(), "ws-1", rejectedIDs)
+ if got := fx.deregisteredCount(); got <= deregsBefore {
+ t.Errorf("deregister calls %d -> %d; the revived server row was never taken offline", deregsBefore, got)
+ }
+
+ // The provider must still look missing so converge can restore it once the
+ // CLI is upgraded again — the demotion is a hold, not a tombstone.
+ if missing := d.providersMissingRuntimes(); len(missing) != 1 || missing[0] != "codex" {
+ t.Errorf("providersMissingRuntimes = %v, want [codex]", missing)
+ }
+}
+
+// TestDemoteBelowMinimumRuntimes_LateAuthoritativeResponseCannotReviveTheProvider
+// is the same interleave through the other apply flavor. The drift and
+// runtime-gone paths use applyRegisterResponseInPlace, which treats the response
+// as authoritative for the whole workspace, so it has to reject a demoted
+// provider too — and hand back its ID, because those callers deregister
+// droppedIDs.
+func TestDemoteBelowMinimumRuntimes_LateAuthoritativeResponseCannotReviveTheProvider(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ inFlight := []map[string]string{{"name": "Codex", "type": "codex", "version": "9.9.9", "status": "online"}}
+ staleResp, err := d.registerBuiltinRuntimesForWorkspaceLocked(context.Background(), "ws-1", inFlight)
+ if err != nil {
+ t.Fatalf("in-flight register: %v", err)
+ }
+
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Fatalf("providers after downgrade = %v, want none (demotion precondition)", got)
+ }
+
+ newIDs, droppedIDs, ok := d.applyRegisterResponseInPlace("ws-1", staleResp, "", nil)
+ if !ok {
+ t.Fatal("apply of the late register response failed")
+ }
+ if len(newIDs) != 0 {
+ t.Errorf("late authoritative response added runtimes %v, want none", newIDs)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Errorf("providers after the late authoritative response = %v, want none", got)
+ }
+ if len(droppedIDs) == 0 {
+ t.Error("demoted runtime was rejected but not reported in droppedIDs, so the caller would never " +
+ "deregister the row the server brought back online")
+ }
+ // The version record must not claim the server holds a version for a
+ // provider whose rows are on their way offline — that is exactly what makes
+ // a later refresh round think this workspace is already up to date.
+ d.mu.Lock()
+ recorded, hasRecord := d.workspaces["ws-1"].builtinVersions["codex"]
+ d.mu.Unlock()
+ if hasRecord {
+ t.Errorf("builtinVersions still records codex=%q after demotion; a later refresh round would "+
+ "read that as the workspace being current", recorded)
+ }
+}
+
+// TestDemoteBelowMinimumRuntimes_UpgradeClearsTheHold proves the demotion is
+// released by the probe round that finds the CLI acceptable again. Without that,
+// the guard protecting the demotion would reject the very register converge
+// makes to bring the provider back, and the runtime would never return.
+func TestDemoteBelowMinimumRuntimes_UpgradeClearsTheHold(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Fatalf("providers after downgrade = %v, want none (demotion precondition)", got)
+ }
+
+ // The user upgrades again; converge re-probes and registers.
+ fx.setProbeVersion("10.0.0")
+ d.convergeRuntimeRegistrations(context.Background())
+
+ for _, workspaceID := range []string{"ws-1", "ws-2"} {
+ if got := registeredProviders(t, d, workspaceID); len(got) != 1 || got[0] != "codex" {
+ t.Errorf("%s providers after upgrade = %v, want [codex] — the demotion hold outlived the "+
+ "downgrade and blocked recovery", workspaceID, got)
+ }
+ }
+ if got := fx.registeredVersionFor("ws-1", "codex"); got != "10.0.0" {
+ t.Errorf("ws-1 registered codex version = %q, want 10.0.0", got)
+ }
+}
+
+// TestSyncWorkspacesFromAPI_FirstRegistrationRejectsDemotedProvider covers the
+// third path a register response reaches local state through.
+//
+// A workspace seen for the first time does not go through
+// applyRegisterResponseInPlace or mergeBuiltinRegisterResponse — it builds the
+// workspaceState directly — so the demotion guard on those two left this one
+// open. A workspace joining while a provider is held below-minimum would bring
+// that provider back, on the strength of a payload probed before the verdict.
+func TestSyncWorkspacesFromAPI_FirstRegistrationRejectsDemotedProvider(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // Hold the new workspace's register in flight. Its payload was probed while
+ // codex was still acceptable; the demotion lands while it waits.
+ arrived := make(chan struct{})
+ release := make(chan struct{})
+ var once sync.Once
+ fx.setRegisterGate(func(workspaceID string) {
+ if workspaceID != "ws-3" {
+ return
+ }
+ once.Do(func() { close(arrived) })
+ <-release
+ })
+
+ fx.setWorkspaces(
+ WorkspaceInfo{ID: "ws-1", Name: "one"},
+ WorkspaceInfo{ID: "ws-2", Name: "two"},
+ WorkspaceInfo{ID: "ws-3", Name: "three"},
+ )
+ synced := make(chan error, 1)
+ go func() { synced <- d.syncWorkspacesFromAPI(context.Background(), false) }()
+ <-arrived
+
+ // The downgrade is confirmed while ws-3's register is still in flight.
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 0 {
+ t.Fatalf("providers for ws-1 after downgrade = %v, want none (demotion precondition)", got)
+ }
+ deregsBefore := fx.deregisteredCount()
+
+ close(release)
+ if err := <-synced; err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-3"); len(got) != 0 {
+ t.Errorf("ws-3 providers = %v, want none — a workspace joining while codex is held "+
+ "below the minimum must not be how it comes back online", got)
+ }
+ if got := fx.deregisteredCount(); got <= deregsBefore {
+ t.Errorf("deregister calls %d -> %d; the row the server created for ws-3 was left online, so it "+
+ "would keep routing work to a runtime the daemon does not track", deregsBefore, got)
+ }
+ // The version record must not claim ws-3 is current for a provider it
+ // refused, or the next refresh round would skip repairing it.
+ d.mu.Lock()
+ _, recorded := d.workspaces["ws-3"].builtinVersions["codex"]
+ d.mu.Unlock()
+ if recorded {
+ t.Error("ws-3 recorded a codex version for a provider whose rows it rejected")
+ }
+}
+
+// TestClearProviderDemotions_KeepsHoldWhenEvidencePredatesTheVerdict pins the
+// ordering rule that d.mu alone cannot supply.
+//
+// Four callers run probe rounds concurrently and version sampling happens off
+// the lock, so the round that finishes last is not necessarily the one that
+// looked last. An OK sample taken before a downgrade must not release the hold
+// that downgrade established — once the hold is gone, a stale register response
+// passes every other guard.
+func TestClearProviderDemotions_KeepsHoldWhenEvidencePredatesTheVerdict(t *testing.T) {
+ d := &Daemon{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), runtimeIndex: map[string]Runtime{}}
+
+ // A round that started before the verdict.
+ sampledAfter := d.demotionSeqSnapshot()
+
+ d.mu.Lock()
+ d.markProvidersDemotedLocked(map[string]string{"codex": "0.0.1"})
+ d.mu.Unlock()
+
+ d.clearProviderDemotions([]string{"codex"}, sampledAfter)
+ d.mu.Lock()
+ stillHeld := d.providerDemotedLocked("codex")
+ d.mu.Unlock()
+ if !stillHeld {
+ t.Fatal("an OK sample taken before the downgrade released the hold; a stale register response " +
+ "would now walk through every remaining guard")
+ }
+
+ // A round that starts after the verdict carries newer evidence and releases.
+ d.clearProviderDemotions([]string{"codex"}, d.demotionSeqSnapshot())
+ d.mu.Lock()
+ stillHeld = d.providerDemotedLocked("codex")
+ d.mu.Unlock()
+ if stillHeld {
+ t.Error("a probe round that started after the verdict must release the hold, or the provider " +
+ "could never recover")
+ }
+}
+
+// TestDetectBuiltinRuntimes_StaleOKRoundDoesNotReleaseANewerHold drives the same
+// ordering through the real probe round rather than the counter directly: the
+// round samples an acceptable version, blocks, and only finishes after a
+// downgrade has been confirmed.
+func TestDetectBuiltinRuntimes_StaleOKRoundDoesNotReleaseANewerHold(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // The stub reads probeVersion BEFORE consulting this hook, so the round has
+ // already sampled the acceptable version by the time it blocks here.
+ arrived := make(chan struct{})
+ release := make(chan struct{})
+ var once sync.Once
+ fx.setProbeErr(func(string, int) error {
+ once.Do(func() {
+ close(arrived)
+ <-release
+ })
+ return nil
+ })
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ d.detectBuiltinRuntimes(context.Background())
+ }()
+ <-arrived
+
+ // The downgrade is confirmed while that round is still in flight.
+ d.mu.Lock()
+ d.markProvidersDemotedLocked(map[string]string{"codex": "0.0.1"})
+ d.mu.Unlock()
+
+ close(release)
+ <-done
+
+ d.mu.Lock()
+ stillHeld := d.providerDemotedLocked("codex")
+ d.mu.Unlock()
+ if !stillHeld {
+ t.Error("a probe round that sampled before the downgrade cleared the newer hold — ordering the " +
+ "map writes is not enough when the evidence itself is sampled off the lock")
+ }
+}
+
+// stubBelowMinimumForProvider rejects ONE provider at a given version, leaving
+// every other provider acceptable at the same version. Round-4's findings are
+// about mixed rounds — one CLI too old while its neighbours are fine — which the
+// single-provider stub cannot express.
+func stubBelowMinimumForProvider(t *testing.T, provider, rejected string) {
+ t.Helper()
+ orig := checkAgentMinVersion
+ t.Cleanup(func() { checkAgentMinVersion = orig })
+ checkAgentMinVersion = func(name, version string) error {
+ if name == provider && version == rejected {
+ return &agent.BelowMinimumError{AgentType: name, Detected: version, Minimum: "1.0.0"}
+ }
+ return nil
+ }
+}
+
+// TestDemoteBelowMinimumRuntimes_CleanupCannotOutliveANewerRecovery closes the
+// TOCTOU that a tracking re-check could only narrow.
+//
+// A deregistration is decided under d.mu and issued after releasing it. The
+// re-check asked "does the daemon still track this row?" immediately before the
+// request, but the recovery can just as easily complete in the gap BETWEEN the
+// check and the request: the register brings the row back — under the same ID,
+// because the server upserts — and the older Deregister lands on top of it. The
+// daemon then tracks and heartbeats a runtime the server has marked offline,
+// which is the direction that strands work silently: the server will not route
+// to it, and neither side notices the disagreement.
+//
+// A point-in-time check cannot fix that; only putting the request inside the
+// order can. The workspace's register lock now spans send → apply → cleanup, so
+// a recovery for the same workspace cannot start while an older cleanup for it
+// is still in flight.
+func TestDemoteBelowMinimumRuntimes_CleanupCannotOutliveANewerRecovery(t *testing.T) {
+ // Stable IDs from the first registration, because a cleanup can only undo a
+ // recovery when the two name the same server-side row.
+ fx := newVersionRefreshFixtureWith(t, func(fx *batchFixture) { fx.enableStableRuntimeIDs() })
+ d := fx.daemon
+ codexID := fx.runtimeIDFor("ws-1", "codex")
+ if codexID == "" {
+ t.Fatal("no server-side runtime ID recorded for ws-1/codex")
+ }
+ if !fx.runtimeOnline(codexID) {
+ t.Fatalf("runtime %s is not online after registration", codexID)
+ }
+
+ // Hold the demotion's Deregister in flight. Only the first call blocks; the
+ // sibling workspace's cleanup runs normally once released.
+ deregisterStarted := make(chan struct{})
+ releaseDeregister := make(chan struct{})
+ var gateOnce sync.Once
+ fx.setDeregisterGate(func([]string) {
+ first := false
+ gateOnce.Do(func() { first = true })
+ if !first {
+ return
+ }
+ close(deregisterStarted)
+ <-releaseDeregister
+ })
+ // Signals that a register for ws-1 reached the server.
+ recovered := make(chan struct{})
+ var regOnce sync.Once
+ fx.setRegisterGate(func(workspaceID string) {
+ if workspaceID != "ws-1" {
+ return
+ }
+ regOnce.Do(func() { close(recovered) })
+ })
+
+ // codex downgrades below the minimum; the refresh round demotes it and
+ // blocks in the cleanup.
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ refreshDone := make(chan struct{})
+ go func() {
+ defer close(refreshDone)
+ d.refreshAgentVersions(context.Background())
+ }()
+ <-deregisterStarted
+
+ // The user upgrades again while that Deregister is still in flight, and
+ // converge tries to bring the provider back.
+ fx.setProbeVersion("10.0.0")
+ convergeDone := make(chan struct{})
+ go func() {
+ defer close(convergeDone)
+ d.convergeRuntimeRegistrations(context.Background())
+ }()
+
+ select {
+ case <-recovered:
+ t.Error("a recovery register for ws-1 reached the server while an older Deregister for the same " +
+ "workspace was still in flight; the cleanup is outside the registration order, so it can land " +
+ "after the recovery and knock the restored runtime offline")
+ case <-time.After(250 * time.Millisecond):
+ // Expected: the recovery is queued behind the cleanup.
+ }
+
+ close(releaseDeregister)
+ <-refreshDone
+ <-convergeDone
+
+ if !fx.runtimeOnline(codexID) {
+ t.Errorf("runtime %s is offline server-side after the upgrade recovered it — an older cleanup "+
+ "landed on top of a newer registration, and the daemon now heartbeats a row the server will "+
+ "not route work to", codexID)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "codex" {
+ t.Errorf("ws-1 providers after recovery = %v, want [codex]", got)
+ }
+}
+
+// TestRegisterRuntimesForWorkspace_ReportsBelowMinimumAsNotAuthoritative pins
+// the return value round 4 found being discarded.
+//
+// registerRuntimesForWorkspaceLocked probes, and its round can reach a
+// below-minimum verdict — but its callers apply the response as AUTHORITATIVE
+// for the whole workspace, so a provider absent from the payload has its rows
+// dropped and deregistered. Acting on the verdict there means acting on it
+// without the claim barrier (so a running task can have its runtime pulled out
+// from under it) and without recording the hold (so the next in-flight response
+// revives the provider and undoes it). The verdict therefore has to travel back
+// as "do not treat this response as authoritative about this provider".
+func TestRegisterRuntimesForWorkspace_ReportsBelowMinimumAsNotAuthoritative(t *testing.T) {
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ stubBelowMinimumAt(t, "0.0.1")
+ fx.setProbeVersion("0.0.1")
+
+ var preserve map[string]string
+ err := d.withWorkspaceRegisterLock("ws-1", func() error {
+ _, _, p, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
+ preserve = p
+ return err
+ })
+ // codex is the only provider, so its payload is empty and the register
+ // short-circuits — the verdict still has to come back.
+ if err != nil && !errors.Is(err, ErrNoRuntimesToRegister) {
+ t.Fatalf("registerRuntimesForWorkspaceLocked: %v", err)
+ }
+ if _, ok := preserve["codex"]; !ok {
+ t.Errorf("preserve set = %v, want codex — a caller that applies this response as authoritative "+
+ "would drop and deregister the provider's runtimes outside the one path allowed to demote", preserve)
+ }
+}
+
+// TestReregisterAfterRuntimeGone_LeavesBelowMinimumToTheDemotionPath is the
+// behaviour that return value buys.
+//
+// The runtime-gone recovery reaches the same below-minimum verdict
+// demoteBelowMinimumRuntimes does, but it has neither of the things that make
+// the demotion safe: the claim barrier, so the rows are never pulled out from
+// under a running task, and the seq-stamped hold, so a register sent before the
+// verdict cannot revive the provider. Dropping the rows here left no record that
+// the verdict had been reached, and the next in-flight response undid it.
+//
+// So it preserves instead. The verdict is not lost — the refresh tick that owns
+// the demotion still takes the provider offline, with both guards in place.
+func TestReregisterAfterRuntimeGone_LeavesBelowMinimumToTheDemotionPath(t *testing.T) {
+ fx := newBatchFixture(t)
+ // Stable IDs, so re-registering the surviving provider returns the row it
+ // already has — what UpsertAgentRuntime does. Without it every re-register
+ // looks like an ID rotation and the deregister count says nothing about the
+ // demotion.
+ fx.enableStableRuntimeIDs()
+ d := fx.daemon
+ agents := map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ d.cfg.Agents = agents
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, agents)
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 {
+ t.Fatalf("providers after registration = %v, want claude and codex", got)
+ }
+
+ // codex is downgraded; claude is fine at the same version.
+ stubBelowMinimumForProvider(t, "codex", "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ deregsBefore := fx.deregisteredCount()
+
+ if err := d.reregisterWorkspaceAfterRuntimeGone(context.Background(), "ws-1"); err != nil {
+ t.Fatalf("reregisterWorkspaceAfterRuntimeGone: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 {
+ t.Errorf("providers after runtime_gone recovery = %v, want claude and codex kept — this path "+
+ "reached the below-minimum verdict without the claim barrier or the hold that make acting on "+
+ "it safe, so it must leave the demotion to the refresh tick", got)
+ }
+ if got := fx.deregisteredCount(); got != deregsBefore {
+ t.Errorf("deregister calls %d -> %d; the recovery took a runtime offline on a verdict it may not act on",
+ deregsBefore, got)
+ }
+ d.mu.Lock()
+ held := d.providerDemotedLocked("codex")
+ d.mu.Unlock()
+ if held {
+ t.Error("the recovery recorded a demotion hold; the hold and the rows must be taken by the same " +
+ "barrier-protected path, or recovery ordering has two owners")
+ }
+
+ // The verdict is deferred, not dropped: the owner still acts on it.
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "claude" {
+ t.Errorf("providers after the refresh tick = %v, want [claude] — deferring the demotion must not "+
+ "lose it", got)
+ }
+}
+
+// TestProfileDriftRefresh_LeavesBelowMinimumToTheDemotionPath is the same
+// deferral on the second authoritative caller.
+//
+// The drift path is the sharper-edged of the two: it Deregisters whatever the
+// authoritative apply drops, so acting on a below-minimum verdict here does not
+// just untrack the runtime locally, it takes the row offline server-side —
+// outside the claim barrier, so a task executing on that runtime has it pulled
+// away mid-flight, and with no hold recorded, so the next in-flight response
+// puts it back anyway.
+func TestProfileDriftRefresh_LeavesBelowMinimumToTheDemotionPath(t *testing.T) {
+ fx := newBatchFixture(t)
+ fx.enableStableRuntimeIDs()
+ d := fx.daemon
+ agents := map[string]AgentEntry{
+ "claude": {Path: "/fake/claude"},
+ "codex": {Path: "/fake/codex"},
+ }
+ d.cfg.Agents = agents
+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})
+ stubAgentProbe(t, agents)
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ // The drift: a profile appears server-side. Its command_name is blank, so it
+ // changes the profile signature without entering the payload — the register
+ // carries built-ins only, and its response is applied as authoritative.
+ fx.mu.Lock()
+ fx.profiles["ws-1"] = []RuntimeProfile{{
+ ID: "prof-1", WorkspaceID: "ws-1", DisplayName: "Broken",
+ ProtocolFamily: "codex", Visibility: "workspace", Enabled: true,
+ }}
+ fx.mu.Unlock()
+ stubBelowMinimumForProvider(t, "codex", "0.0.1")
+ fx.setProbeVersion("0.0.1")
+ deregsBefore := fx.deregisteredCount()
+
+ if err := d.refreshWorkspaceRuntimeProfiles(context.Background(), "ws-1"); err != nil {
+ t.Fatalf("refreshWorkspaceRuntimeProfiles: %v", err)
+ }
+
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 2 || got[0] != "claude" || got[1] != "codex" {
+ t.Errorf("providers after drift refresh = %v, want [claude codex] — the drift path may not act on "+
+ "a below-minimum verdict it cannot record or barrier-protect", got)
+ }
+ if got := fx.deregisteredCount(); got != deregsBefore {
+ t.Errorf("deregister calls %d -> %d; the drift refresh took a runtime offline on a verdict it may "+
+ "not act on", deregsBefore, got)
+ }
+
+ // Deferred, not dropped.
+ d.refreshAgentVersions(context.Background())
+ if got := registeredProviders(t, d, "ws-1"); len(got) != 1 || got[0] != "claude" {
+ t.Errorf("providers after the refresh tick = %v, want [claude]", got)
+ }
+}
diff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.go
index 3f81e9f427..b58100c0f0 100644
--- a/server/internal/daemon/agents_refresh.go
+++ b/server/internal/daemon/agents_refresh.go
@@ -2,6 +2,7 @@ package daemon
import (
"context"
+ "fmt"
"sort"
"time"
)
@@ -21,6 +22,13 @@ var agentDiscoveryInterval = 2 * time.Minute
// off, so a stuck provider cannot turn into a busy loop. Overridable for tests.
var agentConvergeMaxBackoff = 30 * time.Minute
+// agentVersionRefreshInterval is how often a running daemon re-probes the
+// version of every agent CLI it already has registered, so an in-place upgrade
+// of codex/claude is picked up without a restart. A round is one `--version`
+// fork per installed CLI, fanned out and machine-level — it does not scale with
+// workspace count or runtime count. Overridable for tests.
+var agentVersionRefreshInterval = 5 * time.Minute
+
// agentDiscoveryLoop keeps the registered runtime set converged on the agent
// CLIs actually installed on this machine, so a CLI installed while the daemon
// is running comes online without a restart (MUL-5439).
@@ -34,9 +42,16 @@ var agentConvergeMaxBackoff = 30 * time.Minute
// still "missing" on the next tick and gets tried again. It also means a
// provider rejected for being below the minimum version recovers on its own
// after an in-place upgrade.
+//
+// A second, slower ticker keeps the versions of already-registered providers
+// fresh (refreshAgentVersions) — the converge half only ever looks at providers
+// that are *missing* a runtime, so without it an in-place CLI upgrade would stay
+// invisible until the daemon restarted.
func (d *Daemon) agentDiscoveryLoop(ctx context.Context) {
ticker := time.NewTicker(agentDiscoveryInterval)
defer ticker.Stop()
+ versionTicker := time.NewTicker(agentVersionRefreshInterval)
+ defer versionTicker.Stop()
var (
backoff time.Duration
@@ -46,6 +61,8 @@ func (d *Daemon) agentDiscoveryLoop(ctx context.Context) {
select {
case <-ctx.Done():
return
+ case <-versionTicker.C:
+ d.refreshAgentVersions(ctx)
case now := <-ticker.C:
gained := d.refreshAgentAvailability()
missing := d.providersMissingRuntimes()
@@ -100,6 +117,11 @@ func (d *Daemon) agents() map[string]AgentEntry {
// setSkippedAgents replaces the diagnostic "discovered but not registered" set
// reported on /health. Called at the end of every registration round with the
// providers that round dropped.
+//
+// Purely diagnostic, and deliberately so: it is last-writer-wins across every
+// goroutine that probes, so nothing may steer behavior off it. A caller that
+// needs to act on a verdict takes it from detectBuiltinRuntimes' return value,
+// which describes its own round.
func (d *Daemon) setSkippedAgents(skipped map[string]string) {
d.skippedAgentsMu.Lock()
defer d.skippedAgentsMu.Unlock()
@@ -162,6 +184,312 @@ func (d *Daemon) refreshAgentAvailability() []string {
return gained
}
+// refreshAgentVersions re-probes every installed agent CLI and re-registers the
+// built-in runtimes whenever the server has not been told a version this daemon
+// has already detected, so what the server reports matches what is on disk.
+//
+// This is the agent-CLI counterpart to trySelfReload, and it deliberately does
+// NOT restart. What a user needs when codex or claude upgrades is that
+// subsequent tasks run the new CLI under the new version's rules — not that
+// Multica's availability tracks a third party's release cadence. An in-place
+// upgrade leaves the pinned path valid, so the new binary is already what
+// launches; the two things left stale are the cached version (which keys
+// version-sensitive policy such as the Codex sandbox, read back through
+// resolveAgentEntry) and the version the server displays. Both are refreshed
+// here with running tasks untouched.
+//
+// detectBuiltinRuntimes does the probing, which buys three properties for free:
+// probes fan out, a fast failure is retried (runtimeVersionProbeAttempts), and
+// the minimum-version gate still applies. A provider whose probe fails this
+// round keeps its previous version and is retried next round — a failed probe
+// never looks like a version change.
+//
+// What to send is decided per WORKSPACE, from workspaceState.builtinVersions —
+// the versions the last register call the server accepted for that workspace
+// actually carried — never from a before/after diff of the shared version
+// cache. The cache is written by every path that probes, so a diff only sees a
+// change when this round happens to be the first writer: a converge round, a
+// new workspace registering, or a self-heal at task launch will all move it
+// first and leave this round seeing nothing to do — while the workspaces those
+// paths did not touch keep the old version indefinitely.
+//
+// The acknowledgement is per-workspace rather than a global pending set for
+// the same reason in reverse: registration entry points are not serialized, so
+// a register that probed BEFORE an upgrade can land AFTER a refresh round has
+// updated every workspace it could see. A global "done" flag cleared at that
+// moment would strand the late workspace on the old version forever. Scoped to
+// the workspace, the late-landing call simply records what it sent, the record
+// disagrees with the next probe round, and that round re-registers exactly the
+// workspace that fell behind.
+//
+// Re-registration carries the whole built-in set because that is the shape the
+// register endpoint upserts, so one provider's upgrade re-sends its neighbours
+// too. That is safe rather than disruptive: the unchanged entries upsert
+// identically, and mergeBuiltinRegisterResponse swaps a server-side ID rotation
+// in place instead of accumulating a duplicate — the workspace still holds
+// exactly one runtime per provider, and no running task is touched.
+// This runs unconditionally rather than yielding when the converge half has
+// work to do, even though the two occasionally probe in the same window. A
+// provider that is permanently below the minimum supported version never leaves
+// providersMissingRuntimes — that is by design, so it recovers on its own after
+// an upgrade — so yielding to it would let one stuck CLI silently disable version
+// refresh for every healthy provider on the machine, forever.
+func (d *Daemon) refreshAgentVersions(ctx context.Context) {
+ // Nothing has ever been version-detected: the daemon is still starting up,
+ // and initial registration is the sync path's job.
+ if !d.hasDetectedAgentVersions() {
+ return
+ }
+
+ builtins, belowMinimum, _ := d.detectBuiltinRuntimes(ctx)
+ // Runs before the early return below: a downgrade drops the provider from
+ // builtins entirely, so there is no version change left to detect and the
+ // machine could otherwise look idle while a too-old CLI keeps taking work.
+ if len(belowMinimum) > 0 {
+ d.demoteBelowMinimumRuntimes(ctx, belowMinimum)
+ }
+ if len(builtins) == 0 {
+ return
+ }
+ // What this round's payload actually carries, per provider. A provider whose
+ // probe failed is absent — and only carried providers are compared below,
+ // which is what stops an uninstalled CLI from triggering registrations. It
+ // is never dropped from the availability set (refreshAgentAvailability is
+ // deliberately one-directional), so it keeps failing its probe and never
+ // reappears in the payload; comparing records against a payload that cannot
+ // mention it would otherwise turn into one register call per workspace
+ // every few minutes, forever.
+ carried := builtinVersionsFromPayload(builtins)
+
+ // A workspace is behind when some carried provider's last accepted register
+ // call for it carried a different version. A provider with no record for a
+ // workspace is skipped: it has never registered there, so bringing it
+ // online is the converge path's job, not a version change.
+ d.mu.Lock()
+ var behind []string
+ transitions := make(map[string]struct{})
+ for id, ws := range d.workspaces {
+ lagging := false
+ for provider, version := range carried {
+ sent, has := ws.builtinVersions[provider]
+ if !has || sent == version {
+ continue
+ }
+ lagging = true
+ if sent == "" {
+ transitions[fmt.Sprintf("%s %s", provider, version)] = struct{}{}
+ } else {
+ transitions[fmt.Sprintf("%s %s -> %s", provider, sent, version)] = struct{}{}
+ }
+ }
+ if lagging {
+ behind = append(behind, id)
+ }
+ }
+ d.mu.Unlock()
+ if len(behind) == 0 {
+ return
+ }
+ sort.Strings(behind)
+ advancing := make([]string, 0, len(transitions))
+ for t := range transitions {
+ advancing = append(advancing, t)
+ }
+ sort.Strings(advancing)
+ d.logger.Info("agent CLI version not yet on the server; refreshing registration without a restart",
+ "versions", advancing, "workspace_ids", behind)
+
+ // Register only the workspaces that are behind. A failure records nothing,
+ // so that workspace stays behind and the next round retries it.
+ var changed bool
+ for _, id := range behind {
+ // Send, merge and clean up as one ordered step — see
+ // workspaceRegisterLock.
+ _ = d.withWorkspaceRegisterLock(id, func() error {
+ resp, err := d.registerBuiltinRuntimesForWorkspaceLocked(ctx, id, builtins)
+ if err != nil {
+ d.logger.Warn("re-register after agent CLI version change failed; will retry",
+ "workspace_id", id, "error", err)
+ return nil
+ }
+ newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse(id, resp)
+ if !ok {
+ return nil
+ }
+ if len(newIDs) > 0 {
+ changed = true
+ }
+ d.deregisterRevivedRuntimes(ctx, id, rejectedIDs)
+ return nil
+ })
+ }
+ if changed {
+ d.notifyRuntimeSetChanged()
+ }
+}
+
+// demoteBelowMinimumRuntimes takes offline the built-in runtimes of providers
+// whose re-probe confirmed a version below the minimum supported one.
+//
+// Without this, an in-place DOWNGRADE is the one machine change nothing reacts
+// to. probeBuiltinRuntime drops the provider from the registration payload, so
+// refreshAgentVersions sees no version to compare; the runtime row survives
+// because the built-in merge is additive; and the provider is absent from
+// providersMissingRuntimes precisely because it still holds a runtime — so
+// converge ignores it too. The daemon keeps routing tasks to a binary it has
+// already verified it cannot run correctly, under the previously cached
+// version's policy.
+//
+// Deregistering is the narrowest honest response. It stops the server routing
+// work there, the reason is already visible in skipped_agents, and recovery
+// needs no new machinery: once the provider is upgraded it has no runtime, which
+// puts it back in providersMissingRuntimes and lets the converge path register
+// it again. The alternative — keeping the runtime and refusing the launch — puts
+// a check on the hot path and leaves the UI advertising a runtime that rejects
+// everything.
+//
+// Only ever acts on builtinProbeBelowMinimum, never on a probe that merely
+// failed: an unreadable version is transient, and tearing down a working
+// runtime over one is exactly the mistake refreshAgentAvailability's
+// one-directional rule exists to avoid.
+func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum map[string]string) {
+ // Serialize with task claiming the way the restart paths do: the barrier
+ // only sets when no claim is in flight and no task is running, so a
+ // runtime is never deregistered under a task that is still executing —
+ // the server's sweep would fail-and-retry that task while the local
+ // process keeps going, and an upgrade-back would revive the runtime ID
+ // into a genuine duplicate execution. A busy daemon defers to the next
+ // refresh tick; the too-old CLI keeps its runtimes a little longer, which
+ // is the pre-demotion status quo, not a new exposure.
+ if !d.trySetClaimBarrier() {
+ d.logger.Info("defer below-minimum demotion: task or claim in flight",
+ "providers", belowMinimum)
+ return
+ }
+ defer d.releaseClaimBarrier()
+
+ d.mu.Lock()
+ var demoted []string
+ // Grouped per workspace because the cleanup below has to run under each
+ // workspace's register lock — see deregisterDroppedRuntimes.
+ demotedByWorkspace := make(map[string][]string)
+ demotedProviders := make(map[string]string)
+ for workspaceID, ws := range d.workspaces {
+ // A fresh array, not ws.runtimeIDs[:0]: the health handler copies this
+ // slice header under d.mu and serializes it after releasing the lock
+ // (removeStaleRuntime keeps the same rule), so filtering in place would
+ // write into a slice another goroutine is reading.
+ kept := ws.runtimeIDs[:0:0]
+ for _, rid := range ws.runtimeIDs {
+ rt, ok := d.runtimeIndex[rid]
+ if !ok || rt.ProfileID != "" {
+ kept = append(kept, rid)
+ continue
+ }
+ version, below := belowMinimum[rt.Provider]
+ if !below {
+ kept = append(kept, rid)
+ continue
+ }
+ delete(d.runtimeIndex, rid)
+ demoted = append(demoted, rid)
+ demotedByWorkspace[workspaceID] = append(demotedByWorkspace[workspaceID], rid)
+ demotedProviders[rt.Provider] = version
+ // The runtime is gone, so the record of what was registered for it
+ // goes too. When the provider recovers, converge re-registers it and
+ // the record is re-seeded — first sighting is converge's job, not a
+ // version change for the refresh round to chase.
+ delete(ws.builtinVersions, rt.Provider)
+ }
+ ws.runtimeIDs = kept
+ }
+ // Remember the verdict before releasing d.mu. Removing the rows is not
+ // enough: a register sent before this demotion is still in flight, and its
+ // response would re-index the provider the moment it lands. The apply paths
+ // consult this under the same lock, so the two are totally ordered.
+ d.markProvidersDemotedLocked(belowMinimum)
+ d.mu.Unlock()
+
+ if len(demoted) == 0 {
+ return
+ }
+ d.logger.Warn("agent CLI downgraded below the minimum supported version; taking its runtimes offline",
+ "providers", demotedProviders, "runtime_ids", demoted)
+
+ // One workspace at a time, each under its own register lock: the rows were
+ // dropped under d.mu but the requests go out without it, so an upgrade that
+ // recovered the provider in between must not be undone by this older
+ // cleanup. Sorted so the log order is deterministic; never two locks at
+ // once, so there is no ordering to deadlock on.
+ workspaceIDs := make([]string, 0, len(demotedByWorkspace))
+ for workspaceID := range demotedByWorkspace {
+ workspaceIDs = append(workspaceIDs, workspaceID)
+ }
+ sort.Strings(workspaceIDs)
+ for _, workspaceID := range workspaceIDs {
+ _ = d.withWorkspaceRegisterLock(workspaceID, func() error {
+ d.deregisterDroppedRuntimes(ctx, workspaceID, demotedByWorkspace[workspaceID],
+ "below-minimum downgrade")
+ return nil
+ })
+ }
+ d.notifyRuntimeSetChanged()
+}
+
+// deregisterRevivedRuntimes takes offline the rows a register response brought
+// back for a provider that was demoted while that register was in flight.
+//
+// The local apply already refused them, so without this the server would be the
+// only side still believing the runtime is online: it would keep the row in the
+// runtime list and route work to a daemon that no longer tracks it, and those
+// tasks would sit unclaimed until the stale-heartbeat sweep. Best-effort for the
+// same reason every other deregistration path is — the sweep is the backstop.
+//
+// The caller must hold the workspace's register lock (workspaceRegisterLock).
+func (d *Daemon) deregisterRevivedRuntimes(ctx context.Context, workspaceID string, runtimeIDs []string) {
+ // Re-check tracking first: the rejection happened under d.mu but this call
+ // runs without it, and a legitimate recovery register landing in that gap
+ // re-creates the same row — usually under the same ID. Deregistering then
+ // would take the recovered runtime offline on the strength of an older
+ // decision. Anything the daemon tracks now is newer than this cleanup, and
+ // the register lock is what stops a recovery slipping in between this check
+ // and the request below.
+ runtimeIDs = d.untrackedRuntimeIDs(runtimeIDs)
+ if len(runtimeIDs) == 0 {
+ return
+ }
+ d.logger.Warn("register response revived a below-minimum runtime; taking it offline again",
+ "workspace_id", workspaceID, "runtime_ids", runtimeIDs)
+ if err := d.client.Deregister(ctx, runtimeIDs); err != nil {
+ d.logger.Warn("deregister of revived below-minimum runtimes failed",
+ "workspace_id", workspaceID, "runtime_ids", runtimeIDs, "error", err)
+ }
+}
+
+// deregisterDroppedRuntimes takes offline the server-side rows a convergence
+// decided this workspace should no longer host — a provider removed from the
+// daemon's config, a disabled custom profile, a workspace converging to zero.
+//
+// Same contract as deregisterRevivedRuntimes: the caller must hold the
+// workspace's register lock, so the tracking re-check and the request are one
+// ordered step against every other registration for this workspace. Without the
+// lock this is a TOCTOU — a recovery register completing between the two puts
+// the row back and this older cleanup knocks it out, leaving the daemon tracking
+// a runtime the server has offline.
+//
+// Best-effort: the daemon has already stopped heartbeating these rows, so the
+// server's stale-heartbeat sweep is the backstop if the call fails.
+func (d *Daemon) deregisterDroppedRuntimes(ctx context.Context, workspaceID string, runtimeIDs []string, reason string) {
+ runtimeIDs = d.untrackedRuntimeIDs(runtimeIDs)
+ if len(runtimeIDs) == 0 {
+ return
+ }
+ if err := d.client.Deregister(ctx, runtimeIDs); err != nil {
+ d.logger.Warn("deregister of dropped runtimes failed",
+ "workspace_id", workspaceID, "runtime_ids", runtimeIDs, "reason", reason, "error", err)
+ }
+}
+
// providersMissingRuntimes returns the discovered providers that do not have a
// built-in runtime registered for every tracked workspace.
//
@@ -232,7 +560,7 @@ func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {
// detectBuiltinRuntimes version-gates the availability set and publishes
// this round's drops for /health, so a provider that cannot register still
// gets a visible reason even though registration is skipped.
- builtins := d.detectBuiltinRuntimes(ctx)
+ builtins, _, _ := d.detectBuiltinRuntimes(ctx)
if len(builtins) == 0 {
return
}
@@ -275,22 +603,28 @@ func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {
var changed bool
for _, t := range targets {
- resp, err := d.registerBuiltinRuntimesForWorkspace(ctx, t.id, builtins)
- if err != nil {
- // Left in the missing set on purpose: the next tick retries.
- d.logger.Warn("register newly available runtimes failed; will retry",
- "workspace_id", t.id, "providers", t.missing, "error", err)
- continue
- }
- newIDs, ok := d.mergeBuiltinRegisterResponse(t.id, resp)
- if !ok {
- continue
- }
- if len(newIDs) > 0 {
- changed = true
- d.logger.Info("registered runtime for newly installed agent CLI",
- "workspace_id", t.id, "providers", t.missing, "runtime_ids", newIDs)
- }
+ // Send, merge and clean up as one ordered step — see
+ // workspaceRegisterLock.
+ _ = d.withWorkspaceRegisterLock(t.id, func() error {
+ resp, err := d.registerBuiltinRuntimesForWorkspaceLocked(ctx, t.id, builtins)
+ if err != nil {
+ // Left in the missing set on purpose: the next tick retries.
+ d.logger.Warn("register newly available runtimes failed; will retry",
+ "workspace_id", t.id, "providers", t.missing, "error", err)
+ return nil
+ }
+ newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse(t.id, resp)
+ if !ok {
+ return nil
+ }
+ if len(newIDs) > 0 {
+ changed = true
+ d.logger.Info("registered runtime for newly installed agent CLI",
+ "workspace_id", t.id, "providers", t.missing, "runtime_ids", newIDs)
+ }
+ d.deregisterRevivedRuntimes(ctx, t.id, rejectedIDs)
+ return nil
+ })
}
if changed {
d.notifyRuntimeSetChanged()
diff --git a/server/internal/daemon/agents_refresh_test.go b/server/internal/daemon/agents_refresh_test.go
index 116fe12db9..310534d441 100644
--- a/server/internal/daemon/agents_refresh_test.go
+++ b/server/internal/daemon/agents_refresh_test.go
@@ -10,6 +10,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
)
// stubAgentProbe replaces CLI discovery for the duration of a test. The returned
@@ -396,7 +398,7 @@ func TestDiscovery_BelowMinVersionRecoversAfterUpgrade(t *testing.T) {
t.Cleanup(func() { checkAgentMinVersion = origCheck })
checkAgentMinVersion = func(provider, _ string) error {
if provider == "antigravity" && tooOld {
- return errors.New("antigravity version 1.0.0 is below minimum required 1.1.0")
+ return &agent.BelowMinimumError{AgentType: provider, Detected: "1.0.0", Minimum: "1.1.0"}
}
return nil
}
@@ -572,7 +574,7 @@ func TestMergeBuiltinRegisterResponse_ReplacesRotatedRuntimeID(t *testing.T) {
d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{"rt-old"}, "", nil, nil)
d.runtimeIndex["rt-old"] = Runtime{ID: "rt-old", Provider: "codex"}
- newIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
+ newIDs, _, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
Runtimes: []Runtime{{ID: "rt-new", Provider: "codex"}},
})
if !ok {
@@ -596,7 +598,7 @@ func TestMergeBuiltinRegisterResponse_IgnoresCustomProfileRuntimes(t *testing.T)
d := freshDaemon("http://localhost:0")
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)
- newIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
+ newIDs, _, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
Runtimes: []Runtime{
{ID: "rt-builtin", Provider: "codex"},
{ID: "rt-custom", Provider: "codex", ProfileID: "prof-1"},
@@ -621,7 +623,7 @@ func TestMergeBuiltinRegisterResponse_NeverTouchesProfileSignature(t *testing.T)
ws.profileSetSig = "sig-before"
d.workspaces["ws-1"] = ws
- if _, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
+ if _, _, ok := d.mergeBuiltinRegisterResponse("ws-1", &RegisterResponse{
Runtimes: []Runtime{{ID: "rt-1", Provider: "codex"}},
}); !ok {
t.Fatal("merge reported the workspace as untracked")
diff --git a/server/internal/daemon/auto_update.go b/server/internal/daemon/auto_update.go
index 2d1673524c..40b1c22044 100644
--- a/server/internal/daemon/auto_update.go
+++ b/server/internal/daemon/auto_update.go
@@ -2,6 +2,9 @@ package daemon
import (
"context"
+ "fmt"
+ "os/exec"
+ "strings"
"time"
"github.com/multica-ai/multica/server/internal/cli"
@@ -17,6 +20,46 @@ var (
isNewerVersion = cli.IsNewerVersion
)
+// detectSelfVersion runs `<path> --version` and returns the version field.
+// Indirection so tests never fork a real process.
+var detectSelfVersion = func(ctx context.Context, path string) (string, error) {
+ cmd := exec.CommandContext(ctx, path, "--version")
+ // Context cancellation only kills the direct child; a descendant that
+ // inherited our stdout pipe keeps Output() blocked past the deadline.
+ // WaitDelay force-closes the pipes after the kill — without it a replaced
+ // binary that misbehaves would park the autoUpdateLoop goroutine forever
+ // with the updating flag held. Same guard as detectCLIVersion.
+ cmd.WaitDelay = 2 * time.Second
+ out, err := cmd.Output()
+ if err != nil {
+ return "", fmt.Errorf("run %s --version: %w", path, err)
+ }
+ return ParseSelfVersion(string(out)), nil
+}
+
+// ParseSelfVersion pulls the version out of `multica --version` output, whose
+// first line is rendered by cmd/multica's version template:
+//
+// multica 0.3.7 (commit: abc1234, built: 2026-07-29T10:00:00Z)
+// go: go1.26.1, os/arch: darwin/arm64
+//
+// The extracted field is exactly what ldflags put in main.version, which is
+// also what lands in Config.CLIVersion — so the two are directly comparable.
+// Anything that doesn't match the template shape is returned trimmed, which
+// compares unequal and is therefore reported rather than silently ignored.
+//
+// Exported solely so cmd/multica can pin that contract from the producing side:
+// this parser and the version template have to agree, and nothing else would
+// notice if a template edit silently broke the auto-reload probe.
+func ParseSelfVersion(raw string) string {
+ line, _, _ := strings.Cut(raw, "\n")
+ line = strings.TrimSpace(line)
+ if fields := strings.Fields(line); len(fields) >= 2 && fields[0] == "multica" {
+ return fields[1]
+ }
+ return line
+}
+
// autoUpdateInitialDelay is how long the loop waits after Run() returns before
// performing its first version check. The daemon has plenty to do at startup
// (auth, register, sync workspaces, kick off heartbeats); we don't want to add
@@ -25,59 +68,112 @@ var (
// within a couple of minutes rather than after the full check interval.
var autoUpdateInitialDelay = 2 * time.Minute
-// autoUpdateLoop periodically polls GitHub for a newer CLI release and, when
-// one is available and the daemon is idle, runs the same brew-or-download
-// upgrade path as the server-triggered update. On success it triggers a
-// graceful restart into the new binary.
+// selfReloadCheckInterval is how often the loop compares the version compiled
+// into this process against the `--version` output of the binary it would
+// re-exec. One fork/exec per tick, machine-level (not per workspace, not per
+// runtime), so the cost is fixed no matter how big the daemon's workload is.
+// Overridable for tests.
+var selfReloadCheckInterval = 5 * time.Minute
+
+// selfReloadProbeTimeout bounds the `--version` fork/exec. Generous: the point
+// of the timeout is to stop a wedged binary from parking the loop goroutine,
+// not to police a slow disk.
+var selfReloadProbeTimeout = 10 * time.Second
+
+// autoUpdateLoop owns everything that can end in "restart this daemon into a
+// different multica binary". It runs two independent checks on one goroutine,
+// which is what keeps them from racing each other into triggerRestart:
+//
+// - tryAutoUpdate: poll GitHub for a newer release and, when the daemon is
+// idle, run the same brew-or-download upgrade as the server-triggered path.
+// - trySelfReload: notice that the binary on disk was replaced out of band
+// and re-exec into it.
+//
+// Both are skipped entirely for Desktop-managed daemons: the Electron app ships
+// and replaces the CLI binary itself, so self-updating would be clobbered on
+// the next launch and re-execing would fight the app's own lifecycle.
//
-// Disabled when:
-// - the operator opted out via --no-auto-update / MULTICA_DAEMON_AUTO_UPDATE=false;
-// - the daemon points at a self-hosted server (default-off — set
-// MULTICA_DAEMON_AUTO_UPDATE=true to opt back in);
-// - the daemon was spawned by Desktop (the Electron app owns the binary);
-// - the running version doesn't look like a tagged release (dev builds).
+// The GitHub half is additionally skipped when the operator opted out
+// (--no-auto-update / MULTICA_DAEMON_AUTO_UPDATE=false), when the server is
+// self-hosted (default-off, MUL-2381), or when the running version isn't a
+// tagged release — source builds (`make daemon`) report a `git describe`-style
+// version and upgrading them to a public release would silently discard the dev
+// work on the machine. None of those apply to the on-disk half, which follows a
+// binary the operator installed themselves; see trySelfReload.
//
-// Each tick is silent on the happy path of "already on latest" so the log
-// stays uncluttered for users who run the daemon for weeks at a time.
+// Each tick is silent on the happy path so the log stays uncluttered for users
+// who run the daemon for weeks at a time.
func (d *Daemon) autoUpdateLoop(ctx context.Context) {
- if !d.cfg.AutoUpdateEnabled {
- d.logger.Info("auto-update: disabled")
- return
- }
if d.cfg.LaunchedBy == "desktop" {
- // Desktop ships and replaces the CLI binary itself; self-update would
- // be clobbered on the next launch. Stay quiet but don't run.
d.logger.Info("auto-update: skipped (managed by Desktop)")
return
}
- if !isReleaseVersion(d.cfg.CLIVersion) {
- // Source builds (`make daemon`) and ad-hoc builds report a
- // `git describe`-style version; auto-upgrading them to a public
- // release would silently downgrade the dev work checked out on the
- // machine. Skip and let the developer drive their own version.
+
+ pullEnabled := d.cfg.AutoUpdateEnabled
+ switch {
+ case !pullEnabled:
+ d.logger.Info("auto-update: disabled")
+ case !isReleaseVersion(d.cfg.CLIVersion):
d.logger.Info("auto-update: skipped (not a release build)", "version", d.cfg.CLIVersion)
+ pullEnabled = false
+ }
+ reloadEnabled := d.cfg.AutoReloadEnabled
+ if !reloadEnabled {
+ d.logger.Info("auto-reload: disabled")
+ }
+ if !pullEnabled && !reloadEnabled {
return
}
- interval := d.cfg.AutoUpdateCheckInterval
- if interval <= 0 {
- interval = DefaultAutoUpdateCheckInterval
+ pullInterval := d.cfg.AutoUpdateCheckInterval
+ if pullInterval <= 0 {
+ pullInterval = DefaultAutoUpdateCheckInterval
+ }
+ // Log what each half will do before the startup delay, so a user reading
+ // daemon.log right after `daemon start` sees it immediately.
+ if pullEnabled {
+ d.logger.Info("auto-update: started", "interval", pullInterval, "current", d.cfg.CLIVersion)
+ }
+ if reloadEnabled {
+ d.logger.Info("auto-reload: watching the multica binary on disk",
+ "interval", selfReloadCheckInterval, "current", d.cfg.CLIVersion)
}
- d.logger.Info("auto-update: started", "interval", interval, "current", d.cfg.CLIVersion)
if err := sleepWithContext(ctx, autoUpdateInitialDelay); err != nil {
return
}
- d.tryAutoUpdate(ctx)
+ if pullEnabled {
+ d.tryAutoUpdate(ctx)
+ }
+ if reloadEnabled {
+ d.trySelfReload(ctx)
+ }
+
+ // Tickers start only now, after the first check. Starting them before the
+ // delay would let an interval shorter than autoUpdateInitialDelay buffer a
+ // tick and fire a second check immediately after the first.
+ //
+ // A disabled half leaves its channel nil, which never fires in a select.
+ var pullTick, reloadTick <-chan time.Time
+ if pullEnabled {
+ ticker := time.NewTicker(pullInterval)
+ defer ticker.Stop()
+ pullTick = ticker.C
+ }
+ if reloadEnabled {
+ ticker := time.NewTicker(selfReloadCheckInterval)
+ defer ticker.Stop()
+ reloadTick = ticker.C
+ }
- ticker := time.NewTicker(interval)
- defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
- case <-ticker.C:
+ case <-pullTick:
d.tryAutoUpdate(ctx)
+ case <-reloadTick:
+ d.trySelfReload(ctx)
}
}
}
@@ -165,6 +261,16 @@ func (d *Daemon) tryAutoUpdate(ctx context.Context) {
}
d.logger.Info("auto-update: upgrade completed, restarting", "target", release.TagName, "output", output)
+ if !d.triggerRestart() {
+ // The upgrade landed but the handoff target could not be resolved, so
+ // no process exit is coming. Fall through to both deferred restores:
+ // holding the updating flag and the claim barrier for a restart that
+ // will never happen stops this daemon from claiming any task, forever.
+ // The next tick retries — and since the binary on disk is already the
+ // new one, trySelfReload will keep trying too.
+ d.logger.Error("auto-update: upgrade completed but restart could not be scheduled — resuming claims")
+ return
+ }
// triggerRestart cancels the root context, which causes Run() to return
// and the parent (cmd_daemon.go) to re-exec the new binary. Leave both
// the updating flag and the claim barrier held — process exit is
@@ -172,5 +278,146 @@ func (d *Daemon) tryAutoUpdate(ctx context.Context) {
// second auto-update tick to fire mid-shutdown.
released = true
barrierReleased = true
- d.triggerRestart()
+}
+
+// trySelfReload restarts the daemon when the multica binary on disk no longer
+// reports the version compiled into this process.
+//
+// This is the out-of-band half of self-update. `brew upgrade multica`, a
+// re-download, or a developer's `make build` all replace the binary at the same
+// path, and the daemon then keeps serving the version it booted with: its own
+// version string is frozen at compile time, and the pinned-path self-heal in
+// resolveAgentEntry only fires when a path *vanishes*, which an in-place
+// overwrite never does.
+//
+// tryAutoUpdate does eventually recover the most common shape of this — the
+// running version is older than the latest release, so it re-runs the upgrade
+// (a no-op under brew) and restarts. What it cannot recover is the rest:
+// self-hosted daemons where auto-update is default-off (MUL-2381), dev builds
+// skipped by isReleaseVersion, and installing something GitHub doesn't consider
+// newer (a deliberate downgrade, or an intermediate version). It is also up to
+// a full check interval slow. This check closes all of that, which is why it
+// has its own switch (--no-auto-reload / MULTICA_DAEMON_AUTO_RELOAD=false /
+// disable_auto_reload) rather than riding on MULTICA_DAEMON_AUTO_UPDATE.
+//
+// Restart mechanics are shared with tryAutoUpdate rather than reinvented:
+// the same trySetClaimBarrier keeps a running task from being interrupted, and
+// the same triggerRestart performs the handoff. There is deliberately no
+// pending-restart state machine and no drain hook — a busy daemon just defers
+// to the next tick, so the check cannot leave claiming paused while waiting for
+// something to wake it. The deferral is recorded in reloadPendingReason purely
+// so /health can explain why the daemon is still on the old version.
+//
+// A failed probe is never treated as a version change. The binary is most
+// likely to be unreadable during the few hundred milliseconds of the very
+// upgrade this check exists to detect (vanished path, ETXTBSY — the same class
+// runtimeVersionProbeAttempts documents), and "couldn't read the version" is
+// not a reason to restart into one.
+func (d *Daemon) trySelfReload(ctx context.Context) {
+ if ctx.Err() != nil {
+ return
+ }
+ if d.RestartBinary() != "" {
+ return
+ }
+ // Acquire update ownership rather than sampling it. A plain Load() is only a
+ // hint: handleUpdate could win the CAS in the gap between the read and
+ // triggerRestart, and this path would then cancel the root context while the
+ // binary is still being replaced — re-execing a half-written file and cutting
+ // the server-triggered update's status reporting off partway. The CAS is the
+ // only thing that actually arbitrates, because the claim barrier does not:
+ // handleUpdate reaches it through tryBeginServerUpdate, and the two never
+ // inspect each other's state. Same shape tryAutoUpdate uses.
+ //
+ // Released on every exit below except a successful handoff, where the process
+ // is about to go down and clearing it would let a second attempt start
+ // mid-shutdown.
+ if !d.updating.CompareAndSwap(false, true) {
+ d.logger.Debug("auto-reload: skip — update already in progress")
+ return
+ }
+ released := false
+ defer func() {
+ if !released {
+ d.updating.Store(false)
+ }
+ }()
+
+ // Probe the binary the restart would actually exec, not os.Executable():
+ // under brew those differ, and following the stable symlink is the whole
+ // point of restartTargetBinary.
+ target, err := d.restartTargetBinary()
+ if err != nil {
+ d.logger.Warn("auto-reload: could not resolve own executable — will retry", "error", err)
+ return
+ }
+ probeCtx, cancel := context.WithTimeout(ctx, selfReloadProbeTimeout)
+ defer cancel()
+ onDisk, err := detectSelfVersion(probeCtx, target)
+ if err != nil {
+ d.logger.Warn("auto-reload: version probe failed — will retry, not treating it as a change",
+ "binary", target, "error", err)
+ return
+ }
+ // Either side blank makes the comparison meaningless, and acting on it would
+ // be worse than doing nothing: a blank on-disk version is a probe that
+ // technically exited 0 without telling us anything, and a blank running
+ // version would restart into a successor that reads blank too — a reload
+ // every tick, forever.
+ if onDisk == "" || d.cfg.CLIVersion == "" {
+ d.logger.Warn("auto-reload: version unavailable — will retry, not treating it as a change",
+ "binary", target, "on_disk", onDisk, "running", d.cfg.CLIVersion)
+ return
+ }
+ if onDisk == d.cfg.CLIVersion {
+ d.clearReloadPending()
+ return
+ }
+
+ reason := fmt.Sprintf("multica binary on disk reports %s, running %s", onDisk, d.cfg.CLIVersion)
+ d.setReloadPending(reason)
+
+ if !d.trySetClaimBarrier() {
+ d.logger.Info("auto-reload: deferring — task or claim in flight at barrier check", "reason", reason)
+ return
+ }
+ barrierReleased := false
+ defer func() {
+ if !barrierReleased {
+ d.releaseClaimBarrier()
+ }
+ }()
+
+ d.logger.Info("auto-reload: restarting into the binary on disk", "reason", reason, "binary", target)
+ if !d.triggerRestart() {
+ // Resolution failed at the handoff. Both deferred restores run: a failed
+ // restart must never cost the daemon its ability to claim, nor leave the
+ // update flag held against a restart that is not coming. The next tick
+ // re-probes from scratch, so there is no stale baseline to re-detect.
+ return
+ }
+ released = true
+ barrierReleased = true
+}
+
+// setReloadPending records that a multica version change is confirmed but the
+// restart is waiting for the daemon to go idle. Purely diagnostic — surfaced on
+// /health and `daemon status` — and it gates nothing, so it can never park the
+// daemon the way a pending-state machine could.
+func (d *Daemon) setReloadPending(reason string) {
+ d.reloadPendingReason.Store(&reason)
+}
+
+// clearReloadPending drops the note once the on-disk version matches again
+// (the operator reverted the binary before the daemon went idle).
+func (d *Daemon) clearReloadPending() {
+ d.reloadPendingReason.Store(nil)
+}
+
+// reloadPending reports the deferred-restart reason, empty when none.
+func (d *Daemon) reloadPending() string {
+ if reason := d.reloadPendingReason.Load(); reason != nil {
+ return *reason
+ }
+ return ""
}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 0a84db08df..a6be8c3945 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -106,6 +106,7 @@ type Config struct {
GCCodexSessionTTL time.Duration // reclaim a per-issue Codex session store (~/.codex/multica-sessions/<agent>/<issue>) untouched for at least this long, so a done/abandoned issue's conversation history does not accumulate forever (default: 14d, set 0 to disable)
AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true on Multica Cloud, false on self-host)
AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)
+ AutoReloadEnabled bool // restart when the multica binary on disk no longer matches the running version (default: true for CLI-launched daemons)
PollInterval time.Duration
HeartbeatInterval time.Duration
AgentTimeout time.Duration
@@ -155,6 +156,10 @@ type Overrides struct {
// resolves to enabled; the flag exists so users can opt out from the CLI.
DisableAutoUpdate bool
AutoUpdateCheckInterval time.Duration // 0 = use env/default
+ // DisableAutoReload, when true, forces the on-disk version watcher off.
+ // Single-direction for the same reason as DisableAutoUpdate: the
+ // env/default already resolves to enabled.
+ DisableAutoReload bool
}
// LoadConfig builds the daemon configuration from environment variables
@@ -429,15 +434,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
// older server build, which a fresh CLI may no longer talk to. Keeping
// auto-update off by default for self-host avoids both footguns (MUL-2381).
// Operators on either side can flip the default with MULTICA_DAEMON_AUTO_UPDATE.
- autoUpdateEnabled := isOfficialCloudServer(serverBaseURL)
- if v := strings.TrimSpace(os.Getenv("MULTICA_DAEMON_AUTO_UPDATE")); v != "" {
- switch strings.ToLower(v) {
- case "false", "0", "no", "off":
- autoUpdateEnabled = false
- case "true", "1", "yes", "on":
- autoUpdateEnabled = true
- }
- }
+ autoUpdateEnabled := boolFromEnv("MULTICA_DAEMON_AUTO_UPDATE", isOfficialCloudServer(serverBaseURL))
if overrides.DisableAutoUpdate {
autoUpdateEnabled = false
}
@@ -449,6 +446,17 @@ func LoadConfig(overrides Overrides) (Config, error) {
autoUpdateInterval = overrides.AutoUpdateCheckInterval
}
+ // Auto-reload is deliberately NOT gated on autoUpdateEnabled. "Don't pull
+ // new versions from GitHub" and "follow the binary I replaced myself" are
+ // different concerns, and the self-host rationale for defaulting the former
+ // off (don't clobber my fork) argues the opposite way for the latter: an
+ // operator who installed a build by hand wants the daemon to run it.
+ // Default on for every CLI-launched daemon; Desktop opts out at the loop.
+ autoReloadEnabled := boolFromEnv("MULTICA_DAEMON_AUTO_RELOAD", true)
+ if overrides.DisableAutoReload {
+ autoReloadEnabled = false
+ }
+
return Config{
ServerBaseURL: serverBaseURL,
DaemonID: daemonID,
@@ -469,6 +477,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
GCCodexSessionTTL: gcCodexSessionTTL,
AutoUpdateEnabled: autoUpdateEnabled,
AutoUpdateCheckInterval: autoUpdateInterval,
+ AutoReloadEnabled: autoReloadEnabled,
HealthPort: healthPort,
MaxConcurrentTasks: maxConcurrentTasks,
PollInterval: pollInterval,
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 2ccd606ee1..6e8275229c 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -591,6 +591,84 @@ func TestLoadConfig_AutoUpdate_NoFlagWinsOverCloudDefault(t *testing.T) {
}
}
+// TestLoadConfig_AutoReload_DefaultsOnEvenForSelfHost is the review's first
+// product decision, encoded: "don't pull new versions from GitHub" and "follow
+// the binary I replaced myself" are separate concerns. Self-host defaults
+// auto-update OFF (MUL-2381) because upgrading a fork from an upstream release
+// would clobber it — an argument that says nothing about a binary the operator
+// installed by hand.
+func TestLoadConfig_AutoReload_DefaultsOnEvenForSelfHost(t *testing.T) {
+ stageFakeAgent(t)
+ t.Setenv("MULTICA_DAEMON_AUTO_UPDATE", "")
+ t.Setenv("MULTICA_DAEMON_AUTO_RELOAD", "")
+ cfg, err := LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if cfg.AutoUpdateEnabled {
+ t.Fatalf("AutoUpdateEnabled = true for self-host, want false (MUL-2381)")
+ }
+ if !cfg.AutoReloadEnabled {
+ t.Fatalf("AutoReloadEnabled = false for self-host; the on-disk watcher must not ride on the auto-update default")
+ }
+}
+
+// TestLoadConfig_AutoReload_NotGatedOnAutoUpdateEnv is the same decoupling at
+// the env layer: turning GitHub polling off must not silently stop the daemon
+// from following a hand-installed binary.
+func TestLoadConfig_AutoReload_NotGatedOnAutoUpdateEnv(t *testing.T) {
+ stageFakeAgent(t)
+ t.Setenv("MULTICA_DAEMON_AUTO_UPDATE", "false")
+ t.Setenv("MULTICA_DAEMON_AUTO_RELOAD", "")
+ cfg, err := LoadConfig(Overrides{
+ ServerURL: "https://api.multica.ai",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if !cfg.AutoReloadEnabled {
+ t.Fatalf("MULTICA_DAEMON_AUTO_UPDATE=false disabled auto-reload; the two switches are independent")
+ }
+}
+
+// TestLoadConfig_AutoReload_OffSwitches pins the escape hatch across both layers
+// it can be turned off from. The config-file layer resolves to
+// overrides.DisableAutoReload in cmd_daemon.go, so it is covered by the same
+// assertion as the flag.
+func TestLoadConfig_AutoReload_OffSwitches(t *testing.T) {
+ cases := []struct {
+ name string
+ env string
+ overrides Overrides
+ }{
+ {name: "env false", env: "false"},
+ {name: "env 0", env: "0"},
+ {name: "env off", env: "off"},
+ {name: "flag or config file", env: "", overrides: Overrides{DisableAutoReload: true}},
+ {name: "flag beats a truthy env", env: "true", overrides: Overrides{DisableAutoReload: true}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ stageFakeAgent(t)
+ t.Setenv("MULTICA_DAEMON_AUTO_RELOAD", tc.env)
+ overrides := tc.overrides
+ overrides.ServerURL = "https://api.multica.ai"
+ overrides.WorkspacesRoot = t.TempDir()
+ cfg, err := LoadConfig(overrides)
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if cfg.AutoReloadEnabled {
+ t.Fatalf("AutoReloadEnabled = true, want false")
+ }
+ })
+ }
+}
+
// TestResolveAgentsViaLoginShell_StripsAliasShadowing locks down the fix for
// #2512: when the user's rc file declares an alias with the same name as the
// agent CLI, the resolver must still return the real binary on PATH, not the
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 3808d53453..abe8384cdc 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -239,6 +239,20 @@ type workspaceState struct {
// successful profile fetch (older server / network blip); guarded by
// Daemon.mu like every other field on this struct.
profileSetSig string
+ // builtinVersions records, per built-in provider, the version carried by
+ // the last register call the server ACCEPTED for this workspace. This is
+ // the daemon's per-workspace record of what the server knows — which the
+ // shared agentVersions cache deliberately is not: every probing path
+ // writes that cache, but each register call covers only the workspaces it
+ // was invoked for. refreshAgentVersions compares this record against the
+ // current probe round and re-registers exactly the workspaces that are
+ // behind. Scoping the acknowledgement to the workspace is what makes a
+ // concurrent older-generation registration safe: a register that probed
+ // before an upgrade and lands after everyone else was refreshed simply
+ // re-creates the mismatch for its own workspace, and the next round
+ // revisits it. A failed register records nothing, so the workspace stays
+ // behind and is retried. Guarded by Daemon.mu.
+ builtinVersions map[string]string
}
type repoCacheBackend interface {
@@ -272,6 +286,13 @@ type Daemon struct {
versionsMu sync.RWMutex // guards agentVersions
agentVersions map[string]string // provider -> detected CLI version (set during registration)
+ // registerSerial holds one mutex per workspace (workspace_id ->
+ // *sync.Mutex), serializing the "send Register, record what it carried"
+ // critical section (workspaceRegisterLock). Entries are never deleted — a
+ // daemon tracks a handful of workspaces, and a mutex for a workspace that
+ // went away is a few bytes, not a leak worth a lifecycle.
+ registerSerial sync.Map
+
// agentsAvailable holds the current built-in agent CLI availability set —
// the same shape as cfg.Agents, which it supersedes as the read path.
//
@@ -290,6 +311,42 @@ type Daemon struct {
skippedAgentsMu sync.RWMutex
skippedAgents map[string]string // provider -> human-readable reason
+ // demotedProviders remembers the built-in providers whose version was
+ // CONFIRMED below the minimum supported one and whose runtimes
+ // demoteBelowMinimumRuntimes has already taken offline.
+ //
+ // Removing the rows is not enough on its own: a register call that was
+ // already in flight when the demotion landed still carries the pre-demotion
+ // payload, and its response arrives afterwards. Every apply path treats a
+ // response as fresh truth, so it re-indexes the provider locally while the
+ // server's upsert puts the row back online — reviving a CLI the daemon has
+ // already proven it cannot run, until the next refresh tick notices.
+ // Remembering the verdict lets the apply paths reject that late response.
+ //
+ // Machine-level, because the verdict is a property of the binary on this
+ // host rather than of any one workspace: a stale register for workspace A
+ // must not revive the provider for workspace B either. Cleared by the next
+ // probe round that finds the provider acceptable again, which is also the
+ // round that lets converge register it.
+ //
+ // Guarded by d.mu — deliberately the same lock every register-response
+ // apply takes, which is what totally orders "record the verdict" against
+ // "apply a response" instead of merely narrowing the window between them.
+ demotedProviders map[string]demotionRecord // provider -> the rejected version and when it was rejected
+
+ // demotionSeq is a monotonic counter stamped onto each demotion record so a
+ // probe round can tell whether its evidence predates a verdict.
+ //
+ // Ordering the map writes is not enough on its own: version sampling
+ // happens outside d.mu, so a round that started earlier, sampled an
+ // acceptable version, and returned late could otherwise clear a hold
+ // established by a NEWER below-minimum verdict — and once the hold is gone,
+ // a stale register response walks through every guard above. A round
+ // snapshots this counter before it samples anything and may only clear
+ // holds recorded at or before that snapshot, which makes "my evidence is
+ // newer than that verdict" a fact rather than a hope. Guarded by d.mu.
+ demotionSeq uint64
+
// resolvedPathsMu guards resolvedPaths, the self-healed executable paths.
// The daemon pins each agent's absolute path at startup so a later PATH
// change can't redirect a task launch. When that pinned path later vanishes
@@ -358,12 +415,28 @@ type Daemon struct {
pendingWorkInflight map[string]struct{} // runtime_id -> hint-driven heartbeat in flight
pendingWorkLastRun map[string]time.Time // runtime_id -> when the last hint-driven heartbeat started
- cancelFunc context.CancelFunc // set by Run(); called by triggerRestart
- rootCtx context.Context // set by Run(); used by long-running recoveries that must survive per-runtime ctx cancellation
- restartBinary string // non-empty after a successful update; path to the new binary
- updating atomic.Bool // prevents concurrent update attempts
- activeTasks atomic.Int64 // number of tasks currently in handleTask; exposed via /health
- ready atomic.Bool // false until preflight completes; gates /health status (starting -> running)
+ cancelFunc context.CancelFunc // set by Run(); called by triggerRestart
+ rootCtx context.Context // set by Run(); used by long-running recoveries that must survive per-runtime ctx cancellation
+ // restartMu guards restartBinary. Two goroutines can reach triggerRestart —
+ // the server-triggered handleUpdate and the autoUpdateLoop — and
+ // trySelfReload reads RestartBinary() from the latter to avoid racing the
+ // former into a second handoff.
+ restartMu sync.Mutex
+ restartBinary string // non-empty after a successful update; path to the new binary
+ // brewTargetOnce caches the brew half of restartTargetBinary. The install
+ // method and brew prefix cannot change for the lifetime of the process, and
+ // trySelfReload now calls restartTargetBinary every check tick — without
+ // the cache that is up to two uncached `brew --prefix` forks per tick.
+ brewTargetOnce sync.Once
+ brewInstall bool // resolved once: was this binary installed via brew?
+ brewTarget string // "<prefix>/bin/multica" when brewInstall and the prefix resolved
+ updating atomic.Bool // prevents concurrent update attempts
+ activeTasks atomic.Int64 // number of tasks currently in handleTask; exposed via /health
+ ready atomic.Bool // false until preflight completes; gates /health status (starting -> running)
+ // reloadPendingReason explains why a confirmed multica version change hasn't
+ // restarted the daemon yet (a task was running at the barrier check). Set
+ // and cleared by trySelfReload, read by /health. Diagnostic only.
+ reloadPendingReason atomic.Pointer[string]
// claimMu guards pauseClaims and claimsInFlight. It is held only for the
// microseconds it takes to make a decision; ClaimTask itself runs without
@@ -482,10 +555,31 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
// setAgentVersion records the detected CLI version for an agent provider so
// later task-dispatch code (e.g. Codex sandbox policy) can read it.
+//
+// A blank detection never replaces a version we already know. checkAgentMinVersion
+// returns nil for any provider with no MinVersions entry, so a CLI whose
+// `--version` exits 0 without printing anything parseable reaches here with an
+// empty string — and overwriting the cache with it would strip the input every
+// version-keyed policy reads, on a provider that was working a moment ago.
+// "Couldn't read it" is not a version.
+//
+// This cache is the daemon's LOCAL knowledge only — it is not a record of
+// what the server has been told. Every path that probes writes through here
+// (the converge round, the workspace sync, a self-heal at task launch), while
+// each register call covers only the workspaces it was invoked for. What the
+// server accepted is therefore tracked per workspace, in
+// workspaceState.builtinVersions; refreshAgentVersions compares the two.
func (d *Daemon) setAgentVersion(provider, version string) {
d.versionsMu.Lock()
- defer d.versionsMu.Unlock()
+ prev := d.agentVersions[provider]
+ if version == "" && prev != "" {
+ d.versionsMu.Unlock()
+ d.logger.Warn("agent CLI reported no version; keeping the previous one",
+ "provider", provider, "previous", prev)
+ return
+ }
d.agentVersions[provider] = version
+ d.versionsMu.Unlock()
}
// agentVersion returns the last-detected CLI version for an agent provider,
@@ -496,6 +590,141 @@ func (d *Daemon) agentVersion(provider string) string {
return d.agentVersions[provider]
}
+// builtinVersionsFromPayload extracts provider -> version from a registration
+// payload's BUILT-IN entries. Custom profile entries (profile_id set) are not
+// version-tracked — the drift path owns their lifecycle.
+func builtinVersionsFromPayload(runtimes []map[string]string) map[string]string {
+ out := make(map[string]string, len(runtimes))
+ for _, rt := range runtimes {
+ if rt["profile_id"] != "" {
+ continue
+ }
+ out[rt["type"]] = rt["version"]
+ }
+ return out
+}
+
+// workspaceRegisterLock returns the mutex serializing one workspace's whole
+// registration sequence: send Register, apply or reject the response, then
+// deregister the rows that apply refused or dropped.
+//
+// The per-workspace version record (workspaceState.builtinVersions) must
+// reflect the order the SERVER processed the register calls in, because the
+// server's upsert order decides which payload's versions its rows end up
+// holding. Registration entry points are concurrent (refresh, sync, a
+// runtime_gone recovery, profile drift), and without this lock two calls for
+// the same workspace could complete their HTTP responses in the opposite
+// order from the server's processing — recording the NEWER payload locally
+// while the server kept the OLDER one. The refresh round would then see the
+// record agreeing with disk and never re-register: the mismatch is invisible
+// precisely because the record is wrong, so it persists until the next
+// version change or restart. Holding the lock across the request AND the
+// record makes lock order = server order = record order.
+//
+// The section extends past the send because the cleanup has the same problem in
+// a nastier form. A deregistration is decided under d.mu and issued after
+// releasing it, so a recovery register completing in that gap re-creates the
+// same row — usually under the same runtime ID — and the older Deregister lands
+// on top of it. The daemon then tracks and heartbeats a runtime the server has
+// marked offline, which is the direction that silently strands work: the server
+// will not route to it, and neither side notices the disagreement. A
+// point-in-time tracking re-check cannot close that, because the gap is between
+// the check and the request; only putting the request itself inside the order
+// can. Every apply and every cleanup on a workspace therefore runs under this
+// lock, via withWorkspaceRegisterLock.
+func (d *Daemon) workspaceRegisterLock(workspaceID string) *sync.Mutex {
+ mu, _ := d.registerSerial.LoadOrStore(workspaceID, &sync.Mutex{})
+ return mu.(*sync.Mutex)
+}
+
+// withWorkspaceRegisterLock runs one workspace's registration sequence as a
+// single ordered step. Everything that sends a Register for a workspace, folds
+// the response into local state, or deregisters rows that response cost, must
+// run inside fn — see workspaceRegisterLock for why the boundary sits after the
+// cleanup rather than after the send.
+//
+// The lock is per workspace, so sequences for different workspaces still run
+// concurrently and nothing here is ever held across two of them.
+func (d *Daemon) withWorkspaceRegisterLock(workspaceID string, fn func() error) error {
+ mu := d.workspaceRegisterLock(workspaceID)
+ mu.Lock()
+ defer mu.Unlock()
+ return fn()
+}
+
+// recordBuiltinVersionsSent stores, per provider, the version a SUCCESSFUL
+// register call carried for a workspace (see workspaceState.builtinVersions).
+// Merged per provider rather than replaced: a provider absent from this
+// payload (its probe failed this round) was not re-sent, so the server still
+// holds whatever the previous call carried and the record must keep saying so.
+// Callers invoke this only after client.Register succeeds — a failed call
+// records nothing, which is what keeps the workspace behind for the next
+// refresh round — and while holding the workspace's register lock, so the
+// record's write order matches the server's processing order
+// (workspaceRegisterLock). A workspace not yet tracked records nothing here;
+// the sync path seeds the record when it creates the workspaceState.
+func (d *Daemon) recordBuiltinVersionsSent(workspaceID string, runtimes []map[string]string) {
+ sent := builtinVersionsFromPayload(runtimes)
+ if len(sent) == 0 {
+ return
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ ws, ok := d.workspaces[workspaceID]
+ if !ok {
+ return
+ }
+ if ws.builtinVersions == nil {
+ ws.builtinVersions = make(map[string]string, len(sent))
+ }
+ for provider, version := range sent {
+ // Demoted while this register was in flight: its rows are being
+ // deregistered, so recording what the payload carried would tell the
+ // refresh path the server holds a version for a provider that is on its
+ // way offline — and demoteBelowMinimumRuntimes just deleted that entry.
+ if d.providerDemotedLocked(provider) {
+ continue
+ }
+ ws.builtinVersions[provider] = version
+ }
+}
+
+// refreshHealedVersion keeps a self-healed {path, version} pair honest when the
+// healed binary is later replaced in place.
+//
+// resolveAgentEntry deliberately returns healed.version rather than the shared
+// agentVersions cache whenever a previous self-heal is still live, so that a
+// reader which observes the healed path necessarily observes the version
+// detected for it. Nothing refreshed that pair when the SAME path was
+// subsequently overwritten, so the daemon kept keying version-sensitive policy
+// — the Codex sandbox in runTask — off the version captured at heal time. A
+// re-probe would update agentVersions and the version reported to the server
+// while tasks silently kept running under the old policy.
+//
+// Only touches the entry when the path still matches the one just probed: a
+// heal that has since moved the provider elsewhere owns its own pairing.
+func (d *Daemon) refreshHealedVersion(provider, path, version string) {
+ if version == "" {
+ return
+ }
+ d.resolvedPathsMu.Lock()
+ defer d.resolvedPathsMu.Unlock()
+ healed, ok := d.resolvedPaths[provider]
+ if !ok || healed.path != path || healed.version == version {
+ return
+ }
+ d.resolvedPaths[provider] = healedAgent{path: path, version: version}
+}
+
+// hasDetectedAgentVersions reports whether any CLI version has ever been
+// detected. refreshAgentVersions uses it as the "has anything ever registered"
+// guard.
+func (d *Daemon) hasDetectedAgentVersions() bool {
+ d.versionsMu.RLock()
+ defer d.versionsMu.RUnlock()
+ return len(d.agentVersions) > 0
+}
+
// healedAgent bundles a self-healed executable path with the CLI version
// detected for it. The two are published together under resolvedPathsMu and
// returned together from resolveAgentEntry, so a caller that observes the new
@@ -545,6 +774,32 @@ type healedAgent struct {
// below the minimum supported version -> entry is returned unchanged so the
// candidate is never launched and the downstream error still surfaces.
func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry AgentEntry) (AgentEntry, string) {
+ resolved, version, _ := d.resolveAgentEntryWithHeal(ctx, provider, entry)
+ return resolved, version
+}
+
+// healOutcome is what one self-heal attempt concluded. At most one half is
+// meaningful: adopted names a binary that cleared the same gates registration
+// applies, while rejected carries the typed verdict for a candidate that was
+// found and version-detected but refused for being below the minimum supported
+// version. rejected is nil unless the verdict is genuine — it is only ever set
+// from a *agent.BelowMinimumError, which by construction carries a version
+// that parsed.
+type healOutcome struct {
+ adopted healedAgent
+ rejected *agent.BelowMinimumError
+}
+
+// resolveAgentEntryWithHeal is resolveAgentEntry plus what the self-heal
+// concluded, for the one caller that must act on a refusal rather than just
+// decline to launch it.
+//
+// A refusal is a verdict about disk, not a transient failure: the pinned path
+// is gone AND the binary its command now resolves to is too old. Registration
+// needs to hear that, because otherwise it goes on to probe the vanished path,
+// fails, and reports "version detection failed" — which by design leaves the
+// runtime online, claiming tasks for a CLI that cannot launch.
+func (d *Daemon) resolveAgentEntryWithHeal(ctx context.Context, provider string, entry AgentEntry) (AgentEntry, string, healOutcome) {
// A prior self-heal wins over the original pinned path: it carries a
// {path, version} pair we already verified together, so it can never regress
// to the mismatched pairing a reappearing stale path would produce.
@@ -553,15 +808,15 @@ func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry A
d.resolvedPathsMu.RUnlock()
if ok && agentExecutablePresent(healed.path) {
entry.Path = healed.path
- return entry, healed.version
+ return entry, healed.version, healOutcome{adopted: healed}
}
if agentExecutablePresent(entry.Path) {
- return entry, d.agentVersion(provider)
+ return entry, d.agentVersion(provider), healOutcome{}
}
if entry.Command == "" {
- return entry, d.agentVersion(provider)
+ return entry, d.agentVersion(provider), healOutcome{}
}
// Coalesce concurrent heals for the same provider: the first task through
@@ -571,12 +826,12 @@ func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry A
v, _, _ := d.healGroup.Do(provider, func() (any, error) {
return d.healAgentPath(ctx, provider, command), nil
})
- healed, _ = v.(healedAgent)
- if healed.path == "" {
- return entry, d.agentVersion(provider)
+ outcome, _ := v.(healOutcome)
+ if outcome.adopted.path == "" {
+ return entry, d.agentVersion(provider), outcome
}
- entry.Path = healed.path
- return entry, healed.version
+ entry.Path = outcome.adopted.path
+ return entry, outcome.adopted.version, outcome
}
// healAgentPath re-resolves command for provider and, if a usable binary is
@@ -585,10 +840,14 @@ func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry A
// registration enforces. Path and version are published together under
// resolvedPathsMu so any observer of the path also sees the matching version;
// the shared d.agentVersion cache is refreshed too, for registration hygiene.
-// It returns a zero healedAgent when nothing usable was found, so the caller
+// It returns a zero adopted pair when nothing usable was found, so the caller
// keeps the (stale) pinned entry and the candidate is never launched. Runs
// under healGroup, one invocation at a time per provider.
-func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) healedAgent {
+//
+// A candidate refused by the minimum-version gate is reported back rather than
+// swallowed: not launching it is right, but it is also the whole verdict a
+// registration round needs to take the provider's runtimes offline.
+func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) healOutcome {
// Re-check the cache: a predecessor under the same singleflight key may have
// already populated it, or a prior heal completed between the read above and
// entering here.
@@ -596,12 +855,12 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) he
cached, ok := d.resolvedPaths[provider]
d.resolvedPathsMu.RUnlock()
if ok && agentExecutablePresent(cached.path) {
- return cached
+ return healOutcome{adopted: cached}
}
newPath, found := reresolveAgentCommand(command)
if !found {
- return healedAgent{}
+ return healOutcome{}
}
// Verify before adopting. An in-place "upgrade" that actually repoints at an
@@ -612,12 +871,22 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) he
if err != nil {
d.logger.Warn("re-resolved agent executable failed version detection; keeping pinned path",
"provider", provider, "command", command, "new_path", newPath, "error", err)
- return healedAgent{}
+ return healOutcome{}
}
if err := checkAgentMinVersion(provider, version); err != nil {
+ var tooOld *agent.BelowMinimumError
+ if !errors.As(err, &tooOld) {
+ // Read something, understood nothing: not a verdict. Refusing to
+ // adopt is still right, but reporting a rejection would let the
+ // caller demote a runtime on an unreadable version — the exact
+ // transient case the below-minimum machinery must never act on.
+ d.logger.Warn("re-resolved agent executable version could not be validated; keeping pinned path",
+ "provider", provider, "command", command, "new_path", newPath, "version", version, "error", err)
+ return healOutcome{}
+ }
d.logger.Warn("re-resolved agent executable is below the minimum supported version; not adopting it",
"provider", provider, "command", command, "new_path", newPath, "version", version, "error", err)
- return healedAgent{}
+ return healOutcome{rejected: tooOld}
}
adopted := healedAgent{path: newPath, version: version}
@@ -637,7 +906,7 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) he
d.logger.Info("re-resolved agent executable after pinned path vanished (in-place upgrade)",
"provider", provider, "command", command, "new_path", newPath, "version", version)
- return adopted
+ return healOutcome{adopted: adopted}
}
func (d *Daemon) notifyRuntimeSetChanged() {
@@ -882,10 +1151,13 @@ func (d *Daemon) workspaceNeedsRuntimeRecovery(workspaceID string) bool {
// the order they were returned. These are the daemon's authoritative
// current runtime set after the call.
// - droppedIDs: runtime IDs that were tracked before this call but did
-// NOT survive the response. Drift callers Deregister these so the
-// server marks them offline immediately instead of waiting on the 150 s
-// stale-heartbeat sweep; the runtime_gone path can ignore them because
-// those rows were already deleted server-side.
+// NOT survive the response. Callers Deregister these so the server marks
+// them offline immediately instead of waiting on the 150 s
+// stale-heartbeat sweep. On the runtime_gone path the triggering row was
+// already deleted server-side (and pruned locally before the register),
+// but a SIBLING dropped here — e.g. a provider removed from the daemon's
+// config, or a disabled profile — still has a live server row that must be
+// deregistered.
// - ok: false when the workspace was forgotten between the
// register call and this apply (e.g. the user left the workspace and
// syncWorkspacesFromAPI removed it). The caller must abort silently in
@@ -894,38 +1166,82 @@ func (d *Daemon) workspaceNeedsRuntimeRecovery(workspaceID string) bool {
// profileSig is the digest captured during the register; an empty value is
// the explicit "fetch failed, keep the previous signature" sentinel from
// appendProfileRuntimes.
-func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *RegisterResponse, profileSig string) (newIDs, droppedIDs []string, ok bool) {
- newIDs = make([]string, 0, len(resp.Runtimes))
- newIDSet := make(map[string]struct{}, len(resp.Runtimes))
- for _, rt := range resp.Runtimes {
- newIDs = append(newIDs, rt.ID)
- newIDSet[rt.ID] = struct{}{}
- }
-
+//
+// preserveProviders lists the built-in providers this response is not
+// authoritative about, keyed by provider — see preserveProvidersFromProbe. Their
+// entries are absent from the payload, and therefore from the response, either
+// because the probe failed (transient) or because they were confirmed
+// below-minimum by a path with no authority to demote. Either way, dropping
+// their rows here would take a runtime offline outside the one path that does it
+// safely, so their existing built-in runtime rows are kept instead.
+//
+// A provider already under a demotion hold is a different case and is still
+// rejected below: that verdict was reached by demoteBelowMinimumRuntimes, which
+// removed the rows under the claim barrier, and this response merely predates
+// it.
+func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *RegisterResponse, profileSig string, preserveProviders map[string]string) (newIDs, droppedIDs []string, ok bool) {
d.mu.Lock()
defer d.mu.Unlock()
ws, exists := d.workspaces[workspaceID]
if !exists {
return nil, nil, false
}
+ // Reject entries for providers demoted since this register was sent. The
+ // payload predates the verdict, so the response carries the provider as if
+ // it were healthy; indexing it here would undo demoteBelowMinimumRuntimes.
+ // Both sides do this under d.mu, which gives the two a total order: either
+ // the demotion runs first and this rejects the late response, or the apply
+ // runs first and the demotion removes the row it just added. Either way the
+ // provider ends up offline. Rejected IDs join droppedIDs so the caller
+ // deregisters the row the server upserted back into existence.
+ newIDs = make([]string, 0, len(resp.Runtimes))
+ newIDSet := make(map[string]struct{}, len(resp.Runtimes))
+ rejected := make(map[string]struct{})
+ for _, rt := range resp.Runtimes {
+ if rt.ProfileID == "" && d.providerDemotedLocked(rt.Provider) {
+ rejected[rt.ID] = struct{}{}
+ droppedIDs = append(droppedIDs, rt.ID)
+ continue
+ }
+ newIDs = append(newIDs, rt.ID)
+ newIDSet[rt.ID] = struct{}{}
+ }
// Drop runtimeIndex entries for prior runtime IDs that the server did not
// return — typically there are none for upsert-on-existing-provider, but
// a daemon config change (provider removed) or a profile disable would
// leak entries otherwise.
+ kept := newIDs
for _, oldID := range ws.runtimeIDs {
- if _, kept := newIDSet[oldID]; !kept {
+ if _, stillThere := newIDSet[oldID]; stillThere {
+ continue
+ }
+ if _, alreadyRejected := rejected[oldID]; alreadyRejected {
+ // The server returned this ID for a demoted provider and it is
+ // already in droppedIDs; drop the index entry without recording it
+ // a second time.
delete(d.runtimeIndex, oldID)
- droppedIDs = append(droppedIDs, oldID)
+ continue
+ }
+ if rt, tracked := d.runtimeIndex[oldID]; tracked && rt.ProfileID == "" {
+ if _, preserve := preserveProviders[rt.Provider]; preserve {
+ kept = append(kept, oldID)
+ continue
+ }
}
+ delete(d.runtimeIndex, oldID)
+ droppedIDs = append(droppedIDs, oldID)
}
for _, rt := range resp.Runtimes {
+ if _, skip := rejected[rt.ID]; skip {
+ continue
+ }
d.runtimeIndex[rt.ID] = rt
}
// Response is authoritative — replace, do not append. Replacing also
// catches the rare case where UpsertAgentRuntime returns a different ID
// for a surviving provider (e.g. schema change); the daemon converges on
// what the server says without leaving stale heartbeat goroutines.
- ws.runtimeIDs = newIDs
+ ws.runtimeIDs = kept
if resp.ReposVersion != "" {
ws.reposVersion = resp.ReposVersion
ws.allowedRepoURLs = repoAllowlist(resp.Repos)
@@ -969,12 +1285,12 @@ func (d *Daemon) applyRegisterResponseInPlace(workspaceID string, resp *Register
// ID rotation is still handled: when the response returns a different ID for a
// built-in provider the workspace already had, that specific old ID is replaced
// rather than accumulating a duplicate heartbeat.
-func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *RegisterResponse) (newIDs []string, ok bool) {
+func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *RegisterResponse) (newIDs, rejectedIDs []string, ok bool) {
d.mu.Lock()
defer d.mu.Unlock()
ws, exists := d.workspaces[workspaceID]
if !exists {
- return nil, false
+ return nil, nil, false
}
// Index the workspace's current built-in runtimes by provider so a rotated
@@ -995,6 +1311,15 @@ func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *Register
// Not ours to manage; the drift path owns custom profiles.
continue
}
+ // Demoted since this register was sent: the response predates the
+ // verdict, so bringing the provider back here would undo the demotion.
+ // Both run under d.mu, so the two are totally ordered — see the same
+ // guard in applyRegisterResponseInPlace. The caller deregisters the row
+ // the server upserted back.
+ if d.providerDemotedLocked(rt.Provider) {
+ rejectedIDs = append(rejectedIDs, rt.ID)
+ continue
+ }
d.runtimeIndex[rt.ID] = rt
if _, already := present[rt.ID]; already {
continue
@@ -1025,23 +1350,147 @@ func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *Register
if len(resp.Settings) > 0 {
ws.settings = resp.Settings
}
- return newIDs, true
+ return newIDs, rejectedIDs, true
}
-func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspaceID string) error {
- resp, profileSig, err := d.registerRuntimesForWorkspace(ctx, workspaceID)
- if err != nil {
- return fmt.Errorf("register runtimes: %w", err)
+// providerDemotedLocked reports whether provider is currently held below the
+// minimum supported version. Callers must hold d.mu — the demotion record and
+// every register-response apply share that lock precisely so a late response
+// can never slip between the two.
+func (d *Daemon) providerDemotedLocked(provider string) bool {
+ _, demoted := d.demotedProviders[provider]
+ return demoted
+}
+
+// demotionRecord is a confirmed below-minimum verdict: the version that was
+// rejected, plus the demotionSeq tick that establishes when it was reached.
+type demotionRecord struct {
+ version string
+ seq uint64
+}
+
+// markProvidersDemoted records a CONFIRMED below-minimum verdict so a register
+// response still in flight cannot revive the provider. Callers must hold d.mu.
+func (d *Daemon) markProvidersDemotedLocked(providers map[string]string) {
+ if len(providers) == 0 {
+ return
}
+ if d.demotedProviders == nil {
+ d.demotedProviders = make(map[string]demotionRecord, len(providers))
+ }
+ // One tick per verdict batch: every record written here is newer than any
+ // probe round that snapshotted the counter before this call.
+ d.demotionSeq++
+ for provider, version := range providers {
+ d.demotedProviders[provider] = demotionRecord{version: version, seq: d.demotionSeq}
+ }
+}
- newIDs, _, ok := d.applyRegisterResponseInPlace(workspaceID, resp, profileSig)
- if !ok {
- return fmt.Errorf("workspace %s no longer tracked", workspaceID)
+// demotionSeqSnapshot returns the current demotion counter. A probe round takes
+// this BEFORE it samples any version, so a later clearProviderDemotions call can
+// prove its evidence postdates a verdict rather than merely arriving after it.
+func (d *Daemon) demotionSeqSnapshot() uint64 {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.demotionSeq
+}
+
+// clearProviderDemotions drops the verdict for providers whose version probed
+// acceptable again, which is what lets converge register them back.
+//
+// sampledAfter is the counter the calling round snapshotted before it probed. A
+// hold recorded after that snapshot is NEWER evidence than anything this round
+// saw, so it survives: four callers probe concurrently and sampling happens off
+// the lock, which means "returned last" says nothing about "looked last". The
+// round that overlapped a demotion simply declines to clear it and the next one
+// — which starts after the verdict exists, so its sample cannot predate it —
+// does the release. Recovery is at worst one round late; clearing on stale
+// evidence would let a stale register response through every other guard.
+func (d *Daemon) clearProviderDemotions(providers []string, sampledAfter uint64) {
+ if len(providers) == 0 {
+ return
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if len(d.demotedProviders) == 0 {
+ return
}
+ for _, provider := range providers {
+ record, was := d.demotedProviders[provider]
+ if !was {
+ continue
+ }
+ if record.seq > sampledAfter {
+ d.logger.Info("keeping below-minimum hold: this probe round started before the verdict",
+ "provider", provider, "rejected_version", record.version)
+ continue
+ }
+ delete(d.demotedProviders, provider)
+ d.logger.Info("agent CLI is back at or above the minimum supported version",
+ "provider", provider, "rejected_version", record.version)
+ }
+}
- for _, rid := range newIDs {
- d.logger.Info("re-registered runtime after server-side deletion",
- "workspace_id", workspaceID, "runtime_id", rid)
+// untrackedRuntimeIDs filters ids down to those the daemon does not currently
+// track, so a deregistration decided a moment ago cannot take a row offline that
+// a NEWER legitimate registration has since brought back.
+//
+// Every deregistration is decided under d.mu and issued after releasing it —
+// the HTTP call must not hold the daemon lock. A recovery register completing in
+// that gap re-creates the same server-side row, usually under the same runtime
+// ID, and the older cleanup would then knock out the row that just recovered.
+//
+// This filter is only half the guarantee, and on its own it is a TOCTOU: the
+// recovery can just as easily complete between the filter and the request.
+// Callers must therefore run both inside the workspace's register lock, which is
+// what makes the check and the Deregister one ordered step against every other
+// registration for that workspace.
+func (d *Daemon) untrackedRuntimeIDs(ids []string) []string {
+ if len(ids) == 0 {
+ return nil
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ out := make([]string, 0, len(ids))
+ for _, id := range ids {
+ if _, tracked := d.runtimeIndex[id]; tracked {
+ continue
+ }
+ out = append(out, id)
+ }
+ return out
+}
+
+func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, workspaceID string) error {
+ var newIDs []string
+ // Send, apply and clean up as one ordered step — see workspaceRegisterLock.
+ err := d.withWorkspaceRegisterLock(workspaceID, func() error {
+ resp, profileSig, preserve, err := d.registerRuntimesForWorkspaceLocked(ctx, workspaceID)
+ if err != nil {
+ return fmt.Errorf("register runtimes: %w", err)
+ }
+
+ ids, droppedIDs, ok := d.applyRegisterResponseInPlace(workspaceID, resp, profileSig, preserve)
+ if !ok {
+ return fmt.Errorf("workspace %s no longer tracked", workspaceID)
+ }
+ newIDs = ids
+
+ for _, rid := range newIDs {
+ d.logger.Info("re-registered runtime after server-side deletion",
+ "workspace_id", workspaceID, "runtime_id", rid)
+ }
+
+ // A sibling runtime dropped by this recovery (a provider removed from the
+ // daemon's config, a disabled profile) still has a live server row — the
+ // runtime_gone trigger only deleted its own. Eagerly mark those offline,
+ // matching the drift path, instead of leaving them claimable until the
+ // stale-heartbeat sweep.
+ d.deregisterDroppedRuntimes(ctx, workspaceID, droppedIDs, "runtime_gone recovery")
+ return nil
+ })
+ if err != nil {
+ return err
}
d.notifyRuntimeSetChanged()
@@ -1258,6 +1707,8 @@ func (d *Daemon) Run(ctx context.Context) error {
// RestartBinary returns the path to the new binary if the daemon needs to restart
// after a successful update, or empty string if no restart is needed.
func (d *Daemon) RestartBinary() string {
+ d.restartMu.Lock()
+ defer d.restartMu.Unlock()
return d.restartBinary
}
@@ -1403,25 +1854,46 @@ var runtimeVersionProbeRetryDelay = 500 * time.Millisecond
// re-resolved candidate, so an attempt can spend its entire budget there and
// still fail instantly on the outer probe of the stale path.
//
-// One deterministic failure does slip through and get retried: a self-heal
-// candidate rejected by the minimum-version gate, whose stale path then fails
-// fast. It is not worth plumbing a reason out of resolveAgentEntry to catch —
-// the retry is bounded, and every probe in it fails fast by construction.
+// A self-heal candidate rejected by the minimum-version gate is also retried
+// within this window, deliberately: the rejection is a verdict about whatever
+// PATH resolved to during the upgrade window the heal exists for, and the
+// retry gives the upgrade a beat to publish the new binary before the verdict
+// demotes runtimes (see probeBuiltinRuntime).
//
// Overridable for tests.
var runtimeVersionProbeRetryWindow = time.Second
+// builtinProbeVerdict distinguishes the two ways a provider can fail its probe,
+// which callers must treat differently.
+//
+// "Could not read a version" is transient by construction — the CLI was busy,
+// mid-upgrade, or fork/exec hiccuped — so the right response is to leave
+// whatever is registered alone and try again. "Read a version and it is below
+// the minimum supported one" is a confirmed verdict about a binary that is on
+// disk right now, and leaving it registered means the daemon keeps handing it
+// work it cannot run correctly. Collapsing both into one bool made the second
+// case indistinguishable from a hiccup, which is what let a downgraded CLI keep
+// claiming tasks.
+type builtinProbeVerdict int
+
+const (
+ builtinProbeOK builtinProbeVerdict = iota
+ builtinProbeUnavailable
+ builtinProbeBelowMinimum
+)
+
// probeBuiltinRuntime resolves and version-detects one built-in provider,
-// retrying a fast failure up to runtimeVersionProbeAttempts times. It returns
-// false when the provider must be dropped from this round's registration
-// payload: its version could not be detected, or it is below the minimum
-// supported version.
+// retrying a fast failure up to runtimeVersionProbeAttempts times. The verdict
+// tells the caller how to treat a drop: builtinProbeUnavailable means the
+// version could not be read (or not understood) — transient, leave whatever is
+// registered alone — while builtinProbeBelowMinimum is a confirmed too-old
+// verdict the caller may demote on. See builtinProbeVerdict.
//
-// The second return value is a short human-readable reason when ok is false.
-// It is surfaced on /health as skipped_agents so a user can tell "CLI not
-// installed" apart from "CLI installed but dropped at registration", which was
-// previously only visible in the daemon log (MUL-5439).
-func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry AgentEntry) (string, string, bool) {
+// The second return value is a short human-readable reason when the verdict is
+// not OK. It is surfaced on /health as skipped_agents so a user can tell "CLI
+// not installed" apart from "CLI installed but dropped at registration", which
+// was previously only visible in the daemon log (MUL-5439).
+func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry AgentEntry) (string, string, builtinProbeVerdict) {
var (
lastErr error
attempts int
@@ -1455,7 +1927,28 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
// It is re-run per attempt because the heal itself can be what a retry
// fixes: the upgrade that removed the old path may not have published
// the new one yet on the first attempt.
- resolved, _ := d.resolveAgentEntry(ctx, name, entry)
+ resolved, _, heal := d.resolveAgentEntryWithHeal(ctx, name, entry)
+ // The pinned path is gone and the binary its command resolves to now is
+ // too old. Unlike the direct case below, this verdict is about whatever
+ // PATH resolves to at this instant — and the pinned path vanishing is
+ // exactly the mid-upgrade window the per-attempt heal exists for, where
+ // a stale sibling install can shadow the not-yet-published new binary.
+ // Give it the same bounded fast-failure retry as every other outcome
+ // before returning the demotable verdict; a retry that finds the
+ // upgraded binary adopts it instead. It is still the only way this
+ // shape reaches the caller: probing the vanished path can only produce
+ // "version detection failed", which by design leaves the runtime online
+ // and claiming tasks for a CLI that cannot launch.
+ if heal.rejected != nil {
+ if attempts < runtimeVersionProbeAttempts && time.Since(startedAt) < runtimeVersionProbeRetryWindow {
+ d.logger.Debug("re-resolved agent version too old; retrying probe",
+ "name", name, "attempt", attempts, "version", heal.rejected.Detected)
+ continue
+ }
+ d.logger.Warn("skip registering runtime: re-resolved version too old",
+ "name", name, "version", heal.rejected.Detected, "error", heal.rejected.Error())
+ return heal.rejected.Detected, heal.rejected.Error(), builtinProbeBelowMinimum
+ }
version, err := detectAgentVersion(ctx, resolved.Path)
if err != nil {
lastErr = err
@@ -1467,22 +1960,51 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
}
continue
}
- // The min-version verdict is a pure function of the detected version,
- // so a retry would reach the same conclusion — drop the provider now.
if err := checkAgentMinVersion(name, version); err != nil {
- d.logger.Warn("skip registering runtime: version too old", "name", name, "version", version, "error", err)
- return "", err.Error(), false
+ var tooOld *agent.BelowMinimumError
+ if errors.As(err, &tooOld) {
+ // The verdict is a pure function of a version that PARSED, so a
+ // retry would reach the same conclusion — drop the provider now.
+ d.logger.Warn("skip registering runtime: version too old", "name", name, "version", version, "error", err)
+ // The version is returned even though the provider is dropped: the
+ // caller needs it to report what it demoted.
+ return version, err.Error(), builtinProbeBelowMinimum
+ }
+ // The CLI ran but printed something (or nothing) the gate could not
+ // parse. That is "we didn't learn a version", not "we verified it is
+ // too old" — the same transient rule as a failed exec, because the
+ // below-minimum verdict tears runtimes down and must never fire on
+ // evidence this thin.
+ lastErr = err
+ if time.Since(startedAt) >= runtimeVersionProbeRetryWindow {
+ break
+ }
+ if attempts < runtimeVersionProbeAttempts {
+ d.logger.Debug("agent version unparseable; retrying", "name", name, "attempt", attempts, "error", err)
+ }
+ continue
}
d.setAgentVersion(name, version)
+ d.refreshHealedVersion(name, resolved.Path, version)
+ if version == "" {
+ // A provider with no minimum-version floor reaches here with a blank
+ // when its `--version` exits 0 printing nothing. setAgentVersion just
+ // refused to let it overwrite the cache; the payload needs the same
+ // protection, because a whole-set re-registration triggered by a
+ // NEIGHBOUR's upgrade would otherwise send the blank and wipe a
+ // version the server already knows. Reuse the last known one; a
+ // provider that never had a version stays blank, as before.
+ version = d.agentVersion(name)
+ }
d.logger.Debug("agent version detected", "name", name, "version", version, "path", resolved.Path)
- return version, "", true
+ return version, "", builtinProbeOK
}
d.logger.Warn("skip registering runtime", "name", name, "attempts", attempts, "error", lastErr)
reason := "version detection failed"
if lastErr != nil {
reason = fmt.Sprintf("version detection failed: %v", lastErr)
}
- return "", reason, false
+ return "", reason, builtinProbeUnavailable
}
// detectBuiltinRuntimes version-detects every configured built-in agent CLI and
@@ -1509,25 +2031,54 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
// The result describes the machine, not a workspace, so a caller registering a
// batch of workspaces at once calls this ONCE and passes the payload to
// registerRuntimesForWorkspaceBatch for each workspace (MUL-5225).
-func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) []map[string]string {
+//
+// The second return value is THIS round's below-minimum verdicts, provider to
+// the version that was read and rejected. It is returned rather than read back
+// out of skippedAgents because that pair is a diagnostic snapshot of whichever
+// round published last: four different goroutines call this (the discovery
+// loop, the workspace sync, a runtime_gone re-register, a profile drift
+// refresh), so a caller acting on the shared copy can act on someone else's
+// probe — and demoting a runtime is not a decision to make on another round's
+// evidence.
+//
+// The third return value is THIS round's unavailable providers (version could
+// not be read), provider to reason. Callers that treat a register response as
+// AUTHORITATIVE for a workspace's whole runtime set (the runtime_gone recovery
+// and the profile drift refresh, via applyRegisterResponseInPlace) must
+// preserve these providers' existing runtimes: they are absent from the
+// payload because the probe failed, which is transient — tearing a working
+// runtime down over it is exactly what the unavailable/below-minimum verdict
+// split exists to prevent. Only a below-minimum verdict may demote.
+func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string, map[string]string, map[string]string) {
type detected struct {
name string
version string
}
+ // Snapshot before any probe runs: everything sampled below is at least as
+ // new as every verdict recorded up to this point, which is exactly the
+ // claim clearProviderDemotions needs and cannot make from timing alone.
+ sampledAfter := d.demotionSeqSnapshot()
var (
- mu sync.Mutex
- results []detected
- skipped = map[string]string{}
- g errgroup.Group
+ mu sync.Mutex
+ results []detected
+ skipped = map[string]string{}
+ belowMin = map[string]string{}
+ unavailable = map[string]string{}
+ g errgroup.Group
)
g.SetLimit(runtimeVersionProbeConcurrency)
for name, entry := range d.agents() {
name, entry := name, entry
g.Go(func() error {
- version, reason, ok := d.probeBuiltinRuntime(ctx, name, entry)
- if !ok {
+ version, reason, verdict := d.probeBuiltinRuntime(ctx, name, entry)
+ if verdict != builtinProbeOK {
mu.Lock()
skipped[name] = reason
+ if verdict == builtinProbeBelowMinimum {
+ belowMin[name] = version
+ } else {
+ unavailable[name] = reason
+ }
mu.Unlock()
return nil
}
@@ -1551,6 +2102,18 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) []map[string]string
// across runs and order-sensitive tests stay deterministic.
sort.Slice(results, func(i, j int) bool { return results[i].name < results[j].name })
+ // A provider that probes OK is no longer below the minimum, so release any
+ // demotion held against it — otherwise the register that converge is about
+ // to make would be rejected by the very guard that protects the demotion.
+ // Only holds that already existed when this round started sampling are
+ // released; see clearProviderDemotions for why "returned last" is not the
+ // same as "sampled last".
+ recovered := make([]string, 0, len(results))
+ for _, r := range results {
+ recovered = append(recovered, r.name)
+ }
+ d.clearProviderDemotions(recovered, sampledAfter)
+
runtimes := make([]map[string]string, 0, len(results))
for _, r := range results {
displayName := providerDisplayName(r.name)
@@ -1564,7 +2127,7 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) []map[string]string
"status": "online",
})
}
- return runtimes
+ return runtimes, belowMin, unavailable
}
// cloneRuntimeEntries deep-copies a registration runtime payload. Callers that
@@ -1592,8 +2155,53 @@ func cloneRuntimeEntries(in []map[string]string) []map[string]string {
// Registering a batch of workspaces at once (daemon startup) goes through
// registerRuntimesForWorkspaceBatch instead, which shares one probe round
// across the batch.
-func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID string) (*RegisterResponse, string, error) {
- return d.registerRuntimesForWorkspaceBatch(ctx, workspaceID, d.detectBuiltinRuntimes(ctx))
+//
+// The third return value is the set of providers this round's response must not
+// be treated as authoritative about, provider to reason — see
+// preserveProvidersFromProbe. Callers that apply the response as AUTHORITATIVE
+// must pass it to applyRegisterResponseInPlace.
+//
+// The caller must hold the workspace's register lock (withWorkspaceRegisterLock)
+// for this call, the apply, and the cleanup that follows it.
+func (d *Daemon) registerRuntimesForWorkspaceLocked(ctx context.Context, workspaceID string) (*RegisterResponse, string, map[string]string, error) {
+ builtins, belowMinimum, unavailable := d.detectBuiltinRuntimes(ctx)
+ resp, profileSig, err := d.registerRuntimesForWorkspaceBatchLocked(ctx, workspaceID, builtins)
+ return resp, profileSig, preserveProvidersFromProbe(unavailable, belowMinimum), err
+}
+
+// preserveProvidersFromProbe returns the providers whose absence from a
+// registration payload must NOT be read as "this workspace should stop hosting
+// them", keyed by provider.
+//
+// Unavailable is the obvious half: the version could not be read, which is
+// transient, so dropping the rows would tear a working runtime down over one
+// failed probe.
+//
+// Below-minimum is the half that is easy to get wrong, because the verdict IS
+// confirmed — a version was read and rejected. What is missing on these paths is
+// not the evidence but the authority to act on it. Taking a runtime offline for
+// being too old requires two things neither the runtime_gone recovery nor the
+// profile-drift refresh has: the claim barrier, so the rows are never pulled out
+// from under a task that is still executing, and a seq-stamped hold, so a
+// register sent before the verdict cannot revive the provider when it lands.
+// demoteBelowMinimumRuntimes has both and is the single owner of the demotion.
+// A path that drops the rows without them reaches the same verdict and leaves no
+// record that it did, so the next in-flight response quietly undoes it.
+//
+// Preserving here costs at most one refresh tick of a too-old CLI staying
+// online, which is the pre-demotion status quo rather than a new exposure.
+func preserveProvidersFromProbe(unavailable, belowMinimum map[string]string) map[string]string {
+ if len(belowMinimum) == 0 {
+ return unavailable
+ }
+ preserve := make(map[string]string, len(unavailable)+len(belowMinimum))
+ for provider, reason := range unavailable {
+ preserve[provider] = reason
+ }
+ for provider, version := range belowMinimum {
+ preserve[provider] = "below minimum supported version: " + version
+ }
+ return preserve
}
// registerRuntimesForWorkspaceBatch registers one workspace against an already
@@ -1612,7 +2220,10 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s
//
// builtins is treated as read-only and is copied before this workspace's custom
// runtime profiles are appended.
-func (d *Daemon) registerRuntimesForWorkspaceBatch(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, string, error) {
+//
+// The caller must hold the workspace's register lock (withWorkspaceRegisterLock)
+// for this call, the apply, and the cleanup that follows it.
+func (d *Daemon) registerRuntimesForWorkspaceBatchLocked(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, string, error) {
d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.agents()))
runtimes := cloneRuntimeEntries(builtins)
var failedProfiles []map[string]string
@@ -1658,6 +2269,7 @@ func (d *Daemon) registerRuntimesForWorkspaceBatch(ctx context.Context, workspac
return nil, "", fmt.Errorf("register runtimes: empty response")
}
d.logger.Debug("register response", "workspace_id", workspaceID, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos), "repos_version", resp.ReposVersion)
+ d.recordBuiltinVersionsSent(workspaceID, runtimes)
return resp, profileSig, nil
}
@@ -1675,7 +2287,10 @@ func (d *Daemon) registerRuntimesForWorkspaceBatch(ctx context.Context, workspac
// the existing drift path.
//
// builtins is treated as read-only.
-func (d *Daemon) registerBuiltinRuntimesForWorkspace(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, error) {
+//
+// The caller must hold the workspace's register lock (withWorkspaceRegisterLock)
+// for this call, the merge, and the cleanup that follows it.
+func (d *Daemon) registerBuiltinRuntimesForWorkspaceLocked(ctx context.Context, workspaceID string, builtins []map[string]string) (*RegisterResponse, error) {
runtimes := cloneRuntimeEntries(builtins)
if len(runtimes) == 0 {
return nil, ErrNoRuntimesToRegister
@@ -1700,6 +2315,7 @@ func (d *Daemon) registerBuiltinRuntimesForWorkspace(ctx context.Context, worksp
return nil, fmt.Errorf("register builtin runtimes: empty response")
}
d.logger.Debug("builtin register response", "workspace_id", workspaceID, "runtimes", len(resp.Runtimes))
+ d.recordBuiltinVersionsSent(workspaceID, runtimes)
return resp, nil
}
@@ -2209,7 +2825,16 @@ func (d *Daemon) refreshWorkspaceRuntimeProfiles(ctx context.Context, workspaceI
"workspace_id", workspaceID, "previous_sig", cached, "current_sig", live,
"profile_count", len(profiles))
- regResp, profileSig, err := d.registerRuntimesForWorkspace(ctx, workspaceID)
+ // Send, apply and clean up as one ordered step — see workspaceRegisterLock.
+ return d.withWorkspaceRegisterLock(workspaceID, func() error {
+ return d.applyProfileDriftRegistration(ctx, workspaceID)
+ })
+}
+
+// applyProfileDriftRegistration is refreshWorkspaceRuntimeProfiles' registration
+// half. The caller must hold the workspace's register lock.
+func (d *Daemon) applyProfileDriftRegistration(ctx context.Context, workspaceID string) error {
+ regResp, profileSig, preserve, err := d.registerRuntimesForWorkspaceLocked(ctx, workspaceID)
if err != nil {
if errors.Is(err, ErrNoRuntimesToRegister) {
// Convergence-to-zero: a custom-only daemon's only enabled
@@ -2218,12 +2843,23 @@ func (d *Daemon) refreshWorkspaceRuntimeProfiles(ctx context.Context, workspaceI
// proactively Deregister the orphaned server-side rows so the
// runtime list converges to empty without waiting on the 150 s
// stale-heartbeat sweep.
- return d.convergeWorkspaceRuntimesToZero(ctx, workspaceID, profileSig)
+ //
+ // An empty payload only proves "nothing to host" for the providers
+ // whose probe actually concluded, and only for the verdicts this path
+ // is allowed to act on. A provider dropped as UNAVAILABLE or confirmed
+ // below-minimum is absent for a reason this path must not treat as
+ // authoritative (see preserveProvidersFromProbe), so its existing
+ // built-in rows are preserved — the same rule
+ // applyRegisterResponseInPlace applies — while the profile runtimes
+ // the drift is actually about still converge. Skipping the whole
+ // convergence instead would let one permanently unprobeable CLI
+ // keep a disabled profile's runtime online forever.
+ return d.convergeWorkspaceRuntimesToZero(ctx, workspaceID, profileSig, preserve)
}
return err
}
- newIDs, droppedIDs, ok := d.applyRegisterResponseInPlace(workspaceID, regResp, profileSig)
+ newIDs, droppedIDs, ok := d.applyRegisterResponseInPlace(workspaceID, regResp, profileSig, preserve)
if !ok {
return fmt.Errorf("workspace %s no longer tracked", workspaceID)
}
@@ -2239,60 +2875,71 @@ func (d *Daemon) refreshWorkspaceRuntimeProfiles(ctx context.Context, workspaceI
// so the runtime list reflects reality immediately; a 5xx blip here is
// fine because the server's stale-heartbeat sweep will pick them up
// within ~150 s as a backstop.
- if len(droppedIDs) > 0 {
- if err := d.client.Deregister(ctx, droppedIDs); err != nil {
- d.logger.Warn("deregister of dropped runtimes after profile drift failed",
- "workspace_id", workspaceID, "runtime_ids", droppedIDs, "error", err)
- }
- }
+ d.deregisterDroppedRuntimes(ctx, workspaceID, droppedIDs, "profile drift")
// Intentionally NO RecoverOrphans here: see method doc.
return nil
}
// convergeWorkspaceRuntimesToZero handles the drift-refresh case where
-// registerRuntimesForWorkspace would have short-circuited because the daemon
-// has nothing to host on this workspace anymore. It Deregisters the
+// registerRuntimesForWorkspaceLocked would have short-circuited because the
+// daemon has nothing to host on this workspace anymore. It Deregisters the
// previously-tracked runtime IDs (best-effort) and clears the daemon's local
// tracking so taskWakeup / heartbeat / poll loops stop attempting work
// against runtimes that should now be offline.
//
+// The caller must hold the workspace's register lock — this is a cleanup, and it
+// has the same ordering requirement as every other one (workspaceRegisterLock).
+//
+// preserveProviders lists the built-in providers this round's absence from the
+// payload says nothing authoritative about (see preserveProvidersFromProbe), so
+// their existing built-in rows survive — the same preserve rule
+// applyRegisterResponseInPlace applies. Everything else (the disabled/deleted
+// profiles' runtimes, and any builtin whose probe concluded) converges away.
+//
// The workspaceState pointer is preserved: the workspace itself is still a
// valid workspace the user belongs to, just one with no agents on this
// daemon for the moment. If the user re-enables a profile or installs a
// built-in agent, the profile-change notification or the next daemon WS
// reconnect will register it again.
-func (d *Daemon) convergeWorkspaceRuntimesToZero(ctx context.Context, workspaceID, profileSig string) error {
+func (d *Daemon) convergeWorkspaceRuntimesToZero(ctx context.Context, workspaceID, profileSig string, preserveProviders map[string]string) error {
d.mu.Lock()
ws, ok := d.workspaces[workspaceID]
if !ok {
d.mu.Unlock()
return nil
}
- oldRuntimeIDs := append([]string(nil), ws.runtimeIDs...)
- for _, rid := range oldRuntimeIDs {
+ // A fresh array, not ws.runtimeIDs[:0]: the health handler copies this
+ // slice header under d.mu and serializes it after releasing the lock
+ // (removeStaleRuntime keeps the same rule).
+ kept := ws.runtimeIDs[:0:0]
+ var dropped []string
+ for _, rid := range ws.runtimeIDs {
+ if rt, tracked := d.runtimeIndex[rid]; tracked && rt.ProfileID == "" {
+ if _, preserve := preserveProviders[rt.Provider]; preserve {
+ kept = append(kept, rid)
+ continue
+ }
+ // A builtin row converging away here was confirmed gone this
+ // round; drop its version record too, mirroring the demote path.
+ delete(ws.builtinVersions, rt.Provider)
+ }
delete(d.runtimeIndex, rid)
+ dropped = append(dropped, rid)
}
- ws.runtimeIDs = nil
+ ws.runtimeIDs = kept
if profileSig != "" {
- // Cache the converged-empty signature so we don't loop into
- // re-converging on every subsequent sync tick.
+ // Cache the converged signature so we don't loop into re-converging
+ // on every subsequent sync tick.
ws.profileSetSig = profileSig
}
d.mu.Unlock()
d.logger.Info("custom runtime profile drift converged to zero; clearing local tracking",
- "workspace_id", workspaceID, "deregistered_runtime_ids", oldRuntimeIDs)
+ "workspace_id", workspaceID, "deregistered_runtime_ids", dropped,
+ "preserved_providers", preserveProviders)
- if len(oldRuntimeIDs) > 0 {
- if err := d.client.Deregister(ctx, oldRuntimeIDs); err != nil {
- // Best-effort: the server's stale-heartbeat sweep marks the rows
- // offline within ~150 s as a backstop, and on the daemon side
- // we have already stopped heartbeating them.
- d.logger.Warn("deregister after zero-runtime convergence failed",
- "workspace_id", workspaceID, "runtime_ids", oldRuntimeIDs, "error", err)
- }
- }
+ d.deregisterDroppedRuntimes(ctx, workspaceID, dropped, "zero-runtime convergence")
d.notifyRuntimeSetChanged()
return nil
}
@@ -2573,7 +3220,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
)
probeBuiltins := func() []map[string]string {
if !builtinsProbed {
- builtins = d.detectBuiltinRuntimes(ctx)
+ builtins, _, _ = d.detectBuiltinRuntimes(ctx)
builtinsProbed = true
}
return builtins
@@ -2604,29 +3251,77 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
registered++
continue
}
- resp, profileSig, err := d.registerRuntimesForWorkspaceBatch(ctx, id, probeBuiltins())
+ payload := probeBuiltins()
+ var (
+ resp *RegisterResponse
+ runtimeIDs []string
+ )
+ // Send, publish and clean up as one ordered step — see
+ // workspaceRegisterLock.
+ err := d.withWorkspaceRegisterLock(id, func() error {
+ var profileSig string
+ var err error
+ resp, profileSig, err = d.registerRuntimesForWorkspaceBatchLocked(ctx, id, payload)
+ if err != nil {
+ return err
+ }
+ // First registration is the third path a response reaches local state
+ // through — it builds the workspaceState directly instead of going via
+ // applyRegisterResponseInPlace / mergeBuiltinRegisterResponse — so it
+ // needs the same demotion guard, taken in the same d.mu section that
+ // publishes the state. A workspace joining while a provider is held
+ // below-minimum must not be the way that provider comes back.
+ d.mu.Lock()
+ runtimeIDs = make([]string, 0, len(resp.Runtimes))
+ var revivedIDs []string
+ for _, rt := range resp.Runtimes {
+ if rt.ProfileID == "" && d.providerDemotedLocked(rt.Provider) {
+ revivedIDs = append(revivedIDs, rt.ID)
+ continue
+ }
+ runtimeIDs = append(runtimeIDs, rt.ID)
+ d.logger.Info("registered runtime", "workspace_id", id, "runtime_id", rt.ID, "provider", rt.Provider)
+ }
+ ws := newWorkspaceState(id, runtimeIDs, resp.ReposVersion, resp.Repos, resp.Settings)
+ // Seed the profile signature so later on-demand change notifications can
+ // detect drift without re-registering on duplicates (empty sig is the
+ // explicit "unknown — keep the previous value" sentinel from
+ // appendProfileRuntimes; on first registration there is no previous
+ // value, so empty stays empty).
+ ws.profileSetSig = profileSig
+ // Seed the per-workspace record of what the server was told (the
+ // register call above ran before this workspaceState existed, so
+ // recordBuiltinVersionsSent inside it had nowhere to write).
+ ws.builtinVersions = builtinVersionsFromPayload(payload)
+ for provider := range ws.builtinVersions {
+ // Same reason recordBuiltinVersionsSent skips these: a version
+ // record for a provider whose rows are being refused reads as
+ // "this workspace is current" to the next refresh round.
+ if d.providerDemotedLocked(provider) {
+ delete(ws.builtinVersions, provider)
+ }
+ }
+ d.workspaces[id] = ws
+ for _, rt := range resp.Runtimes {
+ if rt.ProfileID == "" && d.providerDemotedLocked(rt.Provider) {
+ continue
+ }
+ d.runtimeIndex[rt.ID] = rt
+ }
+ d.mu.Unlock()
+
+ // The server upserted the refused rows into existence, so it alone
+ // would believe they are online and keep routing work to them. Take
+ // them offline before anything else touches this workspace — and never
+ // RecoverOrphans them below: that reports tasks for a runtime the
+ // daemon does not track and will never claim for.
+ d.deregisterRevivedRuntimes(ctx, id, revivedIDs)
+ return nil
+ })
if err != nil {
d.logger.Error("failed to register runtimes", "workspace_id", id, "name", name, "error", err)
continue
}
- runtimeIDs := make([]string, len(resp.Runtimes))
- for i, rt := range resp.Runtimes {
- runtimeIDs[i] = rt.ID
- d.logger.Info("registered runtime", "workspace_id", id, "runtime_id", rt.ID, "provider", rt.Provider)
- }
- d.mu.Lock()
- ws := newWorkspaceState(id, runtimeIDs, resp.ReposVersion, resp.Repos, resp.Settings)
- // Seed the profile signature so later on-demand change notifications can
- // detect drift without re-registering on duplicates (empty sig is the
- // explicit "unknown — keep the previous value" sentinel from
- // appendProfileRuntimes; on first registration there is no previous
- // value, so empty stays empty).
- ws.profileSetSig = profileSig
- d.workspaces[id] = ws
- for _, rt := range resp.Runtimes {
- d.runtimeIndex[rt.ID] = rt
- }
- d.mu.Unlock()
if d.repoCache != nil && len(resp.Repos) > 0 {
go d.syncWorkspaceRepos(id, resp.Repos)
@@ -2642,7 +3337,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
}
}
- d.logger.Info("watching workspace", "workspace_id", id, "name", name, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos))
+ d.logger.Info("watching workspace", "workspace_id", id, "name", name, "runtimes", len(runtimeIDs), "repos", len(resp.Repos))
registered++
}
@@ -3416,7 +4111,11 @@ func (d *Daemon) exitClaim() {
func (d *Daemon) trySetClaimBarrier() bool {
d.claimMu.Lock()
defer d.claimMu.Unlock()
- if d.claimsInFlight > 0 || d.activeTasks.Load() > 0 {
+ // Refuse when the barrier is already held. Without this the function silently
+ // double-acquires: two holders both believe they own it, and whichever
+ // finishes first releases it out from under the other. tryBeginServerUpdate
+ // makes the same check for the same reason.
+ if d.pauseClaims || d.claimsInFlight > 0 || d.activeTasks.Load() > 0 {
return false
}
d.pauseClaims = true
@@ -3433,33 +4132,27 @@ func (d *Daemon) releaseClaimBarrier() {
d.pauseClaims = false
}
-// triggerRestart initiates a graceful daemon restart after a successful CLI update.
-// For brew installs, it keeps the symlink path (e.g. /opt/homebrew/bin/multica)
-// so the restarted daemon picks up the new Cellar version automatically.
-// For non-brew installs, it resolves to the absolute path of the replaced binary.
-// The caller (cmd_daemon.go) checks RestartBinary() and launches the new process.
-func (d *Daemon) triggerRestart() {
- newBin, err := resolveSelfExecutable()
+// triggerRestart initiates a graceful daemon restart into the binary at
+// restartTargetBinary(). The caller (cmd_daemon.go) checks RestartBinary() and
+// launches the new process.
+//
+// Returns false when the target path could not be resolved, so a caller holding
+// the claim barrier can release it instead of leaving the daemon paused for a
+// restart that will never happen. A restart already scheduled counts as success:
+// the process is going down either way.
+func (d *Daemon) triggerRestart() bool {
+ d.restartMu.Lock()
+ defer d.restartMu.Unlock()
+
+ if d.restartBinary != "" {
+ d.logger.Debug("daemon restart already scheduled", "new_binary", d.restartBinary)
+ return true
+ }
+
+ newBin, err := d.restartTargetBinary()
if err != nil {
d.logger.Error("could not resolve executable path for restart", "error", err)
- return
- }
- // On Linux, os.Executable() reads /proc/self/exe, which the kernel resolves
- // to the Cellar path. brew cleanup deletes that path after upgrade, so we
- // must use the stable <brew-prefix>/bin/multica symlink instead.
- if isBrewInstall() {
- if brewPrefix := getBrewPrefix(); brewPrefix != "" {
- newBin = filepath.Join(brewPrefix, "bin", "multica")
- } else if prefix := matchKnownBrewPrefix(newBin); prefix != "" {
- newBin = filepath.Join(prefix, "bin", "multica")
- } else {
- d.logger.Warn("brew install detected but prefix could not be resolved; restart may fail",
- "executable", newBin)
- }
- } else {
- if resolved, err := filepath.EvalSymlinks(newBin); err == nil {
- newBin = resolved
- }
+ return false
}
d.logger.Info("scheduling daemon restart", "new_binary", newBin)
@@ -3469,6 +4162,52 @@ func (d *Daemon) triggerRestart() {
if d.cancelFunc != nil {
d.cancelFunc()
}
+ return true
+}
+
+// restartTargetBinary resolves the path a restart would re-exec.
+//
+// For brew installs it keeps the stable symlink path (e.g.
+// /opt/homebrew/bin/multica) so the restarted daemon picks up the new Cellar
+// version automatically: on Linux os.Executable() reads /proc/self/exe, which
+// the kernel resolves to the Cellar path, and brew cleanup deletes that path
+// after an upgrade. For non-brew installs it resolves to the absolute path of
+// the replaced binary.
+//
+// Shared with trySelfReload, which must version-probe the same binary the
+// restart would run — probing os.Executable() directly would read the old
+// Cellar path under brew and miss the upgrade entirely.
+func (d *Daemon) restartTargetBinary() (string, error) {
+ newBin, err := resolveSelfExecutable()
+ if err != nil {
+ return "", err
+ }
+ // The install method and brew prefix are fixed for the process lifetime;
+ // resolve them once so the per-tick reload probe doesn't fork
+ // `brew --prefix` every 5 minutes.
+ d.brewTargetOnce.Do(func() {
+ d.brewInstall = isBrewInstall()
+ if !d.brewInstall {
+ return
+ }
+ if brewPrefix := getBrewPrefix(); brewPrefix != "" {
+ d.brewTarget = filepath.Join(brewPrefix, "bin", "multica")
+ } else if prefix := matchKnownBrewPrefix(newBin); prefix != "" {
+ d.brewTarget = filepath.Join(prefix, "bin", "multica")
+ }
+ })
+ if d.brewInstall {
+ if d.brewTarget != "" {
+ return d.brewTarget, nil
+ }
+ d.logger.Warn("brew install detected but prefix could not be resolved; restart may fail",
+ "executable", newBin)
+ return newBin, nil
+ }
+ if resolved, err := filepath.EvalSymlinks(newBin); err == nil {
+ newBin = resolved
+ }
+ return newBin, nil
}
// pollLoop runs the machine-level batch claim poller (MUL-4257): a single
@@ -3806,8 +4545,28 @@ func (d *Daemon) watchTaskCancellation(ctx context.Context, taskID string, pollI
func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
d.mu.Lock()
- rt := d.runtimeIndex[task.RuntimeID]
+ rt, tracked := d.runtimeIndex[task.RuntimeID]
d.mu.Unlock()
+ // The runtime can go offline between the batch claim leaving with its ID and
+ // the claimed task arriving here — a below-minimum demotion or a drift
+ // convergence to zero both drop rows while a claim is in flight. Reporting it
+ // as runtime_offline is what the server already retries on; without this the
+ // zero-value Runtime carries an empty provider and the task dies several
+ // hundred lines later as `no agent configured for provider ""`, which reads
+ // like a misconfigured host and is not retried.
+ if !tracked {
+ d.logger.Warn("claimed task targets a runtime this daemon no longer hosts; failing it back for retry",
+ "task", shortID(task.ID), "runtime_id", task.RuntimeID)
+ if err := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: "runtime went offline before the task started",
+ failureReason: taskfailure.ReasonRuntimeOffline.String(),
+ }); err != nil {
+ d.logger.Error("fail task callback failed", "task", shortID(task.ID), "error", err)
+ }
+ return
+ }
provider := rt.Provider
// Task-scoped logger with short ID for readable concurrent logs.
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index b5c7ec5dba..3d5ad1804d 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -3954,6 +3954,52 @@ func TestHandleTask_BareErrorReportsFailureWithCancelledParent(t *testing.T) {
}
}
+// TestHandleTask_UntrackedRuntimeFailsBackForRetry covers the window between a
+// batch claim leaving with a runtime ID and the claimed task arriving here.
+//
+// A below-minimum demotion or a drift convergence to zero drops runtime rows
+// without coordinating with in-flight claims — deliberately, since gating claims
+// on that is the machinery this daemon does not have. So the task can arrive for
+// a runtime the daemon no longer holds, and the unchecked map read used to hand
+// it a zero-value Runtime: an empty provider that died hundreds of lines later
+// as `no agent configured for provider ""`, a reason the server does not retry.
+func TestHandleTask_UntrackedRuntimeFailsBackForRetry(t *testing.T) {
+ t.Parallel()
+
+ var failBody atomic.Value
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if !strings.HasSuffix(req.URL.Path, "/fail") {
+ t.Errorf("unexpected daemon call: %s %s", req.Method, req.URL.Path)
+ }
+ var body map[string]any
+ _ = json.NewDecoder(req.Body).Decode(&body)
+ failBody.Store(body)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ runtimeIndex: map[string]Runtime{},
+ cancelPollInterval: time.Hour,
+ }
+ d.runner = taskRunnerFunc(func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error) {
+ t.Error("runner ran for a runtime the daemon no longer hosts")
+ return TaskResult{}, nil
+ })
+
+ d.handleTask(context.Background(), Task{ID: "task-gone-runtime", RuntimeID: "rt-demoted"}, 0)
+
+ body, _ := failBody.Load().(map[string]any)
+ if body == nil {
+ t.Fatal("task was never reported as failed; the server would wait out its dispatch timeout")
+ }
+ if got := body["failure_reason"]; got != "runtime_offline" {
+ t.Errorf("failure_reason = %v, want runtime_offline — the reason the server auto-retries on", got)
+ }
+}
+
// TestHandleTask_ReportsUsageBeforeCancel verifies that ReportTaskUsage is called
// even when the server marks the task as cancelled during the post-run status
// check. Regression test for the ordering bug where the cancel check ran before
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index d50e16e2c5..e3db8fca6d 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -42,7 +42,12 @@ type HealthResponse struct {
// render as an absent runtime, which is what made GH #6077 unactionable for
// the reporter (MUL-5439).
SkippedAgents map[string]string `json:"skipped_agents,omitempty"`
- Workspaces []healthWorkspace `json:"workspaces"`
+ // ReloadPendingReason explains why the daemon has confirmed a multica
+ // version change on disk but hasn't restarted into it yet — it was busy at
+ // the last barrier check and will retry when idle. Omitted when empty, so
+ // older consumers see no change. Diagnostic only: nothing keys off it.
+ ReloadPendingReason string `json:"reload_pending_reason,omitempty"`
+ Workspaces []healthWorkspace `json:"workspaces"`
}
type healthWorkspace struct {
@@ -114,7 +119,9 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {
ActiveTaskCount: d.activeTasks.Load(),
Agents: agents,
SkippedAgents: d.skippedAgentsSnapshot(),
- Workspaces: wsList,
+
+ ReloadPendingReason: d.reloadPending(),
+ Workspaces: wsList,
}
w.Header().Set("Content-Type", "application/json")
diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.go
index 49c3aa0906..1797ec1a4c 100644
--- a/server/internal/daemon/health_test.go
+++ b/server/internal/daemon/health_test.go
@@ -77,6 +77,51 @@ func TestHealthHandlerReportsCLIVersionAndActiveTaskCount(t *testing.T) {
}
}
+// TestHealthHandlerReportsDeferredReload covers the "while waiting to restart,
+// the reason and state are visible" criterion. When trySelfReload has confirmed
+// a multica version change but the daemon was busy at the barrier check, the
+// only way a user can tell why the daemon is still on the old version is this
+// field. It is omitempty, so an idle daemon must not emit the key at all.
+func TestHealthHandlerReportsDeferredReload(t *testing.T) {
+ t.Parallel()
+
+ newHealthProbe := func(t *testing.T) (*Daemon, func() map[string]any) {
+ t.Helper()
+ d := &Daemon{
+ cfg: Config{CLIVersion: "0.3.7"},
+ workspaces: map[string]*workspaceState{},
+ logger: slog.Default(),
+ }
+ d.ready.Store(true)
+ return d, func() map[string]any {
+ rec := httptest.NewRecorder()
+ d.healthHandler(time.Now()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))
+ var raw map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode raw response: %v", err)
+ }
+ return raw
+ }
+ }
+
+ t.Run("absent when nothing pending", func(t *testing.T) {
+ _, probe := newHealthProbe(t)
+ if _, present := probe()["reload_pending_reason"]; present {
+ t.Error("reload_pending_reason must be omitted when no restart is pending")
+ }
+ })
+
+ t.Run("explains a deferred restart", func(t *testing.T) {
+ d, probe := newHealthProbe(t)
+ d.setReloadPending("multica binary on disk reports 0.3.8, running 0.3.7")
+
+ got, _ := probe()["reload_pending_reason"].(string)
+ if !strings.Contains(got, "0.3.8") {
+ t.Errorf("reload_pending_reason = %q, want it to name the version on disk", got)
+ }
+ })
+}
+
// TestHealthHandlerReportsStartingUntilReady pins the liveness/readiness split:
// the health server binds and answers before preflight finishes, but it must
// report "starting" until d.ready is set, and only then "running". Otherwise a
diff --git a/server/internal/daemon/helpers.go b/server/internal/daemon/helpers.go
index 4aa81781a6..f3d31d61cb 100644
--- a/server/internal/daemon/helpers.go
+++ b/server/internal/daemon/helpers.go
@@ -55,6 +55,19 @@ func parseFlexDuration(value string) (time.Duration, error) {
return time.ParseDuration(expanded)
}
+// boolFromEnv reads a boolean env override, returning fallback when the
+// variable is unset or carries an unrecognized token. Accepted (case
+// insensitive): true/1/yes/on and false/0/no/off.
+func boolFromEnv(key string, fallback bool) bool {
+ switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
+ case "false", "0", "no", "off":
+ return false
+ case "true", "1", "yes", "on":
+ return true
+ }
+ return fallback
+}
+
func intFromEnv(key string, fallback int) (int, error) {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.go
index 837aa54f06..a1fbfbbdec 100644
--- a/server/internal/daemon/runtime_isolation_test.go
+++ b/server/internal/daemon/runtime_isolation_test.go
@@ -164,6 +164,10 @@ func TestRunBatchPollerClaimsAcrossRuntimes(t *testing.T) {
MaxConcurrentTasks: 4,
}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))
d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1", "rt-2"}}
+ // Both halves, as every production path that publishes a runtime ID does:
+ // handleTask fails a claimed task whose runtime it no longer holds.
+ d.runtimeIndex["rt-1"] = Runtime{ID: "rt-1", Provider: "codex"}
+ d.runtimeIndex["rt-2"] = Runtime{ID: "rt-2", Provider: "claude"}
d.cancelPollInterval = time.Hour // no server-side cancellation polling in this test
var mu sync.Mutex
diff --git a/server/internal/daemon/runtime_probe_batch_test.go b/server/internal/daemon/runtime_probe_batch_test.go
index 99e913b25a..d7ec510c6d 100644
--- a/server/internal/daemon/runtime_probe_batch_test.go
+++ b/server/internal/daemon/runtime_probe_batch_test.go
@@ -16,6 +16,8 @@ import (
"sync/atomic"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
)
// batchFixture wires a Daemon against a fake server that serves a configurable
@@ -39,6 +41,9 @@ type batchFixture struct {
registered []registeredCall
// probes counts detectAgentVersion calls per executable path.
probes map[string]int
+ // probeVersion is what the version probe stub reports; defaults to "9.9.9".
+ // Changing it mid-test simulates an in-place agent CLI upgrade.
+ probeVersion string
// probeErr, when set, is consulted by the version probe stub before it
// succeeds. It receives the executable path and the 1-based attempt count
// for that path, and returns a non-nil error to fail that attempt.
@@ -52,6 +57,70 @@ type batchFixture struct {
// best-effort profile fetch failing while a discovery-driven registration
// is in flight.
profilesFail bool
+ // deregistered accumulates every runtime ID sent to /api/daemon/deregister,
+ // so a test can assert the server was actually told to stop routing work.
+ deregistered []string
+ // registerDelay, when non-zero, makes the register handler sleep before
+ // recording the call, widening the window in which two unserialized
+ // register calls for the same workspace would overlap.
+ registerDelay time.Duration
+ // registerGate, when set, is invoked by the register handler (off fx.mu)
+ // with the workspace ID before the response is built. A test blocks in it to
+ // hold one register in flight while it drives another state change, which is
+ // how the "response predates a verdict" interleaves are made deterministic
+ // instead of timing-dependent.
+ registerGate func(workspaceID string)
+ // registerInFlight / registerMaxInFlight track how many register handlers
+ // run at once, so a test can assert same-workspace serialization.
+ registerInFlight int
+ registerMaxInFlight int
+ // deregisterGate, when set, is invoked by the deregister handler (off fx.mu)
+ // with the runtime IDs before they are applied. A test blocks in it to hold
+ // one cleanup in flight while it drives a recovery, which is how the
+ // "an older cleanup outlives a newer recovery" interleave is made
+ // deterministic instead of timing-dependent.
+ deregisterGate func(runtimeIDs []string)
+ // stableRuntimeIDs makes the register handler return ONE id per
+ // (workspace, runtime) rather than a fresh one per call, mirroring the
+ // server's UpsertAgentRuntime: re-registering a provider returns the row
+ // that already exists. A cleanup can only undo a recovery when the two name
+ // the same row, so that interleave is invisible without this.
+ stableRuntimeIDs bool
+ runtimeIDs map[string]string // "<workspace>|<profile_id or type>" -> runtime ID
+ // online is the server's view of each runtime row: register puts it online,
+ // deregister takes it offline. This is what a test asserts on when the
+ // question is "which side won", rather than "was a call made".
+ online map[string]bool
+}
+
+// enableStableRuntimeIDs must be called before the first registration.
+func (fx *batchFixture) enableStableRuntimeIDs() {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ fx.stableRuntimeIDs = true
+}
+
+// setDeregisterGate installs a hook the deregister handler calls before the
+// rows are taken offline.
+func (fx *batchFixture) setDeregisterGate(fn func(runtimeIDs []string)) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ fx.deregisterGate = fn
+}
+
+// runtimeIDFor returns the server-side runtime ID for a workspace's provider
+// (or profile), which only exists under enableStableRuntimeIDs.
+func (fx *batchFixture) runtimeIDFor(workspaceID, key string) string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.runtimeIDs[workspaceID+"|"+key]
+}
+
+// runtimeOnline reports the server's current status for a runtime row.
+func (fx *batchFixture) runtimeOnline(id string) bool {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.online[id]
}
// failRegister toggles register failure for every workspace.
@@ -96,6 +165,9 @@ func (fx *batchFixture) profilesShouldFail() bool {
type registeredCall struct {
workspaceID string
types []string
+ // versions maps runtime type -> the version that call reported, so a test
+ // can assert the server was told about an in-place CLI upgrade.
+ versions map[string]string
}
func (fx *batchFixture) setWorkspaces(ws ...WorkspaceInfo) {
@@ -110,6 +182,27 @@ func (fx *batchFixture) probeCount(path string) int {
return fx.probes[path]
}
+// setProbeVersion changes what `<cli> --version` reports from now on.
+func (fx *batchFixture) setProbeVersion(version string) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ fx.probeVersion = version
+}
+
+// registeredVersionFor returns the version the LAST Register call for a
+// workspace reported for a provider.
+func (fx *batchFixture) registeredVersionFor(workspaceID, provider string) string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ var version string
+ for _, call := range fx.registered {
+ if call.workspaceID == workspaceID {
+ version = call.versions[provider]
+ }
+ }
+ return version
+}
+
func (fx *batchFixture) setProbeErr(fn func(path string, attempt int) error) {
fx.mu.Lock()
defer fx.mu.Unlock()
@@ -132,6 +225,43 @@ func (fx *batchFixture) registrationFor(workspaceID string) ([]string, int) {
return types, calls
}
+// deregisteredCount returns how many runtime IDs were deregistered server-side.
+func (fx *batchFixture) deregisteredCount() int {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return len(fx.deregistered)
+}
+
+// deregisteredIDs copies the runtime IDs deregistered server-side, in order.
+func (fx *batchFixture) deregisteredIDs() []string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return append([]string(nil), fx.deregistered...)
+}
+
+// setRegisterDelay makes every register call linger, so a test can detect two
+// of them overlapping when they should be serialized.
+// setRegisterGate installs a hook the register handler calls before responding.
+func (fx *batchFixture) setRegisterGate(fn func(workspaceID string)) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ fx.registerGate = fn
+}
+
+func (fx *batchFixture) setRegisterDelay(d time.Duration) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ fx.registerDelay = d
+}
+
+// maxRegisterInFlight reports the peak number of concurrently running
+// register handlers.
+func (fx *batchFixture) maxRegisterInFlight() int {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.registerMaxInFlight
+}
+
func (fx *batchFixture) registerCallCount() int {
fx.mu.Lock()
defer fx.mu.Unlock()
@@ -141,8 +271,11 @@ func (fx *batchFixture) registerCallCount() int {
func newBatchFixture(t *testing.T) *batchFixture {
t.Helper()
fx := &batchFixture{
- profiles: make(map[string][]RuntimeProfile),
- probes: make(map[string]int),
+ profiles: make(map[string][]RuntimeProfile),
+ probes: make(map[string]int),
+ probeVersion: "9.9.9",
+ runtimeIDs: make(map[string]string),
+ online: make(map[string]bool),
}
origDetect := detectAgentVersion
@@ -156,13 +289,14 @@ func newBatchFixture(t *testing.T) *batchFixture {
fx.probes[path]++
attempt := fx.probes[path]
probeErr := fx.probeErr
+ version := fx.probeVersion
fx.mu.Unlock()
if probeErr != nil {
if err := probeErr(path, attempt); err != nil {
return "", err
}
}
- return "9.9.9", nil
+ return version, nil
}
checkAgentMinVersion = func(_, _ string) error { return nil }
@@ -181,28 +315,81 @@ func newBatchFixture(t *testing.T) *batchFixture {
Runtimes []map[string]string `json:"runtimes"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
+ fx.mu.Lock()
+ fx.registerInFlight++
+ if fx.registerInFlight > fx.registerMaxInFlight {
+ fx.registerMaxInFlight = fx.registerInFlight
+ }
+ delay := fx.registerDelay
+ gate := fx.registerGate
+ fx.mu.Unlock()
+ if gate != nil {
+ gate(body.WorkspaceID)
+ }
+ defer func() {
+ fx.mu.Lock()
+ fx.registerInFlight--
+ fx.mu.Unlock()
+ }()
+ if delay > 0 {
+ time.Sleep(delay)
+ }
if fx.registerShouldFail(body.WorkspaceID) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"injected register failure"}`))
return
}
- call := registeredCall{workspaceID: body.WorkspaceID}
+ call := registeredCall{workspaceID: body.WorkspaceID, versions: map[string]string{}}
var resp RegisterResponse
+ fx.mu.Lock()
for _, rt := range body.Runtimes {
call.types = append(call.types, rt["type"])
+ call.versions[rt["type"]] = rt["version"]
+ // Mirror UpsertAgentRuntime: a re-register of a row that already
+ // exists returns that row's ID rather than minting a new one.
+ id := "rt-" + strconv.Itoa(int(runtimeSeq.Add(1)))
+ if fx.stableRuntimeIDs {
+ key := body.WorkspaceID + "|" + rt["type"]
+ if rt["profile_id"] != "" {
+ key = body.WorkspaceID + "|" + rt["profile_id"]
+ }
+ if existing, ok := fx.runtimeIDs[key]; ok {
+ id = existing
+ } else {
+ fx.runtimeIDs[key] = id
+ }
+ }
+ fx.online[id] = true
resp.Runtimes = append(resp.Runtimes, Runtime{
- ID: "rt-" + strconv.Itoa(int(runtimeSeq.Add(1))),
+ ID: id,
Name: rt["name"],
Provider: rt["type"],
Status: "online",
ProfileID: rt["profile_id"],
})
}
- fx.mu.Lock()
fx.registered = append(fx.registered, call)
fx.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
+ case r.URL.Path == "/api/daemon/deregister":
+ var body struct {
+ RuntimeIDs []string `json:"runtime_ids"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ fx.mu.Lock()
+ gate := fx.deregisterGate
+ fx.mu.Unlock()
+ if gate != nil {
+ gate(body.RuntimeIDs)
+ }
+ fx.mu.Lock()
+ fx.deregistered = append(fx.deregistered, body.RuntimeIDs...)
+ for _, id := range body.RuntimeIDs {
+ fx.online[id] = false
+ }
+ fx.mu.Unlock()
+ w.WriteHeader(http.StatusOK)
case strings.HasSuffix(r.URL.Path, "/runtime-profiles"):
if fx.profilesShouldFail() {
w.WriteHeader(http.StatusInternalServerError)
@@ -368,7 +555,7 @@ func TestRegisterRuntimesForWorkspace_ProbesOnStandaloneCall(t *testing.T) {
d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/fake/claude"}}
for i := 1; i <= 2; i++ {
- if _, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {
+ if _, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1"); err != nil {
t.Fatalf("register #%d: %v", i, err)
}
if got := fx.probeCount("/fake/claude"); got != i {
@@ -458,7 +645,7 @@ func TestDetectBuiltinRuntimes_DropsProviderAfterRetriesExhausted(t *testing.T)
return nil
})
- runtimes := d.detectBuiltinRuntimes(context.Background())
+ runtimes, _, _ := d.detectBuiltinRuntimes(context.Background())
if got := fx.probeCount("/fake/codex"); got != runtimeVersionProbeAttempts {
t.Errorf("probed /fake/codex %d times, want %d (retry must stay bounded)", got, runtimeVersionProbeAttempts)
@@ -483,7 +670,7 @@ func TestDetectBuiltinRuntimes_DoesNotRetrySlowProbe(t *testing.T) {
return errors.New("signal: killed")
})
- if runtimes := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
+ if runtimes, _, _ := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
t.Fatalf("detected %v, want none", runtimes)
}
if got := fx.probeCount("/fake/codex"); got != 1 {
@@ -557,7 +744,7 @@ func TestDetectBuiltinRuntimes_DoesNotRetryWhenSelfHealBurnsTheWindow(t *testing
d := freshDaemon("")
d.cfg.Agents = map[string]AgentEntry{"codex": {Path: missing, Command: "codex"}}
- if runtimes := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
+ if runtimes, _, _ := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
t.Fatalf("detected %v, want none", runtimes)
}
if got := probes.Load(); got != 2 {
@@ -565,13 +752,16 @@ func TestDetectBuiltinRuntimes_DoesNotRetryWhenSelfHealBurnsTheWindow(t *testing
}
}
-// TestDetectBuiltinRuntimes_BoundsRetryWhenSelfHealRejectsVersion documents the
-// cost of the case the retry cannot tell apart: a self-heal candidate rejected
-// by the min-version gate leaves the stale path in place, and the outer probe
-// then fails fast — indistinguishable from a transient failure, so the attempt
-// is retried. The verdict is deterministic, so that retry is wasted work; what
-// matters is that it stays bounded and cheap (every probe in it fails fast).
-func TestDetectBuiltinRuntimes_BoundsRetryWhenSelfHealRejectsVersion(t *testing.T) {
+// TestDetectBuiltinRuntimes_SelfHealRejectionIsABelowMinimumVerdict covers the
+// downgrade shape a version manager produces: the pinned path is deleted and the
+// command now resolves to a binary below the minimum supported version.
+//
+// The self-heal refuses to adopt it — correctly, it must never be launched — but
+// that refusal IS the below-minimum verdict, and swallowing it made the outer
+// probe fall back to the vanished path, fail, and report "version detection
+// failed" instead. That reads as transient by design, which leaves the runtime
+// online and claiming tasks for a CLI that cannot start.
+func TestDetectBuiltinRuntimes_SelfHealRejectionIsABelowMinimumVerdict(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("PATH/exec-bit stub layout is POSIX-specific")
}
@@ -585,7 +775,7 @@ func TestDetectBuiltinRuntimes_BoundsRetryWhenSelfHealRejectsVersion(t *testing.
})
checkAgentMinVersion = func(_, version string) error {
if version == "0.0.1" {
- return errors.New("version too old")
+ return &agent.BelowMinimumError{AgentType: "codex", Detected: version, Minimum: "1.0.0"}
}
return nil
}
@@ -593,12 +783,25 @@ func TestDetectBuiltinRuntimes_BoundsRetryWhenSelfHealRejectsVersion(t *testing.
d := freshDaemon("")
d.cfg.Agents = map[string]AgentEntry{"codex": {Path: missing, Command: "codex"}}
- if runtimes := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
+ runtimes, belowMin, _ := d.detectBuiltinRuntimes(context.Background())
+ if len(runtimes) != 0 {
t.Fatalf("detected %v (healed path %q), want none: a below-minimum candidate must not be adopted", runtimes, healed)
}
- // Two attempts, each paying one self-heal probe plus one outer probe.
- if got := probes.Load(); got != int32(2*runtimeVersionProbeAttempts) {
- t.Errorf("ran %d version probes, want %d (%d bounded attempts)", got, 2*runtimeVersionProbeAttempts, runtimeVersionProbeAttempts)
+ // The refusal is the verdict, not a probe failure. Without carrying it out of
+ // the heal, the loop goes on to probe the vanished pinned path, can only
+ // report "version detection failed", and the runtime stays online serving a
+ // CLI that cannot launch.
+ if belowMin["codex"] != "0.0.1" {
+ t.Errorf("below-minimum verdict = %v, want codex 0.0.1", belowMin)
+ }
+ // Unlike the direct below-minimum case, the heal verdict gets the bounded
+ // fast-failure retry before it is returned: the heal re-resolves PATH per
+ // attempt, and mid-upgrade a stale sibling install can shadow the
+ // not-yet-published new binary — so the demotable verdict is only returned
+ // once the retry reached the same conclusion. One probe per attempt, both
+ // on the healed candidate (the outer probe of the vanished path never runs).
+ if got := probes.Load(); got != 2 {
+ t.Errorf("ran %d version probes, want 2 (one per bounded attempt)", got)
}
}
@@ -608,16 +811,16 @@ func TestDetectBuiltinRuntimes_BoundsRetryWhenSelfHealRejectsVersion(t *testing.
func TestDetectBuiltinRuntimes_DoesNotRetryMinVersionRejection(t *testing.T) {
fx := newBatchFixture(t)
stubProbeRetry(t, time.Millisecond, time.Second)
- checkAgentMinVersion = func(provider, _ string) error {
+ checkAgentMinVersion = func(provider, version string) error {
if provider == "codex" {
- return errors.New("version too old")
+ return &agent.BelowMinimumError{AgentType: provider, Detected: version, Minimum: "1.0.0"}
}
return nil
}
d := fx.daemon
d.cfg.Agents = map[string]AgentEntry{"codex": {Path: "/fake/codex"}}
- if runtimes := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
+ if runtimes, _, _ := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 0 {
t.Fatalf("detected %v, want none", runtimes)
}
if got := fx.probeCount("/fake/codex"); got != 1 {
@@ -643,7 +846,7 @@ func TestRegisterRuntimesForWorkspaceBatch_DoesNotMutateSharedPayload(t *testing
builtins := []map[string]string{
{"name": "Claude Code", "type": "claude", "version": "9.9.9", "status": "online"},
}
- if _, _, err := d.registerRuntimesForWorkspaceBatch(context.Background(), "ws-1", builtins); err != nil {
+ if _, _, err := d.registerRuntimesForWorkspaceBatchLocked(context.Background(), "ws-1", builtins); err != nil {
t.Fatalf("batch register: %v", err)
}
diff --git a/server/internal/daemon/runtime_probe_concurrency_test.go b/server/internal/daemon/runtime_probe_concurrency_test.go
index 47cfb00dda..67dbb93565 100644
--- a/server/internal/daemon/runtime_probe_concurrency_test.go
+++ b/server/internal/daemon/runtime_probe_concurrency_test.go
@@ -47,7 +47,7 @@ func TestDetectBuiltinRuntimes_ProbesRunConcurrently(t *testing.T) {
}
start := time.Now()
- runtimes := d.detectBuiltinRuntimes(context.Background())
+ runtimes, _, _ := d.detectBuiltinRuntimes(context.Background())
elapsed := time.Since(start)
if len(runtimes) != len(d.cfg.Agents) {
@@ -104,7 +104,7 @@ func TestDetectBuiltinRuntimes_SkipsFailedProbes(t *testing.T) {
"tooold": {Path: "/usr/bin/true"},
}
- runtimes := d.detectBuiltinRuntimes(context.Background())
+ runtimes, _, _ := d.detectBuiltinRuntimes(context.Background())
got := map[string]bool{}
for _, rt := range runtimes {
got[rt["type"]] = true
diff --git a/server/internal/daemon/runtime_profile_drift_test.go b/server/internal/daemon/runtime_profile_drift_test.go
index f0a772ad98..fa512d22ba 100644
--- a/server/internal/daemon/runtime_profile_drift_test.go
+++ b/server/internal/daemon/runtime_profile_drift_test.go
@@ -302,7 +302,7 @@ func TestRefreshWorkspaceRuntimeProfiles_NoDrift_DoesNotReregister(t *testing.T)
d.cfg.Agents = map[string]AgentEntry{}
// Initial register seeds workspaceState (and ws.profileSetSig).
- resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, profileSig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("initial register: %v", err)
}
@@ -344,7 +344,7 @@ func TestRefreshWorkspaceRuntimeProfiles_NewProfileTriggersReregister(t *testing
d.cfg.Agents = map[string]AgentEntry{}
// Initial register with one profile.
- resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, profileSig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("initial register: %v", err)
}
@@ -438,7 +438,7 @@ func TestRefreshWorkspaceRuntimeProfiles_DriftWithRunningRuntimeSkipsOrphanRecov
d := fx.daemon
d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}
- resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, profileSig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("initial register: %v", err)
}
@@ -496,7 +496,7 @@ func TestRefreshWorkspaceRuntimeProfiles_DisableConvergesCustomOnlyDaemon(t *tes
d.cfg.Agents = map[string]AgentEntry{}
// Initial register: one custom runtime.
- resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, profileSig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("initial register: %v", err)
}
@@ -594,7 +594,7 @@ func TestRefreshWorkspaceRuntimeProfiles_DisableOneOfManyDeregistersDroppedID(t
// Mixed: one built-in + one custom.
d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}
- resp, profileSig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, profileSig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("initial register: %v", err)
}
diff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.go
index f17e9b0159..a81909421e 100644
--- a/server/internal/daemon/runtime_profile_test.go
+++ b/server/internal/daemon/runtime_profile_test.go
@@ -161,7 +161,7 @@ func TestRegisterRuntimes_IncludesBuiltInQwen(t *testing.T) {
"qwen": {Path: "/usr/bin/true", Command: "qwen", Model: "qwen3.8-max-preview"},
}
- resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -185,7 +185,7 @@ func TestRegisterRuntimes_IncludesBuiltInQoderCN(t *testing.T) {
"qoderclicn": {Path: "/usr/bin/true", Command: "qoderclicn"},
}
- resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -220,7 +220,7 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {
// Custom-only host: no built-in agents configured.
d.cfg.Agents = map[string]AgentEntry{}
- resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -277,7 +277,7 @@ func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {
d := fx.daemon
d.cfg.Agents = map[string]AgentEntry{}
- _, sig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ _, sig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -314,7 +314,7 @@ func TestRegisterRuntimes_SkipsUnsupportedProfileFamily(t *testing.T) {
d := fx.daemon
d.cfg.Agents = map[string]AgentEntry{}
- _, sig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ _, sig, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -354,7 +354,7 @@ func TestRegisterRuntimes_ProfilesFetchErrorIsBestEffort(t *testing.T) {
// Built-in agent present so registration has something to register.
d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}
- resp, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")
+ resp, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1")
if err != nil {
t.Fatalf("registration should succeed despite profiles 404: %v", err)
}
@@ -389,7 +389,7 @@ func TestRegisterRuntimes_PrefersCommandPathOverride(t *testing.T) {
d.cfg.Agents = map[string]AgentEntry{}
d.cfg.ProfileCommandOverrides = map[string]string{"prof-1": "/opt/custom/company-codex"}
- if _, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {
+ if _, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1"); err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
@@ -423,7 +423,7 @@ func TestRegisterRuntimes_OverrideNotExecutableFallsBackToPath(t *testing.T) {
d.cfg.Agents = map[string]AgentEntry{}
d.cfg.ProfileCommandOverrides = map[string]string{"prof-1": "/opt/stale/company-codex"}
- if _, _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1"); err != nil {
+ if _, _, _, err := d.registerRuntimesForWorkspaceLocked(context.Background(), "ws-1"); err != nil {
t.Fatalf("registerRuntimesForWorkspace: %v", err)
}
diff --git a/server/internal/daemon/self_reload_test.go b/server/internal/daemon/self_reload_test.go
new file mode 100644
index 0000000000..00e5d440ad
--- /dev/null
+++ b/server/internal/daemon/self_reload_test.go
@@ -0,0 +1,586 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// newSelfReloadTestDaemon returns a Daemon wired for trySelfReload: a stubbed
+// self-executable path so restartTargetBinary resolves without touching the
+// real process, plus a sentinel cancelFunc the test asserts on to detect that
+// triggerRestart fired.
+func newSelfReloadTestDaemon(t *testing.T, runningVersion string) (*Daemon, *atomic.Int32) {
+ t.Helper()
+
+ origResolve := resolveSelfExecutable
+ origBrew := isBrewInstall
+ t.Cleanup(func() {
+ resolveSelfExecutable = origResolve
+ isBrewInstall = origBrew
+ })
+ binary := filepath.Join(t.TempDir(), "multica")
+ resolveSelfExecutable = func() (string, error) { return binary, nil }
+ isBrewInstall = func() bool { return false }
+
+ var restartCalls atomic.Int32
+ d := &Daemon{
+ cfg: Config{CLIVersion: runningVersion, AutoReloadEnabled: true},
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ cancelFunc: func() { restartCalls.Add(1) },
+ }
+ return d, &restartCalls
+}
+
+// stubSelfVersion makes the `multica --version` probe report version (or fail).
+func stubSelfVersion(t *testing.T, version string, err error) *atomic.Int32 {
+ t.Helper()
+ orig := detectSelfVersion
+ t.Cleanup(func() { detectSelfVersion = orig })
+ var calls atomic.Int32
+ detectSelfVersion = func(context.Context, string) (string, error) {
+ calls.Add(1)
+ return version, err
+ }
+ return &calls
+}
+
+// TestTrySelfReload_RestartsWhenOnDiskVersionDiffers is the core of MUL-3269:
+// an in-place upgrade leaves the executable path valid, so nothing in the
+// existing self-heal notices it and the daemon serves the version it booted
+// with indefinitely. Comparing the compile-time version against the binary on
+// disk is what closes that.
+func TestTrySelfReload_RestartsWhenOnDiskVersionDiffers(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "0.3.8", nil)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times, want 1", restartCalls.Load())
+ }
+ if d.RestartBinary() == "" {
+ t.Fatal("restart binary not recorded; the parent has nothing to re-exec")
+ }
+ if !claimsPaused(t, d) {
+ t.Fatal("pauseClaims must stay held across the restart kick, like the auto-update path")
+ }
+}
+
+// TestTrySelfReload_RestartsOnDowngrade covers a gap tryAutoUpdate structurally
+// cannot: isNewerVersion says no, so the GitHub poller never fires, but the
+// operator did deliberately install an older build and the daemon must follow it.
+func TestTrySelfReload_RestartsOnDowngrade(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.8")
+ stubSelfVersion(t, "0.3.7", nil)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times, want 1 (a downgrade is still a version change)", restartCalls.Load())
+ }
+}
+
+// TestTrySelfReload_ProbeFailureIsNotAVersionChange is the review's third
+// blocker. The binary is most likely to be unreadable during the few hundred
+// milliseconds of the very upgrade this check exists to detect (vanished path,
+// ETXTBSY), and "couldn't read the version" must never restart the daemon into
+// a version nobody confirmed.
+func TestTrySelfReload_ProbeFailureIsNotAVersionChange(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "", errors.New("fork/exec: text file busy"))
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired on a failed probe")
+ }
+ if claimsPaused(t, d) {
+ t.Fatal("a failed probe must not pause claiming")
+ }
+ if got := d.reloadPending(); got != "" {
+ t.Fatalf("reload pending reason = %q, want empty after a failed probe", got)
+ }
+}
+
+// TestTrySelfReload_BlankVersionIsNotAVersionChange covers a probe that exits 0
+// without telling us anything, and the mirror case of a running version we don't
+// know: restarting on a blank running version would produce a successor that
+// reads blank too, i.e. a reload every tick forever.
+func TestTrySelfReload_BlankVersionIsNotAVersionChange(t *testing.T) {
+ cases := []struct{ name, running, onDisk string }{
+ {"blank on disk", "0.3.7", ""},
+ {"blank running", "", "0.3.8"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, tc.running)
+ stubSelfVersion(t, tc.onDisk, nil)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatal("triggerRestart fired on a version it could not compare")
+ }
+ if got := d.reloadPending(); got != "" {
+ t.Fatalf("reload pending reason = %q, want empty", got)
+ }
+ })
+ }
+}
+
+// TestTrySelfReload_NoopWhenVersionMatches also covers the operator putting the
+// old binary back before the daemon went idle: the deferred-restart note must
+// clear rather than linger on /health forever.
+func TestTrySelfReload_NoopWhenVersionMatches(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "0.3.7", nil)
+ d.setReloadPending("stale note from an earlier round")
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired even though the on-disk version matches")
+ }
+ if got := d.reloadPending(); got != "" {
+ t.Fatalf("reload pending reason = %q, want it cleared once the change went away", got)
+ }
+}
+
+// TestTrySelfReload_DefersWhileBusy pins the "a running task is never
+// interrupted by an upgrade" acceptance criterion, for both shapes of busy.
+//
+// Deferring is the whole mechanism — there is deliberately no pending-restart
+// state machine waiting on a drain signal, because that is what parked the
+// daemon in the first draft of this feature: the drain hook was anchored to
+// exitClaim, which the batch poller (MUL-4257) now calls synchronously right
+// after dispatch while activeTasks is still non-zero. Retrying from scratch on
+// the next tick cannot get stuck that way.
+func TestTrySelfReload_DefersWhileBusy(t *testing.T) {
+ cases := []struct {
+ name string
+ setup func(*Daemon)
+ }{
+ {"task running", func(d *Daemon) { d.activeTasks.Store(1) }},
+ {"claim in flight", func(d *Daemon) { d.claimMu.Lock(); d.claimsInFlight = 1; d.claimMu.Unlock() }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ probes := stubSelfVersion(t, "0.3.8", nil)
+ tc.setup(d)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired while the daemon was busy")
+ }
+ if claimsPaused(t, d) {
+ t.Fatal("a deferred reload must leave claiming enabled, not park the poller")
+ }
+ if got := d.reloadPending(); got == "" {
+ t.Fatal("a deferred reload must be visible on /health so the stale version is explainable")
+ }
+
+ // The next tick re-probes from scratch and restarts once idle —
+ // no baseline to go stale, no signal to wait for.
+ d.activeTasks.Store(0)
+ d.claimMu.Lock()
+ d.claimsInFlight = 0
+ d.claimMu.Unlock()
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times after the daemon went idle, want 1", restartCalls.Load())
+ }
+ if probes.Load() != 2 {
+ t.Fatalf("probed %d times, want 2 (each tick re-probes)", probes.Load())
+ }
+ })
+ }
+}
+
+// TestTrySelfReload_SkipsWhenAnUpdateIsInFlight keeps this check off the
+// server-triggered handleUpdate's toes: that path runs on its own goroutine and
+// ends in triggerRestart too.
+func TestTrySelfReload_SkipsWhenAnUpdateIsInFlight(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ probes := stubSelfVersion(t, "0.3.8", nil)
+ d.updating.Store(true)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatal("triggerRestart fired while another update was in progress")
+ }
+ if probes.Load() != 0 {
+ t.Fatal("skipping must happen before the probe, not after paying for it")
+ }
+}
+
+// TestTrySelfReload_SkipsWhenRestartAlreadyScheduled stops a second tick from
+// re-entering during the shutdown window after triggerRestart cancelled the
+// root context.
+func TestTrySelfReload_SkipsWhenRestartAlreadyScheduled(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "0.3.8", nil)
+
+ d.trySelfReload(context.Background())
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("cancelFunc fired %d times, want 1", restartCalls.Load())
+ }
+}
+
+// TestTrySelfReload_ReleasesBarrierWhenHandoffFails is the review's nit about
+// the first draft looping: a failed restart must not leave the daemon paused
+// forever, and because nothing is remembered across ticks the next round simply
+// re-detects and retries.
+func TestTrySelfReload_ReleasesBarrierWhenHandoffFails(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "0.3.8", nil)
+
+ // Resolve succeeds for the probe, then starts failing at the handoff.
+ resolveSelfExecutable = func() (string, error) { return "", errors.New("cannot resolve executable") }
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatal("cancelFunc fired without a restart binary")
+ }
+ if claimsPaused(t, d) {
+ t.Fatal("pauseClaims must be released when the restart handoff fails, or the daemon claims nothing ever again")
+ }
+}
+
+// TestAutoUpdateLoop_WatchesTheBinaryWhenAutoUpdateIsOff is the review's first
+// product decision: the on-disk check must not sit behind
+// MULTICA_DAEMON_AUTO_UPDATE. Self-hosted daemons default auto-update off
+// (MUL-2381), and "don't pull from GitHub" is not "don't follow the binary I
+// replaced myself".
+func TestAutoUpdateLoop_WatchesTheBinaryWhenAutoUpdateIsOff(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ d.cfg.AutoUpdateEnabled = false
+ stubSelfVersion(t, "0.3.8", nil)
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v9.9.9"}, errors.New("fetchLatestRelease must not be called"))
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatal("runUpdateFn called with auto-update disabled")
+ return "", nil
+ }
+ shortenLoopTimers(t)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ done := make(chan struct{})
+ go func() {
+ d.autoUpdateLoop(ctx)
+ close(done)
+ }()
+
+ waitFor(t, func() bool { return restartCalls.Load() == 1 },
+ "self-reload never restarted with auto-update disabled")
+ cancel()
+ <-done
+}
+
+// TestAutoUpdateLoop_AlsoWatchesTheBinaryForDevBuilds covers the other half of
+// the same gap: isReleaseVersion skips dev builds for the GitHub poller, but a
+// developer who rebuilt and replaced the binary wants the daemon to run it.
+func TestAutoUpdateLoop_AlsoWatchesTheBinaryForDevBuilds(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "v0.3.7-42-gabcdef0")
+ d.cfg.AutoUpdateEnabled = true
+ stubSelfVersion(t, "v0.3.7-43-gbcdef01", nil)
+ withStubRelease(t, nil, errors.New("fetchLatestRelease must not be called for a dev build"))
+ shortenLoopTimers(t)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ done := make(chan struct{})
+ go func() {
+ d.autoUpdateLoop(ctx)
+ close(done)
+ }()
+
+ waitFor(t, func() bool { return restartCalls.Load() == 1 },
+ "self-reload never restarted for a dev build")
+ cancel()
+ <-done
+}
+
+// TestAutoUpdateLoop_SkipsBothHalvesForDesktop asserts the Desktop exclusion is
+// drawn once, above both checks: the Electron app ships and replaces the CLI
+// binary itself, so following it would fight the app's own lifecycle.
+func TestAutoUpdateLoop_SkipsBothHalvesForDesktop(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ d.cfg.AutoUpdateEnabled = true
+ d.cfg.LaunchedBy = "desktop"
+ probes := stubSelfVersion(t, "0.3.8", nil)
+ withStubRelease(t, nil, errors.New("fetchLatestRelease must not be called on Desktop"))
+ shortenLoopTimers(t)
+
+ // Returns immediately rather than looping, so no cancel is needed.
+ d.autoUpdateLoop(context.Background())
+
+ if probes.Load() != 0 {
+ t.Fatalf("probed the binary %d times on a Desktop-managed daemon, want 0", probes.Load())
+ }
+ if restartCalls.Load() != 0 {
+ t.Fatal("Desktop-managed daemon scheduled a restart")
+ }
+}
+
+// TestAutoUpdateLoop_ExitsWhenBothHalvesDisabled keeps the goroutine from
+// spinning a ticker nobody reads.
+func TestAutoUpdateLoop_ExitsWhenBothHalvesDisabled(t *testing.T) {
+ d, _ := newSelfReloadTestDaemon(t, "0.3.7")
+ d.cfg.AutoUpdateEnabled = false
+ d.cfg.AutoReloadEnabled = false
+ probes := stubSelfVersion(t, "0.3.8", nil)
+ shortenLoopTimers(t)
+
+ d.autoUpdateLoop(context.Background())
+
+ if probes.Load() != 0 {
+ t.Fatalf("probed %d times with both halves disabled, want 0", probes.Load())
+ }
+}
+
+func TestParseSelfVersion(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want string
+ }{
+ {
+ name: "release build template",
+ raw: "multica 0.3.7 (commit: abc1234, built: 2026-07-29T10:00:00Z)\ngo: go1.26.1, os/arch: darwin/arm64\n",
+ want: "0.3.7",
+ },
+ {
+ name: "dev build from git describe",
+ raw: "multica v0.3.7-42-gabcdef0-dirty (commit: abcdef0, built: unknown)\n",
+ want: "v0.3.7-42-gabcdef0-dirty",
+ },
+ {
+ // Unrecognized shape is reported as-is rather than swallowed: it
+ // compares unequal, which surfaces as a reload instead of silence.
+ name: "unexpected shape falls back to the first line",
+ raw: "0.3.7\n",
+ want: "0.3.7",
+ },
+ {
+ name: "empty output",
+ raw: "",
+ want: "",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := ParseSelfVersion(tc.raw); got != tc.want {
+ t.Fatalf("ParseSelfVersion(%q) = %q, want %q", tc.raw, got, tc.want)
+ }
+ })
+ }
+}
+
+// shortenLoopTimers collapses the loop's startup delay and check interval so a
+// loop-level test finishes in milliseconds.
+func shortenLoopTimers(t *testing.T) {
+ t.Helper()
+ origDelay, origInterval := autoUpdateInitialDelay, selfReloadCheckInterval
+ t.Cleanup(func() {
+ autoUpdateInitialDelay = origDelay
+ selfReloadCheckInterval = origInterval
+ })
+ autoUpdateInitialDelay = time.Millisecond
+ selfReloadCheckInterval = 5 * time.Millisecond
+}
+
+func waitFor(t *testing.T, cond func() bool, msg string) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(deadline) {
+ if cond() {
+ return
+ }
+ time.Sleep(time.Millisecond)
+ }
+ t.Fatal(msg)
+}
+
+// claimsPaused reads pauseClaims under claimMu, honoring the field's own
+// concurrency contract rather than relying on the test being single-goroutine.
+func claimsPaused(t *testing.T, d *Daemon) bool {
+ t.Helper()
+ d.claimMu.Lock()
+ defer d.claimMu.Unlock()
+ return d.pauseClaims
+}
+
+// TestTryAutoUpdate_ResumesClaimingWhenRestartCannotBeScheduled is the
+// permanent-stall case. tryAutoUpdate marks both cleanup switches as released
+// just before the handoff, on the assumption that the process is about to exit.
+// If triggerRestart cannot resolve a target, no exit is coming — and holding the
+// updating flag and the claim barrier for a restart that never happens leaves
+// the daemon alive but claiming nothing, forever. Every poller's tryEnterClaim
+// returns false and nothing ever clears it.
+//
+// Note this outlived the void-returning triggerRestart it came from: the failure
+// was unobservable before. trySelfReload handles the same failure, so the two
+// halves of one loop must not disagree about it.
+func TestTryAutoUpdate_ResumesClaimingWhenRestartCannotBeScheduled(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+ d.runUpdateFn = func(string) (string, error) { return "upgraded", nil }
+
+ origResolve := resolveSelfExecutable
+ t.Cleanup(func() { resolveSelfExecutable = origResolve })
+ resolveSelfExecutable = func() (string, error) { return "", errors.New("cannot resolve executable") }
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatal("cancelFunc fired without a restart binary")
+ }
+ if claimsPaused(t, d) {
+ t.Error("pauseClaims held for a restart that will never happen — the daemon would claim nothing forever")
+ }
+ if d.updating.Load() {
+ t.Error("updating flag held for a restart that will never happen — no later update or reload could run")
+ }
+}
+
+// TestTrySelfReload_YieldsToAServerTriggeredUpdate closes the ownership race,
+// interleaved the way it actually happens rather than pre-set.
+//
+// The bug isn't "updating was already true" — a plain Load() catches that. It is
+// the window *after* the look: handleUpdate wins the CAS while this path is
+// still probing, starts replacing the binary, and this path carries on to
+// triggerRestart anyway — re-execing a half-written file and cutting the
+// update's status reporting off partway. The claim barrier arbitrates nothing
+// here, because handleUpdate reaches it through tryBeginServerUpdate and the two
+// never inspect each other's state. Acquiring ownership up front is what makes
+// the window unreachable.
+func TestTrySelfReload_YieldsToAServerTriggeredUpdate(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+
+ // The server-triggered path tries to take ownership mid-probe, exactly as
+ // handleUpdate would via tryBeginServerUpdate's CAS.
+ var serverUpdateWon atomic.Bool
+ orig := detectSelfVersion
+ t.Cleanup(func() { detectSelfVersion = orig })
+ detectSelfVersion = func(context.Context, string) (string, error) {
+ if d.updating.CompareAndSwap(false, true) {
+ serverUpdateWon.Store(true)
+ }
+ return "0.3.8", nil
+ }
+
+ d.trySelfReload(context.Background())
+
+ if serverUpdateWon.Load() {
+ t.Fatalf("a server-triggered update acquired ownership mid-reload (restarts fired: %d) — "+
+ "this path only sampled the flag instead of taking it, so both could act on the binary at once",
+ restartCalls.Load())
+ }
+}
+
+// TestTrySelfReload_SkipsWhenOwnershipIsAlreadyHeld is the simpler half: an
+// update already in flight when the tick fires.
+func TestTrySelfReload_SkipsWhenOwnershipIsAlreadyHeld(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ probes := stubSelfVersion(t, "0.3.8", nil)
+ if !d.updating.CompareAndSwap(false, true) {
+ t.Fatal("precondition: updating should have been free")
+ }
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatal("restarted while a server-triggered update was replacing the binary")
+ }
+ if claimsPaused(t, d) {
+ t.Error("took the claim barrier out from under the in-flight update")
+ }
+ if probes.Load() != 0 {
+ t.Error("ownership must be settled before paying for a probe")
+ }
+ if !d.updating.Load() {
+ t.Error("released the other path's update ownership")
+ }
+}
+
+// TestTrySelfReload_ReleasesUpdateOwnershipOnEveryNonRestartPath: holding the
+// flag after deciding not to restart would block every later update — the
+// server-triggered one included — with nothing to clear it.
+func TestTrySelfReload_ReleasesUpdateOwnershipOnEveryNonRestartPath(t *testing.T) {
+ cases := []struct {
+ name string
+ onDisk string
+ probeer error
+ busy bool
+ }{
+ {name: "probe failed", probeer: errors.New("text file busy")},
+ {name: "no change", onDisk: "0.3.7"},
+ {name: "blank on disk", onDisk: ""},
+ {name: "deferred while busy", onDisk: "0.3.8", busy: true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ d, _ := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, tc.onDisk, tc.probeer)
+ if tc.busy {
+ d.activeTasks.Store(1)
+ }
+
+ d.trySelfReload(context.Background())
+
+ if d.updating.Load() {
+ t.Fatal("update ownership held after declining to restart; nothing would ever clear it")
+ }
+ })
+ }
+}
+
+// TestTrySelfReload_HoldsUpdateOwnershipAcrossRestart is the one path that must
+// keep it: the process is going down, and clearing it would let a second
+// attempt start mid-shutdown.
+func TestTrySelfReload_HoldsUpdateOwnershipAcrossRestart(t *testing.T) {
+ d, restartCalls := newSelfReloadTestDaemon(t, "0.3.7")
+ stubSelfVersion(t, "0.3.8", nil)
+
+ d.trySelfReload(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times, want 1", restartCalls.Load())
+ }
+ if !d.updating.Load() {
+ t.Error("update ownership must survive the restart kick")
+ }
+}
+
+// TestTrySetClaimBarrier_RefusesWhenAlreadyHeld: without this the function
+// silently double-acquires, and whichever holder finishes first releases the
+// barrier out from under the other.
+func TestTrySetClaimBarrier_RefusesWhenAlreadyHeld(t *testing.T) {
+ d := &Daemon{}
+
+ if !d.trySetClaimBarrier() {
+ t.Fatal("first acquisition should succeed on an idle daemon")
+ }
+ if d.trySetClaimBarrier() {
+ t.Fatal("second acquisition succeeded while the barrier was already held")
+ }
+ d.releaseClaimBarrier()
+ if !d.trySetClaimBarrier() {
+ t.Fatal("acquisition should succeed again after release")
+ }
+}
diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.go
index 89e391a633..41bf227047 100644
--- a/server/pkg/agent/version.go
+++ b/server/pkg/agent/version.go
@@ -151,8 +151,26 @@ func (v semver) lessThan(other semver) bool {
return v.Patch < other.Patch
}
+// BelowMinimumError reports a version that parsed successfully and is below
+// the configured minimum. It is a distinct type so callers can tell a
+// CONFIRMED too-old verdict apart from "could not parse the version": only
+// the former is evidence strong enough to act on (taking a runtime offline),
+// while an unreadable version must be treated like any other failed
+// detection and leave working runtimes alone.
+type BelowMinimumError struct {
+ AgentType string
+ Detected string
+ Minimum string
+}
+
+func (e *BelowMinimumError) Error() string {
+ return fmt.Sprintf("%s version %s is below minimum required %s — please upgrade", e.AgentType, e.Detected, e.Minimum)
+}
+
// CheckMinVersion validates that detectedVersion meets the minimum for agentType.
-// Returns nil if the version is acceptable or no minimum is defined.
+// Returns nil if the version is acceptable or no minimum is defined, a
+// *BelowMinimumError when the version parsed and is confirmed too old, and a
+// plain error when the version could not be parsed at all.
func CheckMinVersion(agentType, detectedVersion string) error {
minRaw, ok := MinVersions[agentType]
if !ok {
@@ -167,7 +185,7 @@ func CheckMinVersion(agentType, detectedVersion string) error {
return fmt.Errorf("cannot parse detected %s version %q: %w", agentType, detectedVersion, err)
}
if detected.lessThan(min) {
- return fmt.Errorf("%s version %s is below minimum required %s — please upgrade", agentType, detectedVersion, minRaw)
+ return &BelowMinimumError{AgentType: agentType, Detected: detectedVersion, Minimum: minRaw}
}
return nil
}