Skip to content

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

Go

MUL-6164 feat(runtime): take an unusable agent CLI offline and refuse its triggers with the fix (#6966)

Bohan Jiangb30a3ae55c3d
diff --git a/packages/views/issues/blocked-trigger-copy.test.ts b/packages/views/issues/blocked-trigger-copy.test.ts
index 5488132a91..f31366eb4b 100644
--- a/packages/views/issues/blocked-trigger-copy.test.ts
+++ b/packages/views/issues/blocked-trigger-copy.test.ts
@@ -41,6 +41,21 @@ describe("blocked trigger copy", () => {
expect(unbound).toBe(en.comment.trigger_blocked_short_agent_runtime_required);
});
+ // MUL-6164 adds the third member of the family: the machine is reachable and
+ // its CLI cannot run there. "Offline" copy would send the user to reconnect
+ // something that is already connected.
+ it("distinguishes an unusable runtime from an offline one", () => {
+ const unusable = blockedReasonLabel("runtime_unusable", t);
+ const offline = blockedReasonLabel("runtime_offline", t);
+
+ expect(unusable).not.toBe(offline);
+ expect(unusable).toBe(en.comment.trigger_blocked_runtime_unusable);
+ expect(unusable.toLowerCase()).not.toContain("offline");
+ expect(blockedShortReasonLabel("runtime_unusable", t)).toBe(
+ en.comment.trigger_blocked_short_runtime_unusable,
+ );
+ });
+
it("degrades an unknown code to the generic label", () => {
expect(blockedReasonLabel("some_future_code", t)).toBe(en.comment.trigger_blocked_generic);
expect(blockedShortReasonLabel("some_future_code", t)).toBe(
diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.ts
index 41397cd50a..e11165659d 100644
--- a/packages/views/issues/blocked-trigger-copy.ts
+++ b/packages/views/issues/blocked-trigger-copy.ts
@@ -17,6 +17,12 @@ import type { useT } from "../i18n";
// reason (MUL-5559): an unbound agent has no machine to reconnect, so "runtime
// offline" copy sends the user looking for a computer that does not exist. The
// fix it needs is binding the agent to a runtime.
+//
+// `runtime_unusable` is the third member of that family (MUL-6164): the machine
+// IS reachable and its agent CLI cannot be executed there, so "offline" copy
+// sends the user to reconnect something that is already connected. The fix is a
+// reinstall on that machine, and the system comment the server leaves on the
+// issue carries the exact command.
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
// Full sentence — for tooltips and other surfaces with room to explain.
@@ -28,6 +34,8 @@ export function blockedReasonLabel(reasonCode: string, t: IssuesT): string {
return t(($) => $.comment.trigger_blocked_target_unavailable);
case "runtime_offline":
return t(($) => $.comment.trigger_blocked_runtime_offline);
+ case "runtime_unusable":
+ return t(($) => $.comment.trigger_blocked_runtime_unusable);
case "agent_runtime_required":
return t(($) => $.comment.trigger_blocked_agent_runtime_required);
default:
@@ -45,6 +53,8 @@ export function blockedShortReasonLabel(reasonCode: string, t: IssuesT): string
return t(($) => $.comment.trigger_blocked_short_target_unavailable);
case "runtime_offline":
return t(($) => $.comment.trigger_blocked_short_runtime_offline);
+ case "runtime_unusable":
+ return t(($) => $.comment.trigger_blocked_short_runtime_unusable);
case "agent_runtime_required":
return t(($) => $.comment.trigger_blocked_short_agent_runtime_required);
default:
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index ac1a72b921..32c074e870 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -414,11 +414,13 @@
"trigger_blocked_invocation_not_allowed": "This target can't be found, or you don't have permission to use it",
"trigger_blocked_target_unavailable": "This target is unavailable",
"trigger_blocked_runtime_offline": "This target's runtime is offline",
+ "trigger_blocked_runtime_unusable": "This target's agent CLI can't run on its machine — reinstall it there",
"trigger_blocked_agent_runtime_required": "This target has no runtime — bind one to run it",
"trigger_blocked_generic": "This target won't be triggered",
"trigger_blocked_short_invocation_not_allowed": "Not found or no permission",
"trigger_blocked_short_target_unavailable": "Unavailable",
"trigger_blocked_short_runtime_offline": "Runtime offline",
+ "trigger_blocked_short_runtime_unusable": "CLI can't run",
"trigger_blocked_short_agent_runtime_required": "Needs a runtime",
"trigger_blocked_short_generic": "Won't start",
"send_reply_failed": "Failed to send reply",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 91243dc36f..b4ec42acad 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -404,11 +404,13 @@
"trigger_blocked_invocation_not_allowed": "この対象が見つからないか、使用する権限がありません",
"trigger_blocked_target_unavailable": "この対象は利用できません",
"trigger_blocked_runtime_offline": "この対象のランタイムがオフラインです",
+ "trigger_blocked_runtime_unusable": "この対象の CLI はそのマシンで実行できません — そのマシンで再インストールしてください",
"trigger_blocked_agent_runtime_required": "この対象にはランタイムがありません — 実行するにはバインドしてください",
"trigger_blocked_generic": "この対象はトリガーされません",
"trigger_blocked_short_invocation_not_allowed": "未検出または権限なし",
"trigger_blocked_short_target_unavailable": "利用不可",
"trigger_blocked_short_runtime_offline": "ランタイム オフライン",
+ "trigger_blocked_short_runtime_unusable": "CLI を実行できません",
"trigger_blocked_short_agent_runtime_required": "ランタイム未設定",
"trigger_blocked_short_generic": "トリガーされません",
"send_reply_failed": "返信を送信できませんでした",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 4ec5fa272d..35877bd9d9 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -404,11 +404,13 @@
"trigger_blocked_invocation_not_allowed": "이 대상을 찾을 수 없거나 사용할 권한이 없습니다",
"trigger_blocked_target_unavailable": "이 대상을 사용할 수 없습니다",
"trigger_blocked_runtime_offline": "이 대상의 런타임이 오프라인입니다",
+ "trigger_blocked_runtime_unusable": "이 대상의 CLI를 해당 기기에서 실행할 수 없습니다 — 그 기기에서 다시 설치하세요",
"trigger_blocked_agent_runtime_required": "이 대상에 런타임이 없습니다 — 실행하려면 런타임을 연결하세요",
"trigger_blocked_generic": "이 대상은 트리거되지 않습니다",
"trigger_blocked_short_invocation_not_allowed": "찾을 수 없음 또는 권한 없음",
"trigger_blocked_short_target_unavailable": "사용 불가",
"trigger_blocked_short_runtime_offline": "런타임 오프라인",
+ "trigger_blocked_short_runtime_unusable": "CLI 실행 불가",
"trigger_blocked_short_agent_runtime_required": "런타임 필요",
"trigger_blocked_short_generic": "트리거 안 됨",
"send_reply_failed": "답글을 보내지 못했습니다",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 310b824dfd..284fa735e1 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -404,11 +404,13 @@
"trigger_blocked_invocation_not_allowed": "找不到该目标,或你没有它的使用权限",
"trigger_blocked_target_unavailable": "该目标不可用",
"trigger_blocked_runtime_offline": "该目标的运行时已离线",
+ "trigger_blocked_runtime_unusable": "该目标的 CLI 在它所在的机器上无法运行 —— 需要在那台机器上重装",
"trigger_blocked_agent_runtime_required": "该目标未绑定运行时——绑定后才能运行",
"trigger_blocked_generic": "该目标不会被触发",
"trigger_blocked_short_invocation_not_allowed": "找不到或无权限",
"trigger_blocked_short_target_unavailable": "不可用",
"trigger_blocked_short_runtime_offline": "运行时离线",
+ "trigger_blocked_short_runtime_unusable": "CLI 无法运行",
"trigger_blocked_short_agent_runtime_required": "需绑定运行时",
"trigger_blocked_short_generic": "不会触发",
"send_reply_failed": "发送回复失败",
diff --git a/server/internal/daemon/agent_version_refresh_test.go b/server/internal/daemon/agent_version_refresh_test.go
index 918ba62da2..86a0479a56 100644
--- a/server/internal/daemon/agent_version_refresh_test.go
+++ b/server/internal/daemon/agent_version_refresh_test.go
@@ -375,7 +375,7 @@ func TestDemoteBelowMinimumRuntimes_DoesNotRaceTheHealthHandler(t *testing.T) {
}
}()
for i := 0; i < 100; i++ {
- d.demoteBelowMinimumRuntimes(context.Background(), map[string]string{"codex": "0.0.1"})
+ d.demoteUnusableRuntimes(context.Background(), map[string]runtimeVerdict{"codex": {reason: "below minimum supported version: 0.0.1"}})
}
<-done
@@ -1126,7 +1126,7 @@ func TestDemoteBelowMinimumRuntimes_LateRegisterResponseCannotReviveTheProvider(
deregsBefore := fx.deregisteredCount()
// The older register's response finally lands.
- newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse("ws-1", staleResp)
+ newIDs, revived, ok := d.mergeBuiltinRegisterResponse("ws-1", staleResp)
if !ok {
t.Fatal("merge of the late register response failed")
}
@@ -1140,11 +1140,11 @@ func TestDemoteBelowMinimumRuntimes_LateRegisterResponseCannotReviveTheProvider(
// 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 {
+ if len(revived.ids) == 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)
+ d.deregisterRevivedRuntimes(context.Background(), "ws-1", revived)
if got := fx.deregisteredCount(); got <= deregsBefore {
t.Errorf("deregister calls %d -> %d; the revived server row was never taken offline", deregsBefore, got)
}
@@ -1316,7 +1316,7 @@ func TestClearProviderDemotions_KeepsHoldWhenEvidencePredatesTheVerdict(t *testi
sampledAfter := d.demotionSeqSnapshot()
d.mu.Lock()
- d.markProvidersDemotedLocked(map[string]string{"codex": "0.0.1"})
+ d.markProvidersDemotedLocked(map[string]runtimeVerdict{"codex": {reason: "below minimum supported version: 0.0.1"}})
d.mu.Unlock()
d.clearProviderDemotions([]string{"codex"}, sampledAfter)
@@ -1369,7 +1369,7 @@ func TestDetectBuiltinRuntimes_StaleOKRoundDoesNotReleaseANewerHold(t *testing.T
// The downgrade is confirmed while that round is still in flight.
d.mu.Lock()
- d.markProvidersDemotedLocked(map[string]string{"codex": "0.0.1"})
+ d.markProvidersDemotedLocked(map[string]runtimeVerdict{"codex": {reason: "below minimum supported version: 0.0.1"}})
d.mu.Unlock()
close(release)
diff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.go
index e232401bb8..56fc0e02af 100644
--- a/server/internal/daemon/agents_refresh.go
+++ b/server/internal/daemon/agents_refresh.go
@@ -254,12 +254,12 @@ func (d *Daemon) refreshAgentVersions(ctx context.Context) {
return
}
- builtins, belowMinimum, _ := d.detectBuiltinRuntimes(ctx)
- // Runs before the early return below: a downgrade drops the provider from
+ builtins, demotable, _ := d.detectBuiltinRuntimes(ctx)
+ // Runs before the early return below: a condemned provider drops out of
// 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)
+ // machine could otherwise look idle while an unusable CLI keeps taking work.
+ if len(demotable) > 0 {
+ d.demoteUnusableRuntimes(ctx, demotable)
}
if len(builtins) == 0 {
return
@@ -325,14 +325,14 @@ func (d *Daemon) refreshAgentVersions(ctx context.Context) {
"workspace_id", id, "error", err)
return nil
}
- newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse(id, resp)
+ newIDs, revived, ok := d.mergeBuiltinRegisterResponse(id, resp)
if !ok {
return nil
}
if len(newIDs) > 0 {
changed = true
}
- d.deregisterRevivedRuntimes(ctx, id, rejectedIDs)
+ d.deregisterRevivedRuntimes(ctx, id, revived)
return nil
})
}
@@ -341,8 +341,9 @@ func (d *Daemon) refreshAgentVersions(ctx context.Context) {
}
}
-// demoteBelowMinimumRuntimes takes offline the built-in runtimes of providers
-// whose re-probe confirmed a version below the minimum supported one.
+// demoteUnusableRuntimes takes offline the built-in runtimes of providers whose
+// re-probe reached a confirmed verdict about the binary on disk: a version below
+// the minimum supported one, or a file the OS refuses to execute at all.
//
// Without this, an in-place DOWNGRADE is the one machine change nothing reacts
// to. probeBuiltinRuntime drops the provider from the registration payload, so
@@ -353,6 +354,12 @@ func (d *Daemon) refreshAgentVersions(ctx context.Context) {
// already verified it cannot run correctly, under the previously cached
// version's policy.
//
+// A CLI that cannot exec reaches the same dead end by a different road
+// (MUL-6164): an npm placeholder stub passes every "is it installed" check the
+// daemon makes, so the runtime stays online and every task it claims dies at
+// fork/exec. Treating that as transient meant the user saw the same failure once
+// per task instead of once, and had no signal the runtime was the problem.
+//
// 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
@@ -361,11 +368,15 @@ func (d *Daemon) refreshAgentVersions(ctx context.Context) {
// 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) {
+// Only ever acts on a confirmed verdict, 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. detectBuiltinRuntimes owns that distinction, including the
+// confirmation window a not-executable verdict must clear first.
+//
+// causes maps each condemned provider to the evidence against it, which is
+// already user-visible in skipped_agents and is what the log below reports.
+func (d *Daemon) demoteUnusableRuntimes(ctx context.Context, causes map[string]runtimeVerdict) {
// 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 —
@@ -375,8 +386,8 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
// 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)
+ d.logger.Info("defer runtime demotion: task or claim in flight",
+ "providers", causes)
return
}
defer d.releaseClaimBarrier()
@@ -387,6 +398,7 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
// workspace's register lock — see deregisterDroppedRuntimes.
demotedByWorkspace := make(map[string][]string)
demotedProviders := make(map[string]string)
+ offlineReasons := make(map[string]RuntimeOfflineReason)
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
@@ -399,15 +411,21 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
kept = append(kept, rid)
continue
}
- version, below := belowMinimum[rt.Provider]
- if !below {
+ cause, condemned := causes[rt.Provider]
+ if !condemned {
kept = append(kept, rid)
continue
}
delete(d.runtimeIndex, rid)
demoted = append(demoted, rid)
demotedByWorkspace[workspaceID] = append(demotedByWorkspace[workspaceID], rid)
- demotedProviders[rt.Provider] = version
+ demotedProviders[rt.Provider] = cause.reason
+ // Carried to the server per runtime row: a client asking "why is my
+ // agent offline" reads it from there, and only this side knows both
+ // the verdict and the repair command (MUL-6164).
+ if cause.offline != nil {
+ offlineReasons[rid] = *cause.offline
+ }
// 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
@@ -420,13 +438,13 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
// 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.markProvidersDemotedLocked(causes)
d.mu.Unlock()
if len(demoted) == 0 {
return
}
- d.logger.Warn("agent CLI downgraded below the minimum supported version; taking its runtimes offline",
+ d.logger.Warn("agent CLI is no longer usable on this machine; taking its runtimes offline",
"providers", demotedProviders, "runtime_ids", demoted)
// One workspace at a time, each under its own register lock: the rows were
@@ -442,7 +460,7 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
for _, workspaceID := range workspaceIDs {
_ = d.withWorkspaceRegisterLock(workspaceID, func() error {
d.deregisterDroppedRuntimes(ctx, workspaceID, demotedByWorkspace[workspaceID],
- "below-minimum downgrade")
+ "agent CLI unusable", offlineReasons)
return nil
})
}
@@ -459,7 +477,8 @@ func (d *Daemon) demoteBelowMinimumRuntimes(ctx context.Context, belowMinimum ma
// 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) {
+func (d *Daemon) deregisterRevivedRuntimes(ctx context.Context, workspaceID string, revived revivedRuntimes) {
+ runtimeIDs := revived.ids
// 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
@@ -471,10 +490,14 @@ func (d *Daemon) deregisterRevivedRuntimes(ctx context.Context, workspaceID stri
if len(runtimeIDs) == 0 {
return
}
- d.logger.Warn("register response revived a below-minimum runtime; taking it offline again",
+ d.logger.Warn("register response revived a demoted 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",
+ // Re-send the cause: that register's upsert overwrote the runtime row's
+ // metadata, so the reason the demotion stored is gone and the server would
+ // otherwise be left with a bare "offline" — which reads as "wait for the
+ // machine" on every admission path (MUL-6164).
+ if err := d.client.Deregister(ctx, runtimeIDs, revived.reasonsFor(runtimeIDs)); err != nil {
+ d.logger.Warn("deregister of revived demoted runtimes failed",
"workspace_id", workspaceID, "runtime_ids", runtimeIDs, "error", err)
}
}
@@ -492,12 +515,12 @@ func (d *Daemon) deregisterRevivedRuntimes(ctx context.Context, workspaceID stri
//
// 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) {
+func (d *Daemon) deregisterDroppedRuntimes(ctx context.Context, workspaceID string, runtimeIDs []string, reason string, offlineReasons map[string]RuntimeOfflineReason) {
runtimeIDs = d.untrackedRuntimeIDs(runtimeIDs)
if len(runtimeIDs) == 0 {
return
}
- if err := d.client.Deregister(ctx, runtimeIDs); err != nil {
+ if err := d.client.Deregister(ctx, runtimeIDs, offlineReasons); err != nil {
d.logger.Warn("deregister of dropped runtimes failed",
"workspace_id", workspaceID, "runtime_ids", runtimeIDs, "reason", reason, "error", err)
}
@@ -626,7 +649,7 @@ func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {
"workspace_id", t.id, "providers", t.missing, "error", err)
return nil
}
- newIDs, rejectedIDs, ok := d.mergeBuiltinRegisterResponse(t.id, resp)
+ newIDs, revived, ok := d.mergeBuiltinRegisterResponse(t.id, resp)
if !ok {
return nil
}
@@ -635,7 +658,7 @@ func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {
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)
+ d.deregisterRevivedRuntimes(ctx, t.id, revived)
return nil
})
}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index df5229f546..9d60e3b872 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -13,6 +13,7 @@ import (
"sync"
"time"
+ "github.com/multica-ai/multica/server/pkg/agent"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -789,10 +790,32 @@ func (c *Client) GetTaskGCCheck(ctx context.Context, taskID string) (*TaskGCStat
return &resp, nil
}
-func (c *Client) Deregister(ctx context.Context, runtimeIDs []string) error {
- return c.postJSON(ctx, "/api/daemon/deregister", map[string]any{
- "runtime_ids": runtimeIDs,
- }, nil)
+// RuntimeOfflineCodeNotExecutable marks a runtime taken offline because the OS
+// refuses to execute its agent CLI. It is the one deregistration cause that no
+// amount of waiting fixes, which is what the server needs to know: work for an
+// offline machine may queue until the machine returns, but work for this one
+// must be refused with an explanation (MUL-6164).
+const RuntimeOfflineCodeNotExecutable = "not_executable"
+
+// RuntimeOfflineReason is why a runtime went offline, in the form clients can
+// act on: a stable code they switch on and localize, and the command that
+// repairs the install. Prose stays in Detail for logs — never as the thing a
+// client parses.
+type RuntimeOfflineReason struct {
+ Code string `json:"code"`
+ Detail string `json:"detail,omitempty"`
+ Repair *agent.ExecFormatRepair `json:"repair,omitempty"`
+}
+
+// Deregister takes runtimes offline. reasons is optional and keyed by runtime
+// id: a daemon shutting down has nothing to explain, while one that condemned a
+// broken CLI does.
+func (c *Client) Deregister(ctx context.Context, runtimeIDs []string, reasons map[string]RuntimeOfflineReason) error {
+ body := map[string]any{"runtime_ids": runtimeIDs}
+ if len(reasons) > 0 {
+ body["offline_reasons"] = reasons
+ }
+ return c.postJSON(ctx, "/api/daemon/deregister", body, nil)
}
// RegisterResponse holds the server's response to a daemon registration.
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index dab7dfc2fa..5b17b1586a 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -406,7 +406,13 @@ type Daemon struct {
// 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
+ demotedProviders map[string]demotionRecord // provider -> the evidence that condemned it and when
+
+ // notExecutableSince is when each provider was FIRST observed to be
+ // unrunnable, for the confirmation window in confirmNotExecutable. Entries
+ // are cleared by the round that finds the provider healthy again. Guarded
+ // by d.mu.
+ notExecutableSince map[string]time.Time
// demotionSeq is a monotonic counter stamped onto each demotion record so a
// probe round can tell whether its evidence predates a verdict.
@@ -1478,12 +1484,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, rejectedIDs []string, ok bool) {
+func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *RegisterResponse) (newIDs []string, revived revivedRuntimes, ok bool) {
d.mu.Lock()
defer d.mu.Unlock()
ws, exists := d.workspaces[workspaceID]
if !exists {
- return nil, nil, false
+ return nil, revivedRuntimes{}, false
}
// Index the workspace's current built-in runtimes by provider so a rotated
@@ -1510,7 +1516,7 @@ func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *Register
// guard in applyRegisterResponseInPlace. The caller deregisters the row
// the server upserted back.
if d.providerDemotedLocked(rt.Provider) {
- rejectedIDs = append(rejectedIDs, rt.ID)
+ revived.add(d, rt.ID, rt.Provider)
continue
}
d.runtimeIndex[rt.ID] = rt
@@ -1543,7 +1549,7 @@ func (d *Daemon) mergeBuiltinRegisterResponse(workspaceID string, resp *Register
if len(resp.Settings) > 0 {
ws.settings = resp.Settings
}
- return newIDs, rejectedIDs, true
+ return newIDs, revived, true
}
// providerDemotedLocked reports whether provider is currently held below the
@@ -1555,16 +1561,79 @@ func (d *Daemon) providerDemotedLocked(provider string) bool {
return demoted
}
-// demotionRecord is a confirmed below-minimum verdict: the version that was
-// rejected, plus the demotionSeq tick that establishes when it was reached.
+// demotedOfflineReasonLocked returns the structured cause recorded for a
+// demoted provider, or nil when the verdict carries none (below-minimum) or the
+// provider is not demoted. Callers must hold d.mu.
+func (d *Daemon) demotedOfflineReasonLocked(provider string) *RuntimeOfflineReason {
+ record, demoted := d.demotedProviders[provider]
+ if !demoted {
+ return nil
+ }
+ return record.offline
+}
+
+// revivedRuntimes are the rows a register response brought back for a provider
+// the daemon has already condemned: the ids to take offline again, and the
+// cause to re-attach per row because that register's upsert just overwrote it.
+type revivedRuntimes struct {
+ ids []string
+ reasons map[string]RuntimeOfflineReason
+}
+
+// reasonsFor narrows the causes to the rows actually being deregistered. The
+// caller re-checks tracking first — a row that came back legitimately in the
+// meantime is dropped from the list — and sending a cause for a row we are no
+// longer taking offline would attach it to a healthy runtime.
+func (r revivedRuntimes) reasonsFor(runtimeIDs []string) map[string]RuntimeOfflineReason {
+ if len(r.reasons) == 0 {
+ return nil
+ }
+ out := make(map[string]RuntimeOfflineReason, len(runtimeIDs))
+ for _, id := range runtimeIDs {
+ if reason, ok := r.reasons[id]; ok {
+ out[id] = reason
+ }
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
+// add records one revived row. Callers must hold d.mu (it reads the demotion
+// record), and it is a no-op for a provider with no structured cause — those
+// rows still need deregistering, they just have nothing to re-attach.
+func (r *revivedRuntimes) add(d *Daemon, runtimeID, provider string) {
+ r.ids = append(r.ids, runtimeID)
+ reason := d.demotedOfflineReasonLocked(provider)
+ if reason == nil {
+ return
+ }
+ if r.reasons == nil {
+ r.reasons = make(map[string]RuntimeOfflineReason, 1)
+ }
+ r.reasons[runtimeID] = *reason
+}
+
+// demotionRecord is a confirmed verdict about the binary on disk: the evidence
+// that produced it (the rejected version, or why the CLI could not be run),
+// plus the demotionSeq tick that establishes when it was reached.
+//
+// offline is the structured half, kept because the server can lose it. A
+// register sent before the verdict still upserts the runtime row, and that
+// upsert overwrites metadata wholesale — so the reason this daemon just stored
+// is gone, and the cleanup that takes the revived row offline again has to
+// re-attach it. Without that the server ends up "offline, no reason", which
+// downgrades the refusal back to "wait for the machine" (MUL-6164).
type demotionRecord struct {
- version string
- seq uint64
+ evidence string
+ offline *RuntimeOfflineReason
+ 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) {
+// markProvidersDemoted records a CONFIRMED verdict so a register response still
+// in flight cannot revive the provider. Callers must hold d.mu.
+func (d *Daemon) markProvidersDemotedLocked(providers map[string]runtimeVerdict) {
if len(providers) == 0 {
return
}
@@ -1574,9 +1643,53 @@ func (d *Daemon) markProvidersDemotedLocked(providers map[string]string) {
// 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}
+ for provider, verdict := range providers {
+ d.demotedProviders[provider] = demotionRecord{
+ evidence: verdict.reason,
+ offline: verdict.offline,
+ seq: d.demotionSeq,
+ }
+ }
+}
+
+// notExecutableConfirmWindow is how long a "the OS will not run this file"
+// verdict must keep reproducing before the daemon acts on it.
+//
+// The verdict itself is deterministic, but the file is not: the repair we tell
+// users to run (`node <pkg>/install.cjs`) overwrites the bin entry in place, and
+// a probe that lands mid-copy sees a truncated file. Requiring a second sighting
+// this far apart makes an overwrite window impossible to mistake for a broken
+// install, and costs a genuinely broken install only one extra probe round.
+// A var so tests can collapse the wait.
+var notExecutableConfirmWindow = time.Minute
+
+// confirmNotExecutable records that this round found provider unrunnable and
+// reports whether the verdict is now old enough to act on.
+//
+// The first sighting only starts the clock. Two sightings are required no matter
+// how the window is configured, so concurrent probe rounds — four callers reach
+// detectBuiltinRuntimes — cannot combine into an instant demotion.
+func (d *Daemon) confirmNotExecutable(provider string, now time.Time) bool {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ first, seen := d.notExecutableSince[provider]
+ if !seen {
+ if d.notExecutableSince == nil {
+ d.notExecutableSince = make(map[string]time.Time, 1)
+ }
+ d.notExecutableSince[provider] = now
+ return false
}
+ return now.Sub(first) >= notExecutableConfirmWindow
+}
+
+// clearNotExecutable forgets the pending verdict for a provider that probed OK,
+// so a later unrelated failure starts its own confirmation window instead of
+// inheriting a stale one.
+func (d *Daemon) clearNotExecutable(provider string) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ delete(d.notExecutableSince, provider)
}
// demotionSeqSnapshot returns the current demotion counter. A probe round takes
@@ -1614,13 +1727,13 @@ func (d *Daemon) clearProviderDemotions(providers []string, sampledAfter uint64)
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)
+ d.logger.Info("keeping demotion hold: this probe round started before the verdict",
+ "provider", provider, "verdict", record.evidence)
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)
+ d.logger.Info("agent CLI is usable again",
+ "provider", provider, "previous_verdict", record.evidence)
}
}
@@ -1679,7 +1792,7 @@ func (d *Daemon) reregisterWorkspaceAfterRuntimeGone(ctx context.Context, worksp
// 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")
+ d.deregisterDroppedRuntimes(ctx, workspaceID, droppedIDs, "runtime_gone recovery", nil)
return nil
})
if err != nil {
@@ -1917,7 +2030,7 @@ func (d *Daemon) deregisterRuntimes() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- if err := d.client.Deregister(ctx, runtimeIDs); err != nil {
+ if err := d.client.Deregister(ctx, runtimeIDs, nil); err != nil {
d.logger.Warn("failed to deregister runtimes on shutdown", "error", err)
} else {
d.logger.Info("deregistered runtimes", "count", len(runtimeIDs))
@@ -2056,25 +2169,67 @@ var runtimeVersionProbeRetryDelay = 500 * time.Millisecond
// Overridable for tests.
var runtimeVersionProbeRetryWindow = time.Second
-// builtinProbeVerdict distinguishes the two ways a provider can fail its probe,
+// builtinProbeVerdict distinguishes the 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.
+// whatever is registered alone and try again. The other two are confirmed
+// verdicts about a binary that is on disk right now, and leaving either
+// registered means the daemon keeps handing work to a CLI it has already proven
+// it cannot use: "read a version and it is below the minimum supported one",
+// and "the OS refuses to execute the file at all". Collapsing these into one
+// bool made a confirmed verdict indistinguishable from a hiccup, which is what
+// let a downgraded CLI keep claiming tasks.
type builtinProbeVerdict int
const (
builtinProbeOK builtinProbeVerdict = iota
builtinProbeUnavailable
builtinProbeBelowMinimum
+ // builtinProbeNotExecutable: the file resolved, but the OS rejected it as
+ // not a runnable program (an npm placeholder stub whose postinstall was
+ // blocked is the case in the field — MUL-6164). Deterministic in the same
+ // sense as below-minimum: the same bytes will be refused every time until
+ // someone reinstalls, so retrying is not what fixes it.
+ builtinProbeNotExecutable
)
+// runtimeVerdict is one provider's confirmed verdict: the human reason that
+// goes to /health and the daemon log, plus — when the cause is one the user has
+// to act on — the structured record the server stores on the runtime row.
+//
+// The two halves are deliberately separate. The reason is prose for an operator
+// reading logs; offline is a stable code plus a repair command for clients,
+// which localize their own sentence around it. dispatch/reason.go's rule is
+// that a reason code is decided at its source and never reverse-engineered from
+// a human-readable string, and this is that source.
+type runtimeVerdict struct {
+ reason string
+ offline *RuntimeOfflineReason
+}
+
+// newRuntimeVerdict pairs a probe verdict with what the server needs to know
+// about it. Only a verdict the user must repair carries an offline reason: a
+// below-minimum CLI keeps today's behaviour (the runtime goes offline and work
+// queues) because changing when THAT blocks a trigger is a separate product
+// decision from this one.
+//
+// execPath is the pinned entry point, which is the right path for this verdict:
+// a file the OS refuses to execute is present, so the self-heal that would have
+// re-resolved a vanished path never runs, and the probe failed on this exact
+// file.
+func newRuntimeVerdict(verdict builtinProbeVerdict, reason, execPath string) runtimeVerdict {
+ if verdict != builtinProbeNotExecutable {
+ return runtimeVerdict{reason: reason}
+ }
+ offline := &RuntimeOfflineReason{Code: RuntimeOfflineCodeNotExecutable, Detail: reason}
+ if repair, ok := agent.ExecFormatRepairFor(execPath); ok {
+ offline.Repair = &repair
+ }
+ return runtimeVerdict{reason: reason, offline: offline}
+}
+
// probeBuiltinRuntime resolves and version-detects one built-in provider,
// retrying a fast failure up to runtimeVersionProbeAttempts times. The verdict
// tells the caller how to treat a drop: builtinProbeUnavailable means the
@@ -2192,6 +2347,18 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
d.logger.Debug("agent version detected", "name", name, "version", version, "path", resolved.Path)
return version, "", builtinProbeOK
}
+ // The OS refusing to execute the file is not a failed probe, it is a
+ // finding: the CLI is installed, resolvable, and unrunnable. Report it as
+ // its own verdict so the caller can take the runtime offline instead of
+ // keeping it online for a binary that cannot start (MUL-6164). The
+ // diagnosis attached in pkg/agent rides along as the reason, so /health
+ // carries the repair command and not just the errno.
+ if agent.IsExecFormatError(lastErr) {
+ d.logger.Warn("skip registering runtime: agent CLI is not executable on this machine",
+ "name", name, "attempts", attempts, "error", lastErr)
+ return "", fmt.Sprintf("agent CLI is not executable: %v", lastErr), builtinProbeNotExecutable
+ }
+
d.logger.Warn("skip registering runtime", "name", name, "attempts", attempts, "error", lastErr)
reason := "version detection failed"
if lastErr != nil {
@@ -2225,8 +2392,8 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
// batch of workspaces at once calls this ONCE and passes the payload to
// registerRuntimesForWorkspaceBatch for each workspace (MUL-5225).
//
-// 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
+// The second return value is THIS round's confirmed verdicts, provider to the
+// evidence against it. 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
@@ -2242,7 +2409,7 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age
// 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) {
+func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string, map[string]runtimeVerdict, map[string]string) {
type detected struct {
name string
version string
@@ -2255,7 +2422,7 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string
mu sync.Mutex
results []detected
skipped = map[string]string{}
- belowMin = map[string]string{}
+ demotable = map[string]runtimeVerdict{}
unavailable = map[string]string{}
g errgroup.Group
)
@@ -2265,16 +2432,25 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string
g.Go(func() error {
version, reason, verdict := d.probeBuiltinRuntime(ctx, name, entry)
if verdict != builtinProbeOK {
+ // A not-executable verdict is deterministic, but the file can be
+ // unreadable for a moment while an installer overwrites it in
+ // place — which is exactly the repair we are telling users to
+ // run. Demote only once the verdict has survived a second probe
+ // a confirmation window later; until then it is treated as
+ // transient, which costs one more round and nothing else.
+ demote := verdict == builtinProbeBelowMinimum ||
+ (verdict == builtinProbeNotExecutable && d.confirmNotExecutable(name, time.Now()))
mu.Lock()
skipped[name] = reason
- if verdict == builtinProbeBelowMinimum {
- belowMin[name] = version
+ if demote {
+ demotable[name] = newRuntimeVerdict(verdict, reason, entry.Path)
} else {
unavailable[name] = reason
}
mu.Unlock()
return nil
}
+ d.clearNotExecutable(name)
mu.Lock()
results = append(results, detected{name: name, version: version})
mu.Unlock()
@@ -2320,7 +2496,7 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string
"status": "online",
})
}
- return runtimes, belowMin, unavailable
+ return runtimes, demotable, unavailable
}
// cloneRuntimeEntries deep-copies a registration runtime payload. Callers that
@@ -2370,29 +2546,30 @@ func (d *Daemon) registerRuntimesForWorkspaceLocked(ctx context.Context, workspa
// 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.
+// Demotable is the half that is easy to get wrong, because the verdict IS
+// confirmed — a version was read and rejected, or the OS refused to run the
+// file. What is missing on these paths is not the evidence but the authority to
+// act on it. Taking a runtime offline 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. demoteUnusableRuntimes 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
+// Preserving here costs at most one refresh tick of an unusable 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 {
+func preserveProvidersFromProbe(unavailable map[string]string, demotable map[string]runtimeVerdict) map[string]string {
+ if len(demotable) == 0 {
return unavailable
}
- preserve := make(map[string]string, len(unavailable)+len(belowMinimum))
+ preserve := make(map[string]string, len(unavailable)+len(demotable))
for provider, reason := range unavailable {
preserve[provider] = reason
}
- for provider, version := range belowMinimum {
- preserve[provider] = "below minimum supported version: " + version
+ for provider, verdict := range demotable {
+ preserve[provider] = verdict.reason
}
return preserve
}
@@ -3080,7 +3257,7 @@ func (d *Daemon) applyProfileDriftRegistration(ctx context.Context, workspaceID
// 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.
- d.deregisterDroppedRuntimes(ctx, workspaceID, droppedIDs, "profile drift")
+ d.deregisterDroppedRuntimes(ctx, workspaceID, droppedIDs, "profile drift", nil)
// Intentionally NO RecoverOrphans here: see method doc.
return nil
@@ -3144,7 +3321,7 @@ func (d *Daemon) convergeWorkspaceRuntimesToZero(ctx context.Context, workspaceI
"workspace_id", workspaceID, "deregistered_runtime_ids", dropped,
"preserved_providers", preserveProviders)
- d.deregisterDroppedRuntimes(ctx, workspaceID, dropped, "zero-runtime convergence")
+ d.deregisterDroppedRuntimes(ctx, workspaceID, dropped, "zero-runtime convergence", nil)
d.notifyRuntimeSetChanged()
return nil
}
@@ -3483,10 +3660,10 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
// below-minimum must not be the way that provider comes back.
d.mu.Lock()
runtimeIDs = make([]string, 0, len(resp.Runtimes))
- var revivedIDs []string
+ var revived revivedRuntimes
for _, rt := range resp.Runtimes {
if rt.ProfileID == "" && d.providerDemotedLocked(rt.Provider) {
- revivedIDs = append(revivedIDs, rt.ID)
+ revived.add(d, rt.ID, rt.Provider)
continue
}
runtimeIDs = append(runtimeIDs, rt.ID)
@@ -3525,7 +3702,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
// 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)
+ d.deregisterRevivedRuntimes(ctx, id, revived)
return nil
})
if err != nil {
diff --git a/server/internal/daemon/runtime_not_executable_test.go b/server/internal/daemon/runtime_not_executable_test.go
new file mode 100644
index 0000000000..d9b9c0ca83
--- /dev/null
+++ b/server/internal/daemon/runtime_not_executable_test.go
@@ -0,0 +1,309 @@
+package daemon
+
+import (
+ "context"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// stubNotExecutableProbe makes every version probe fail the way the OS fails a
+// file it will not execute — an npm placeholder stub whose postinstall was
+// blocked (MUL-6164) — wrapped exactly as detectCLIVersion wraps it, so the
+// daemon sees the same error shape it sees in the field.
+func stubNotExecutableProbe(t *testing.T, path string) {
+ t.Helper()
+ orig := detectAgentVersion
+ t.Cleanup(func() { detectAgentVersion = orig })
+ detectAgentVersion = func(_ context.Context, p string) (string, error) {
+ enoexec := &fs.PathError{Op: "fork/exec", Path: p, Err: syscall.ENOEXEC}
+ return "", fmt.Errorf("detect version for %s: %w", p, agent.ExplainExecError(enoexec))
+ }
+}
+
+// stubConfirmWindow collapses the confirmation window so a second probe round
+// counts as confirmation immediately. Two rounds are still required.
+func stubConfirmWindow(t *testing.T, window time.Duration) {
+ t.Helper()
+ orig := notExecutableConfirmWindow
+ t.Cleanup(func() { notExecutableConfirmWindow = orig })
+ notExecutableConfirmWindow = window
+}
+
+// npmPackagedCLI stages the layout an npm-installed agent CLI has — a bin entry
+// under a package whose manifest declares the postinstall that was supposed to
+// replace it — so the daemon can derive a real repair command from it.
+func npmPackagedCLI(t *testing.T) string {
+ t.Helper()
+ root := filepath.Join(t.TempDir(), "claude-code")
+ if err := os.MkdirAll(filepath.Join(root, "bin"), 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ manifest := `{"name":"@anthropic-ai/claude-code","scripts":{"postinstall":"node install.cjs"}}`
+ if err := os.WriteFile(filepath.Join(root, "package.json"), []byte(manifest), 0o644); err != nil {
+ t.Fatalf("write manifest: %v", err)
+ }
+ return filepath.Join(root, "bin", "claude.exe")
+}
+
+func notExecutableDaemon(t *testing.T) *Daemon {
+ t.Helper()
+ stubProbeRetry(t, time.Millisecond, time.Millisecond)
+ execPath := npmPackagedCLI(t)
+ stubNotExecutableProbe(t, execPath)
+ d := freshDaemon("")
+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: execPath, Command: "claude"}}
+ return d
+}
+
+// A CLI that cannot exec is a fact about the file on disk, so it must end up on
+// the demotable side of the probe rather than the transient one — that is what
+// takes the runtime offline instead of leaving it online to claim tasks it
+// cannot run. The first sighting still waits: an installer overwriting the bin
+// entry in place is briefly indistinguishable from a broken install.
+func TestDetectBuiltinRuntimes_NotExecutableDemotesOnlyAfterConfirmation(t *testing.T) {
+ stubConfirmWindow(t, 0)
+ d := notExecutableDaemon(t)
+
+ runtimes, demotable, unavailable := d.detectBuiltinRuntimes(context.Background())
+ if len(runtimes) != 0 {
+ t.Fatalf("registered %v, want none: the CLI cannot run", runtimes)
+ }
+ if _, ok := demotable["claude"]; ok {
+ t.Errorf("first sighting demoted %v, want it held for confirmation", demotable)
+ }
+ if _, ok := unavailable["claude"]; !ok {
+ t.Errorf("first sighting = %v, want claude treated as transient for one round", unavailable)
+ }
+
+ _, demotable, unavailable = d.detectBuiltinRuntimes(context.Background())
+ if _, ok := unavailable["claude"]; ok {
+ t.Errorf("second sighting = %v, want claude condemned, not held again", unavailable)
+ }
+ verdict, ok := demotable["claude"]
+ if !ok {
+ t.Fatalf("second sighting did not condemn claude: %v", demotable)
+ }
+ // The reason is what /health shows and what the demotion logs, so it has to
+ // carry the repair instructions, not just the errno.
+ for _, want := range []string{"not executable", "postinstall"} {
+ if !strings.Contains(verdict.reason, want) {
+ t.Errorf("reason is missing %q, so the user still cannot act on it:\n%s", want, verdict.reason)
+ }
+ }
+ // And the structured half the server stores: without a code the admission
+ // paths cannot tell this apart from a sleeping laptop.
+ if verdict.offline == nil || verdict.offline.Code != RuntimeOfflineCodeNotExecutable {
+ t.Fatalf("verdict carries no offline reason for the server: %+v", verdict.offline)
+ }
+ if verdict.offline.Repair == nil || !strings.Contains(verdict.offline.Repair.Command, "install.cjs") {
+ t.Errorf("offline reason lost the repair command: %+v", verdict.offline.Repair)
+ }
+}
+
+// Two probes inside the window are two samples of the same instant as far as
+// this verdict is concerned — an in-place install can span them.
+func TestDetectBuiltinRuntimes_NotExecutableWaitsOutTheWindow(t *testing.T) {
+ stubConfirmWindow(t, time.Hour)
+ d := notExecutableDaemon(t)
+
+ for round := 1; round <= 3; round++ {
+ _, demotable, _ := d.detectBuiltinRuntimes(context.Background())
+ if _, ok := demotable["claude"]; ok {
+ t.Fatalf("round %d demoted inside the confirmation window", round)
+ }
+ }
+}
+
+// The window is measured from the FIRST sighting, and a healthy probe resets it
+// — otherwise an unrelated failure months later would inherit a stale clock and
+// demote on its first sighting.
+func TestConfirmNotExecutable_WindowStartsAtFirstSighting(t *testing.T) {
+ stubConfirmWindow(t, time.Minute)
+ d := freshDaemon("")
+ start := time.Now()
+
+ if d.confirmNotExecutable("claude", start) {
+ t.Fatal("first sighting confirmed the verdict on its own")
+ }
+ if d.confirmNotExecutable("claude", start.Add(59*time.Second)) {
+ t.Error("confirmed before the window elapsed")
+ }
+ if !d.confirmNotExecutable("claude", start.Add(time.Minute)) {
+ t.Error("did not confirm after the window elapsed")
+ }
+
+ d.clearNotExecutable("claude")
+ if d.confirmNotExecutable("claude", start.Add(time.Hour)) {
+ t.Error("a recovered provider must start a fresh window, not inherit the old one")
+ }
+}
+
+// The user-visible half of the feature: once the verdict is confirmed, the
+// provider's runtimes actually go offline instead of staying online to claim
+// tasks that die at fork/exec — and they come back on their own after the
+// repair, without a daemon restart.
+func TestRefreshAgentVersions_TakesNotExecutableRuntimeOfflineAndBack(t *testing.T) {
+ stubConfirmWindow(t, 0)
+ fx := newVersionRefreshFixture(t)
+ d := fx.daemon
+
+ // npm blocks the postinstall on the next `npm i -g`: same path, same
+ // executable bit, a placeholder stub where the binary used to be.
+ fx.setProbeErr(func(path string, _ int) error {
+ enoexec := &fs.PathError{Op: "fork/exec", Path: path, Err: syscall.ENOEXEC}
+ return fmt.Errorf("detect version for %s: %w", path, agent.ExplainExecError(enoexec))
+ })
+
+ d.refreshAgentVersions(context.Background()) // first sighting: held
+ for _, workspaceID := range []string{"ws-1", "ws-2"} {
+ if got := registeredProviders(t, d, workspaceID); len(got) != 1 {
+ t.Fatalf("%s providers = %v, want codex still online during confirmation", workspaceID, got)
+ }
+ }
+
+ d.refreshAgentVersions(context.Background()) // confirmed: demote
+ for _, workspaceID := range []string{"ws-1", "ws-2"} {
+ if got := registeredProviders(t, d, workspaceID); len(got) != 0 {
+ t.Errorf("%s providers = %v, want none: the CLI cannot run, so the runtime must not keep claiming tasks", workspaceID, got)
+ }
+ }
+ if reason := d.skippedAgentsSnapshot()["codex"]; !strings.Contains(reason, "not executable") {
+ t.Errorf("/health reason = %q, want it to say why the runtime went offline", reason)
+ }
+
+ // The user runs the repair. Nothing restarts; the converge path re-registers.
+ fx.setProbeErr(nil)
+ 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 repair = %v, want [codex] back without a restart", workspaceID, got)
+ }
+ }
+}
+
+// A provider that probes OK again clears its pending verdict, which is what
+// makes recovery automatic: no runtime + no hold puts it back in
+// providersMissingRuntimes for the converge path to register.
+func TestDetectBuiltinRuntimes_HealthyProbeClearsPendingVerdict(t *testing.T) {
+ stubConfirmWindow(t, 0)
+ stubProbeRetry(t, time.Millisecond, time.Millisecond)
+ d := freshDaemon("")
+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/fake/claude", Command: "claude"}}
+
+ broken := true
+ orig := detectAgentVersion
+ t.Cleanup(func() { detectAgentVersion = orig })
+ detectAgentVersion = func(_ context.Context, p string) (string, error) {
+ if broken {
+ enoexec := &fs.PathError{Op: "fork/exec", Path: p, Err: syscall.ENOEXEC}
+ return "", fmt.Errorf("detect version for %s: %w", p, agent.ExplainExecError(enoexec))
+ }
+ return "2.1.231", nil
+ }
+
+ d.detectBuiltinRuntimes(context.Background()) // first sighting: clock starts
+ broken = false
+ if runtimes, _, _ := d.detectBuiltinRuntimes(context.Background()); len(runtimes) != 1 {
+ t.Fatalf("repaired CLI registered %v, want one runtime", runtimes)
+ }
+ broken = true
+ if _, demotable, _ := d.detectBuiltinRuntimes(context.Background()); len(demotable) != 0 {
+ t.Errorf("a fresh failure demoted immediately (%v): the healthy probe should have reset the clock", demotable)
+ }
+}
+
+// The verdict has to survive the server losing it.
+//
+// A register whose REQUEST is still in flight across the verdict is upserted
+// after it, and that upsert overwrites the runtime row's metadata wholesale —
+// including the reason the demotion just stored. The local hold correctly
+// refuses the response, but if the cleanup that takes the revived row offline
+// again sends no reason, the server is left with a bare "offline". Every
+// admission path then reads that as "the machine will come back" and goes right
+// back to queueing, which is the behaviour this change exists to remove
+// (MUL-6164).
+func TestDeregisterRevivedRuntimes_ReattachesTheUnusableReason(t *testing.T) {
+ stubConfirmWindow(t, 0)
+ // Stable ids before the first registration: the interleave only exists when
+ // the stale response names the same row the demotion took offline.
+ fx := newVersionRefreshFixtureWith(t, func(fx *batchFixture) { fx.enableStableRuntimeIDs() })
+ d := fx.daemon
+ runtimeID := fx.runtimeIDFor("ws-1", "codex")
+ if runtimeID == "" {
+ t.Fatal("fixture did not expose a stable runtime id")
+ }
+
+ // Hold ONE register inside the server handler, before it upserts. That is
+ // the request the verdict has to survive; every later register passes
+ // straight through.
+ var once sync.Once
+ reached, release := make(chan struct{}), make(chan struct{})
+ fx.setRegisterGate(func(string) {
+ once.Do(func() {
+ close(reached)
+ <-release
+ })
+ })
+
+ inFlight := []map[string]string{{"name": "Codex", "type": "codex", "version": "9.9.9", "status": "online"}}
+ respCh := make(chan *RegisterResponse, 1)
+ go func() {
+ resp, err := d.registerBuiltinRuntimesForWorkspaceLocked(context.Background(), "ws-1", inFlight)
+ if err != nil {
+ respCh <- nil
+ return
+ }
+ respCh <- resp
+ }()
+ <-reached
+
+ // While it is held: the CLI breaks and the verdict lands, reason and all.
+ fx.setProbeErr(func(path string, _ int) error {
+ enoexec := &fs.PathError{Op: "fork/exec", Path: path, Err: syscall.ENOEXEC}
+ return fmt.Errorf("detect version for %s: %w", path, agent.ExplainExecError(enoexec))
+ })
+ d.refreshAgentVersions(context.Background()) // first sighting
+ d.refreshAgentVersions(context.Background()) // confirmed: demote
+ if _, ok := fx.runtimeOfflineReason(runtimeID); !ok {
+ t.Fatal("demotion did not record a reason on the runtime row (precondition)")
+ }
+
+ // The held register now upserts, wiping the reason and putting the row back
+ // online — the loss this test exists for.
+ close(release)
+ staleResp := <-respCh
+ if staleResp == nil {
+ t.Fatal("in-flight register failed")
+ }
+ if _, ok := fx.runtimeOfflineReason(runtimeID); ok {
+ t.Fatal("precondition: the late upsert should have cleared the stored reason")
+ }
+
+ _, revived, ok := d.mergeBuiltinRegisterResponse("ws-1", staleResp)
+ if !ok {
+ t.Fatal("merge of the late register response failed")
+ }
+ if len(revived.ids) == 0 {
+ t.Fatal("late response was rejected locally but named no row to take offline again")
+ }
+
+ d.deregisterRevivedRuntimes(context.Background(), "ws-1", revived)
+
+ reason, ok := fx.runtimeOfflineReason(runtimeID)
+ if !ok {
+ t.Fatal("the revived row went offline with no reason: admission would treat an unusable CLI as a " +
+ "sleeping machine and queue for it again")
+ }
+ if reason.Code != RuntimeOfflineCodeNotExecutable {
+ t.Errorf("re-attached reason = %q, want %q", reason.Code, RuntimeOfflineCodeNotExecutable)
+ }
+}
diff --git a/server/internal/daemon/runtime_probe_batch_test.go b/server/internal/daemon/runtime_probe_batch_test.go
index 129fde5c9d..b4dadfb586 100644
--- a/server/internal/daemon/runtime_probe_batch_test.go
+++ b/server/internal/daemon/runtime_probe_batch_test.go
@@ -60,6 +60,10 @@ type batchFixture struct {
// 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
+ // offlineReasons is the server's view of WHY each row is offline. The
+ // register upsert overwrites it (see the register handler), which is what
+ // makes "the reason survived a late healthy register" testable.
+ offlineReasons map[string]RuntimeOfflineReason
// 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.
@@ -116,6 +120,16 @@ func (fx *batchFixture) runtimeIDFor(workspaceID, key string) string {
return fx.runtimeIDs[workspaceID+"|"+key]
}
+// runtimeOfflineReason returns the server's stored cause for a runtime row, or
+// false when the row carries none — which is what "offline for an unknown
+// reason" looks like to every admission path.
+func (fx *batchFixture) runtimeOfflineReason(id string) (RuntimeOfflineReason, bool) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ reason, ok := fx.offlineReasons[id]
+ return reason, ok
+}
+
// runtimeOnline reports the server's current status for a runtime row.
func (fx *batchFixture) runtimeOnline(id string) bool {
fx.mu.Lock()
@@ -382,6 +396,10 @@ func newBatchFixture(t *testing.T) *batchFixture {
}
}
fx.online[id] = true
+ // The real upsert overwrites metadata wholesale, so a register
+ // drops any recorded reason. This is the mechanism the revived-row
+ // cleanup has to compensate for.
+ delete(fx.offlineReasons, id)
resp.Runtimes = append(resp.Runtimes, Runtime{
ID: id,
Name: rt["name"],
@@ -396,7 +414,8 @@ func newBatchFixture(t *testing.T) *batchFixture {
_ = json.NewEncoder(w).Encode(resp)
case r.URL.Path == "/api/daemon/deregister":
var body struct {
- RuntimeIDs []string `json:"runtime_ids"`
+ RuntimeIDs []string `json:"runtime_ids"`
+ OfflineReasons map[string]RuntimeOfflineReason `json:"offline_reasons"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
fx.mu.Lock()
@@ -409,6 +428,15 @@ func newBatchFixture(t *testing.T) *batchFixture {
fx.deregistered = append(fx.deregistered, body.RuntimeIDs...)
for _, id := range body.RuntimeIDs {
fx.online[id] = false
+ // Mirror the server: the reason is stored on the runtime row, and
+ // a deregister without one leaves whatever was there — which is
+ // how the "revived then cleaned up" interleave loses it.
+ if reason, ok := body.OfflineReasons[id]; ok {
+ if fx.offlineReasons == nil {
+ fx.offlineReasons = make(map[string]RuntimeOfflineReason)
+ }
+ fx.offlineReasons[id] = reason
+ }
}
fx.mu.Unlock()
w.WriteHeader(http.StatusOK)
@@ -813,8 +841,14 @@ func TestDetectBuiltinRuntimes_SelfHealRejectionIsABelowMinimumVerdict(t *testin
// 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)
+ if !strings.Contains(belowMin["codex"].reason, "0.0.1") || !strings.Contains(belowMin["codex"].reason, "below minimum") {
+ t.Errorf("demotable verdict = %v, want codex condemned for being below minimum at 0.0.1", belowMin)
+ }
+ // Below-minimum keeps today's behaviour on the trigger paths: it takes the
+ // runtime offline but does not carry the "a human must repair this" code
+ // that refuses new work (MUL-6164 scoped that to the unusable verdict).
+ if belowMin["codex"].offline != nil {
+ t.Errorf("below-minimum verdict must not carry an offline reason: %+v", belowMin["codex"].offline)
}
// 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
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
index d08a5c7646..067ecff00d 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -31,6 +31,14 @@ const (
// that runtime is not online at dispatch time. The task is not lost — the
// user's fix is to bring the machine back, and queued work waits for it.
ReasonRuntimeOffline ReasonCode = "runtime_offline"
+ // ReasonRuntimeUnusable: the target is bound to a runtime whose machine is
+ // reachable, but whose agent CLI cannot be executed there — the npm
+ // placeholder stub left behind when a package's postinstall was blocked is
+ // the case in the field (MUL-6164). Distinct from runtime_offline for the
+ // same reason agent_runtime_required is: waiting changes nothing here. The
+ // machine is already on, and the fix is a command the user runs on it, which
+ // the daemon reports with this verdict so clients can show it.
+ ReasonRuntimeUnusable ReasonCode = "runtime_unusable"
// ReasonAgentRuntimeRequired: the target is permitted but bound to no
// runtime at all (agent.runtime_id IS NULL), which is where an agent lands
// when its runtime is deleted (MUL-5559). Distinct from runtime_offline on
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
index 7e864d4804..3887df7460 100644
--- a/server/internal/handler/admission.go
+++ b/server/internal/handler/admission.go
@@ -56,6 +56,7 @@ const (
ReasonInvocationNotAllowed = dispatch.ReasonInvocationNotAllowed
ReasonTargetUnavailable = dispatch.ReasonTargetUnavailable
ReasonRuntimeOffline = dispatch.ReasonRuntimeOffline
+ ReasonRuntimeUnusable = dispatch.ReasonRuntimeUnusable
ReasonAgentRuntimeRequired = dispatch.ReasonAgentRuntimeRequired
ReasonAttributionBlocked = dispatch.ReasonAttributionBlocked
ReasonAlreadyActive = dispatch.ReasonAlreadyActive
@@ -116,6 +117,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {
return "the target is unavailable"
case ReasonRuntimeOffline:
return "the target's runtime is offline"
+ case ReasonRuntimeUnusable:
+ return "the target's agent CLI cannot run on its machine"
case ReasonAgentRuntimeRequired:
return "the target needs a runtime"
case ReasonAttributionBlocked:
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 911fae765e..2fc284e83f 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -861,8 +861,11 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusConflict, "chat agent is archived")
return
}
- if !agent.RuntimeID.Valid {
- h.writeDispatchBlocked(w, http.StatusConflict, ReasonAgentRuntimeRequired)
+ // Shared verdict: an unbound agent and a machine whose CLI cannot run are
+ // both refusals here, with their own codes. A merely offline runtime is not
+ // checked at all — chat messages queue for it, as they always have.
+ if verdict, err := service.AgentReadiness(r.Context(), h.Queries, agent); err == nil && verdict.Blocked() {
+ h.writeDispatchBlocked(w, http.StatusConflict, verdict.Reason)
return
}
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index bf9a04e231..9b1bf16db6 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1963,10 +1963,37 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co
AutopilotDelegationAuthorityUserID: delegationAuthorityUserID,
})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
+ h.noteBlockedRuntimeTargets(ctx, issue, targets)
enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
return commentTriggerOutcomes(targets, enqueued)
}
+// noteBlockedRuntimeTargets leaves one system comment per agent refused for an
+// unusable runtime, whoever authored the trigger — see noteRuntimeUnusable for
+// why a human author gets one too. Deduped by agent so a comment naming both
+// @Agent and the squad it leads produces a single notice.
+//
+// Called from the trigger path only. The resolver that produced these targets
+// also runs for the composer preview, where writing a comment would be a side
+// effect of typing.
+func (h *Handler) noteBlockedRuntimeTargets(ctx context.Context, issue db.Issue, targets []commentMentionTarget) {
+ var noted map[string]struct{}
+ for _, t := range targets {
+ if t.unusable == nil {
+ continue
+ }
+ id := uuidToString(t.unusable.agent.ID)
+ if _, done := noted[id]; done {
+ continue
+ }
+ if noted == nil {
+ noted = make(map[string]struct{}, 1)
+ }
+ noted[id] = struct{}{}
+ h.noteRuntimeUnusable(ctx, issue, t.unusable.agent, t.unusable.verdict)
+ }
+}
+
func filterSuppressedCommentAgentTriggers(triggers []commentAgentTrigger, suppressAgentIDs []pgtype.UUID) []commentAgentTrigger {
if len(triggers) == 0 || len(suppressAgentIDs) == 0 {
return triggers
@@ -2952,6 +2979,18 @@ type commentMentionTarget struct {
ExecAgentID string
Status DispatchStatus
ReasonCode DispatchReasonCode
+ // unusable carries the refused agent and its verdict for the one reason
+ // that needs a durable trace (runtime_unusable). Internal to the handler:
+ // the resolver runs for the composer PREVIEW as well, so it only records
+ // what happened — writing the notice is the trigger path's job.
+ unusable *blockedRuntimeNotice
+}
+
+// blockedRuntimeNotice is a refusal worth leaving on the issue: which agent, and
+// the verdict that names the repair.
+type blockedRuntimeNotice struct {
+ agent db.Agent
+ verdict service.AgentVerdict
}
func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, mentions []util.Mention, authorType, authorID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, []commentMentionTarget) {
@@ -2997,6 +3036,20 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
blockTarget := func(targetType, targetID string, reason DispatchReasonCode) {
addTarget(commentMentionTarget{TargetType: targetType, TargetID: targetID, Status: DispatchBlocked, ReasonCode: reason})
}
+ // blockUnusableTarget is blockTarget for the one verdict that also needs a
+ // durable trace. Every author gets it, including a human: the chip and toast
+ // carry the reason code but not the repair command, and an agent-authored
+ // mention has nobody watching a response at all.
+ blockUnusableTarget := func(targetType, targetID string, agent db.Agent, verdict service.AgentVerdict) {
+ notice := &blockedRuntimeNotice{agent: agent, verdict: verdict}
+ if verdict.Reason != ReasonRuntimeUnusable {
+ notice = nil
+ }
+ addTarget(commentMentionTarget{
+ TargetType: targetType, TargetID: targetID,
+ Status: DispatchBlocked, ReasonCode: verdict.Reason, unusable: notice,
+ })
+ }
for _, m := range mentions {
if m.Type == "squad" {
// @squad mention → trigger the squad's leader agent.
@@ -3054,10 +3107,9 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
blockTarget("squad", m.ID, ReasonTargetUnavailable)
continue
}
- if !agent.RuntimeID.Valid {
- // Unbound, not offline: the leader survived its runtime's
- // deletion and needs a new one (MUL-5559).
- blockTarget("squad", m.ID, ReasonAgentRuntimeRequired)
+ // Same shared verdict as the direct-agent branch below.
+ if verdict, err := service.AgentReadiness(ctx, h.Queries, agent); err == nil && verdict.Blocked() {
+ blockUnusableTarget("squad", m.ID, agent, verdict)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)
@@ -3109,10 +3161,14 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
blockTarget("agent", m.ID, ReasonTargetUnavailable)
continue
}
- if !agent.RuntimeID.Valid {
- // Unbound, not offline: there is no machine to bring back, so the
- // user needs "bind a runtime", not "reconnect it" (MUL-5559).
- blockTarget("agent", m.ID, ReasonAgentRuntimeRequired)
+ // One readiness verdict for every admission path (service.AgentReadiness).
+ // Only a BLOCKED verdict refuses the mention: an unbound agent has no
+ // machine to bring back (MUL-5559), and a machine whose CLI cannot run
+ // will not start doing so on its own (MUL-6164). A merely offline
+ // runtime keeps queueing — that wait ends by itself when the machine
+ // returns, and taking it away would remove a behaviour people rely on.
+ if verdict, err := service.AgentReadiness(ctx, h.Queries, agent); err == nil && verdict.Blocked() {
+ blockUnusableTarget("agent", m.ID, agent, verdict)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index efa5b59705..381dfecef6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -890,10 +890,28 @@ func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos, ws.Settings))
}
+// setRuntimeOffline flips a runtime offline, recording the daemon's reason when
+// it sent one. An absent or unusable reason falls back to the plain offline
+// write: a malformed payload must never cost the caller the state change it
+// actually asked for.
+func (h *Handler) setRuntimeOffline(ctx context.Context, runtimeID pgtype.UUID, reason json.RawMessage) error {
+ if len(reason) > 0 && json.Valid(reason) {
+ return h.Queries.SetAgentRuntimeOfflineWithReason(ctx, db.SetAgentRuntimeOfflineWithReasonParams{
+ ID: runtimeID,
+ OfflineReason: reason,
+ })
+ }
+ return h.Queries.SetAgentRuntimeOffline(ctx, runtimeID)
+}
+
// DaemonDeregister marks runtimes as offline when the daemon shuts down.
func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {
var req struct {
RuntimeIDs []string `json:"runtime_ids"`
+ // OfflineReasons is optional and keyed by runtime id. Present only for
+ // causes the user must repair — a daemon shutting down sends none, so an
+ // older daemon simply keeps today's behaviour (MUL-6164).
+ OfflineReasons map[string]json.RawMessage `json:"offline_reasons"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -926,7 +944,7 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {
continue
}
- if err := h.Queries.SetAgentRuntimeOffline(r.Context(), rt.ID); err != nil {
+ if err := h.setRuntimeOffline(r.Context(), rt.ID, req.OfflineReasons[rid]); err != nil {
slog.Warn("deregister: failed to set offline", "runtime_id", rid, "error", err)
continue
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 1bbf2818bd..c17105389a 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2220,12 +2220,15 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "agent not found")
return
}
- if !agent.RuntimeID.Valid {
- writeAgentUnavailable(w, "agent has no runtime", ReasonAgentRuntimeRequired)
+ // Quick-create needs the agent to run NOW, so any non-ready verdict refuses
+ // — but with the verdict's own code, so "CLI cannot run" no longer arrives
+ // as "runtime is offline" and sends the user to reconnect a machine that is
+ // already connected (MUL-6164).
+ if verdict, err := service.AgentReadiness(r.Context(), h.Queries, agent); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check agent runtime")
return
- }
- if !h.isRuntimeOnline(r.Context(), agent.RuntimeID) {
- writeAgentUnavailable(w, "agent's runtime is offline", ReasonRuntimeOffline)
+ } else if !verdict.Ready() {
+ writeAgentUnavailable(w, verdict.Detail, verdict.Reason)
return
}
@@ -3341,11 +3344,24 @@ func (h *Handler) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool
}
agent, err := h.Queries.GetAgent(ctx, issue.AssigneeID)
- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ if err != nil {
return false
}
-
- return true
+ // The shared verdict, not a local re-check (service.AgentReadiness). Only a
+ // BLOCKED verdict stops the enqueue: an offline machine still queues,
+ // because that work runs when the machine comes back.
+ verdict, err := service.AgentReadiness(ctx, h.Queries, agent)
+ if err != nil || !verdict.Blocked() {
+ return err == nil
+ }
+ // Assignment has no response the assigner reads for this outcome, so a
+ // refusal that needs human repair leaves the explanation on the issue
+ // (MUL-6164). An unbound agent keeps its silent skip: the agent list
+ // already shows it has no runtime, and nothing about it is new here.
+ if verdict.Reason == ReasonRuntimeUnusable {
+ h.noteRuntimeUnusable(ctx, issue, agent, verdict)
+ }
+ return false
}
func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/handler/runtime_unusable_notice.go b/server/internal/handler/runtime_unusable_notice.go
new file mode 100644
index 0000000000..f4fc3c78d7
--- /dev/null
+++ b/server/internal/handler/runtime_unusable_notice.go
@@ -0,0 +1,52 @@
+package handler
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// noteRuntimeUnusable records, on the issue itself, that a trigger was refused
+// because the target's agent CLI cannot run on its machine.
+//
+// Written for EVERY author, not only the unattended ones. The composer chip and
+// the post-send toast do reach whoever was typing, but they carry the reason
+// code alone — the repair command is too long for a chip and too important to
+// put in something that disappears. An agent-authored @mention has nobody
+// watching a response at all. So both get the same durable record, and the
+// transient surfaces stay a preview of it rather than the only copy (MUL-6164).
+//
+// Best-effort by construction: the refusal already happened and is correct
+// whether or not this note lands, so a failure here is logged, never returned.
+func (h *Handler) noteRuntimeUnusable(ctx context.Context, issue db.Issue, agent db.Agent, verdict service.AgentVerdict) {
+ content := service.RuntimeUnusableNotice(agent.Name, verdict)
+ // author_type='system', author_id=zero UUID — same shape as the sub-issue
+ // completion notice; clients branch on author_type, not the UUID value.
+ comment, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ AuthorType: "system",
+ AuthorID: pgtype.UUID{Valid: true},
+ Content: content,
+ Type: "system",
+ ParentID: pgtype.UUID{Valid: false},
+ })
+ if err != nil {
+ slog.Warn("runtime unusable notice: create system comment failed",
+ "error", err,
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(agent.ID))
+ return
+ }
+ h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), "system", "", map[string]any{
+ "comment": commentToResponse(comment, nil, nil),
+ "issue_title": issue.Title,
+ "issue_assignee_type": textToPtr(issue.AssigneeType),
+ "issue_assignee_id": uuidToPtr(issue.AssigneeID),
+ "issue_status": issue.Status,
+ })
+}
diff --git a/server/internal/service/agent_ready.go b/server/internal/service/agent_ready.go
index 92d70e3695..f548a79a6c 100644
--- a/server/internal/service/agent_ready.go
+++ b/server/internal/service/agent_ready.go
@@ -2,14 +2,85 @@ package service
import (
"context"
+ "encoding/json"
+ "fmt"
+ "github.com/multica-ai/multica/server/internal/dispatch"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// AgentReadiness reports whether an agent can accept new work right now.
-// "Ready" means archived_at IS NULL, runtime_id IS NOT NULL, and the bound
-// runtime's status is 'online'. When not ready, reason describes which gate
-// failed in language suitable for autopilot_run.failure_reason.
+// AgentAvailability is what a readiness check concluded, in the vocabulary the
+// callers actually branch on.
+//
+// The distinction that matters is not "ready or not" but whether WAITING is a
+// plan. A sleeping laptop comes back on its own, so queued work is right to
+// wait for it; an agent bound to nothing, or bound to a machine whose CLI
+// cannot run, will never pick that work up until a human acts. dispatch's
+// reason codes already draw that line — this type is the server-side half so
+// every admission path draws it the same way.
+type AgentAvailability int
+
+const (
+ // AgentAvailable: the agent can take work now.
+ AgentAvailable AgentAvailability = iota
+ // AgentWaitable: not runnable right now, but nothing is broken — the
+ // machine is offline and work queued for it runs when it returns.
+ AgentWaitable
+ // AgentBlocked: nothing will claim this agent's work until someone
+ // intervenes. Callers must refuse the trigger and say why.
+ AgentBlocked
+)
+
+// AgentVerdict is a readiness decision plus everything a caller needs to act on
+// it: the wire reason code, and — when the daemon reported one — the command
+// that repairs the runtime.
+type AgentVerdict struct {
+ Availability AgentAvailability
+ // Reason is the dispatch code for a non-available verdict, empty otherwise.
+ Reason dispatch.ReasonCode
+ // Repair is the fix the daemon reported for an unusable runtime: the npm
+ // package that owns the broken entry point and the command that reinstalls
+ // it. Absent for every other verdict, and for a runtime whose daemon is too
+ // old to report one.
+ Repair *RuntimeRepair
+ // Detail is the daemon's own description, for logs and for the record left
+ // on a blocked non-interactive trigger. Never parsed.
+ Detail string
+}
+
+// Ready reports whether the agent can take work right now.
+func (v AgentVerdict) Ready() bool { return v.Availability == AgentAvailable }
+
+// Blocked reports whether waiting is futile and the caller must refuse the
+// trigger rather than queue it.
+func (v AgentVerdict) Blocked() bool { return v.Availability == AgentBlocked }
+
+// RuntimeRepair mirrors the daemon's agent.ExecFormatRepair over the wire.
+type RuntimeRepair struct {
+ Package string `json:"package,omitempty"`
+ Command string `json:"command,omitempty"`
+ // Shell is the interpreter Command is written for, as reported by the
+ // machine that must run it ("bash", "powershell"). Rendered as the code
+ // block's language so a Windows user is not handed POSIX syntax in a bash
+ // fence. Empty from a daemon too old to report it.
+ Shell string `json:"shell,omitempty"`
+}
+
+// runtimeOfflineReason is the daemon's structured explanation, stored on the
+// runtime row's metadata by the deregister handler.
+type runtimeOfflineReason struct {
+ Code string `json:"code"`
+ Detail string `json:"detail"`
+ Repair *RuntimeRepair `json:"repair"`
+}
+
+// runtimeOfflineCodeNotExecutable is the daemon's code for "the OS refuses to
+// execute this agent CLI" (daemon.RuntimeOfflineCodeNotExecutable). Compared as
+// a string because the server must not import the daemon package.
+const runtimeOfflineCodeNotExecutable = "not_executable"
+
+// AgentReadiness reports whether an agent can accept new work right now, and
+// what the caller should do when it cannot.
//
// err is non-nil only on DB lookup failure for the runtime row. Callers that
// treat a transient DB error as "do not skip" (the autopilot admission gate)
@@ -20,24 +91,110 @@ import (
// - service.shouldSkipDispatch (autopilot admission gate)
// - service.dispatchRunOnly (squad-leader runtime check, MUL-2429)
// - handler.isSquadLeaderReady (issue-assign / comment-trigger path)
+// - the direct-agent trigger paths, which consult it for the BLOCKED verdict
+// only: an offline machine still queues, because that wait ends by itself.
//
-// Keeping these aligned matters because the three paths can otherwise drift
-// — e.g. one starts allowing "starting" runtimes while another doesn't, and
-// the bug only surfaces when a user assigns the same squad through two
-// different entry points. Touch this function, all three paths move together.
-func AgentReadiness(ctx context.Context, q *db.Queries, agent db.Agent) (ready bool, reason string, err error) {
+// Keeping these aligned matters because the paths can otherwise drift — e.g.
+// one starts allowing "starting" runtimes while another doesn't, and the bug
+// only surfaces when a user assigns the same agent through two different entry
+// points. Touch this function, all of them move together.
+func AgentReadiness(ctx context.Context, q *db.Queries, agent db.Agent) (AgentVerdict, error) {
if agent.ArchivedAt.Valid {
- return false, "agent is archived", nil
+ return AgentVerdict{
+ Availability: AgentBlocked,
+ Reason: dispatch.ReasonTargetUnavailable,
+ Detail: "agent is archived",
+ }, nil
}
if !agent.RuntimeID.Valid {
- return false, "agent has no runtime bound", nil
+ return AgentVerdict{
+ Availability: AgentBlocked,
+ Reason: dispatch.ReasonAgentRuntimeRequired,
+ Detail: "agent has no runtime bound",
+ }, nil
}
rt, err := q.GetAgentRuntime(ctx, agent.RuntimeID)
if err != nil {
- return false, "", err
+ return AgentVerdict{}, err
+ }
+ return runtimeVerdict(rt), nil
+}
+
+// runtimeVerdict is the half of the decision that depends only on the runtime
+// row, split out so every branch is testable without a database.
+func runtimeVerdict(rt db.AgentRuntime) AgentVerdict {
+ if rt.Status == "online" {
+ return AgentVerdict{Availability: AgentAvailable}
+ }
+ // Offline with a reason the daemon says a human must repair: refuse rather
+ // than queue, and carry the repair so the caller can show it.
+ if reason, ok := parseRuntimeOfflineReason(rt.Metadata); ok && reason.Code == runtimeOfflineCodeNotExecutable {
+ return AgentVerdict{
+ Availability: AgentBlocked,
+ Reason: dispatch.ReasonRuntimeUnusable,
+ Repair: reason.Repair,
+ Detail: reason.Detail,
+ }
+ }
+ return AgentVerdict{
+ Availability: AgentWaitable,
+ Reason: dispatch.ReasonRuntimeOffline,
+ Detail: "agent runtime is " + rt.Status,
+ }
+}
+
+// parseRuntimeOfflineReason reads the daemon's explanation off a runtime row.
+// A row with no reason, or metadata this server cannot parse, simply has no
+// explanation — never a different verdict.
+func parseRuntimeOfflineReason(metadata []byte) (runtimeOfflineReason, bool) {
+ if len(metadata) == 0 {
+ return runtimeOfflineReason{}, false
+ }
+ var envelope struct {
+ OfflineReason *runtimeOfflineReason `json:"offline_reason"`
+ }
+ if err := json.Unmarshal(metadata, &envelope); err != nil || envelope.OfflineReason == nil {
+ return runtimeOfflineReason{}, false
}
- if rt.Status != "online" {
- return false, "agent runtime is " + rt.Status, nil
+ return *envelope.OfflineReason, true
+}
+
+// RuntimeUnusableNotice is the durable explanation left on an issue when a
+// trigger is refused because the target's agent CLI cannot run on its machine.
+//
+// It lives here, next to the verdict, because two layers write it: the handler
+// for a refused @mention and the service for a refused assignment. One text,
+// one place to fix it. It names the repair command when the daemon reported
+// one and stays useful when it did not — a natively installed CLI has no
+// postinstall to re-run, and inventing a command would send the user somewhere
+// that does not exist.
+func RuntimeUnusableNotice(agentName string, verdict AgentVerdict) string {
+ name := agentName
+ if name == "" {
+ name = "The assigned agent"
+ }
+ if verdict.Repair != nil && verdict.Repair.Command != "" {
+ return fmt.Sprintf(
+ "%s could not start: its CLI is installed but cannot be executed on that machine, so this trigger was not queued.\n\n"+
+ "Usually the package's postinstall was blocked (npm 12 allowScripts, pnpm 10 approve-builds, `--ignore-scripts`, `--omit=optional`) and the bin entry is still a placeholder. On that machine, run:\n\n"+
+ "```%s\n%s\n```\n\n"+
+ "The runtime comes back on its own within a couple of minutes; trigger the agent again after that.",
+ name, repairFenceLanguage(verdict.Repair.Shell), verdict.Repair.Command,
+ )
+ }
+ return fmt.Sprintf(
+ "%s could not start: its CLI is installed but cannot be executed on that machine, so this trigger was not queued. "+
+ "Reinstall the agent CLI on that machine with install scripts enabled; the runtime comes back on its own within a couple of minutes.",
+ name,
+ )
+}
+
+// repairFenceLanguage labels the code block with the shell the command was
+// written for. A daemon too old to report one predates the Windows rendering
+// entirely, so its command is POSIX by construction.
+func repairFenceLanguage(shell string) string {
+ if shell == "powershell" {
+ return "powershell"
}
- return true, "", nil
+ return "bash"
}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 874923025f..2309a38693 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -868,12 +868,12 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
}
return fmt.Errorf("resolve leader: %w", err)
}
- ready, reason, err := AgentReadiness(ctx, s.Queries, agent)
+ verdict, err := AgentReadiness(ctx, s.Queries, agent)
if err != nil {
return fmt.Errorf("check agent readiness: %w", err)
}
- if !ready {
- return &errDispatchSkipped{reason: formatAdmissionReason(ap, reason), code: agentReadinessReasonCode(agent)}
+ if !verdict.Ready() {
+ return &errDispatchSkipped{reason: formatAdmissionReason(ap, verdict.Detail), code: verdict.Reason}
}
// Fail-closed invocation gate for squad autopilots (admission principal =
@@ -1221,7 +1221,7 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
// chance to succeed.
return "", "", false
}
- ready, reason, err := AgentReadiness(ctx, s.Queries, agent)
+ verdict, err := AgentReadiness(ctx, s.Queries, agent)
if err != nil {
slog.Warn("autopilot admission: failed to load runtime",
"autopilot_id", util.UUIDToString(ap.ID),
@@ -1230,15 +1230,19 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
)
return "", "", false
}
- if !ready {
- if ap.ExecutionMode == "create_issue" && strings.HasPrefix(reason, "agent runtime is ") {
+ if !verdict.Ready() {
+ // A merely-offline machine still gets create_issue work: the issue is
+ // written server-side and the run waits for the laptop to come back. An
+ // unusable runtime does not qualify — nothing there can run until a
+ // human repairs it, so a doomed issue-create is not an improvement.
+ if ap.ExecutionMode == "create_issue" && verdict.Availability == AgentWaitable {
slog.Info("autopilot admission: allowing create_issue dispatch for offline runtime",
"autopilot_id", util.UUIDToString(ap.ID),
"runtime_id", util.UUIDToString(agent.RuntimeID),
- "reason", reason,
+ "reason", verdict.Detail,
)
} else {
- return formatAdmissionReason(ap, reason), agentReadinessReasonCode(agent), true
+ return formatAdmissionReason(ap, verdict.Detail), verdict.Reason, true
}
}
// Invocation gate at the autopilot layer (MUL-3963 / MUL-4525). The
@@ -1259,23 +1263,6 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
return "", "", false
}
-// agentReadinessReasonCode types the reason an AgentReadiness check failed from
-// the agent's own state rather than the human-readable reason string (MUL-4525).
-// An archived agent cannot run at all; anything else (no runtime bound, or a
-// bound runtime that is not online) is a runtime-availability problem.
-func agentReadinessReasonCode(agent db.Agent) dispatch.ReasonCode {
- if agent.ArchivedAt.Valid {
- return dispatch.ReasonTargetUnavailable
- }
- // No runtime bound at all is a different user story from a runtime that is
- // merely offline: nothing will ever pick the work up, and the fix is to bind
- // the agent to a runtime (MUL-5559).
- if !agent.RuntimeID.Valid {
- return dispatch.ReasonAgentRuntimeRequired
- }
- return dispatch.ReasonRuntimeOffline
-}
-
// formatAdmissionReason rewrites the generic AgentReadiness reason into the
// admission-gate phrasing the failure monitor and existing alerting are tuned
// for. Keeping the prefix stable matters: dashboards group skip reasons by
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 6bac136339..3d82db73ac 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/dispatch"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/issueposition"
@@ -582,7 +583,21 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,
if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {
return pgtype.UUID{}
}
- if s.shouldEnqueueAgentTask(ctx, issue) {
+ // Backlog is the parking lot: nothing runs from it, so nothing here needs
+ // explaining either.
+ if issue.Status == "backlog" {
+ return pgtype.UUID{}
+ }
+ verdict, admitted := agentAssigneeVerdict(ctx, s.Queries, issue)
+ if !admitted && verdict.Reason == dispatch.ReasonRuntimeUnusable {
+ // Assignment has no response the assigner reads for this outcome, so the
+ // refusal explains itself on the issue instead of vanishing (MUL-6164).
+ // Only here, not in the create-with-assignee path above: that one runs
+ // inside the issue's transaction, and a notice about a machine has no
+ // business deciding whether the issue itself commits.
+ s.noteRuntimeUnusable(ctx, issue, verdict)
+ }
+ if admitted {
var task db.AgentTaskQueue
var err error
if agentRunFireAt.IsZero() {
@@ -604,15 +619,15 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,
return pgtype.UUID{}
}
-// shouldEnqueueAgentTask returns true when an issue create or assignment
-// should trigger the assigned agent. Backlog issues are skipped — backlog
-// acts as a parking lot for pre-assigning without immediate execution.
+// shouldEnqueueAgentTaskWithQueries returns true when an issue create should
+// trigger the assigned agent. Backlog issues are skipped — backlog acts as a
+// parking lot for pre-assigning without immediate execution. The assignment
+// path does the same test through agentAssigneeVerdict, which also tells it
+// WHY a refusal happened; this one runs inside the create transaction, where
+// there is nothing to tell anyone yet.
+//
// Mirrors handler.shouldEnqueueAgentTask; kept here to make the service
// self-contained, since both code paths must move together.
-func (s *IssueService) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {
- return s.shouldEnqueueAgentTaskWithQueries(ctx, s.Queries, issue)
-}
-
func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {
if issue.Status == "backlog" {
return false
@@ -621,14 +636,29 @@ func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q
}
func isAgentAssigneeReadyWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {
+ _, ok := agentAssigneeVerdict(ctx, q, issue)
+ return ok
+}
+
+// agentAssigneeVerdict resolves the issue's agent assignee through the shared
+// readiness check and reports whether work may be enqueued for it, plus the
+// verdict when it may not.
+//
+// Only a BLOCKED verdict stops the enqueue. A merely offline machine still
+// queues: that work runs when the laptop comes back, and people rely on it.
+func agentAssigneeVerdict(ctx context.Context, q *db.Queries, issue db.Issue) (AgentVerdict, bool) {
if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {
- return false
+ return AgentVerdict{}, false
}
agent, err := q.GetAgent(ctx, issue.AssigneeID)
- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
- return false
+ if err != nil {
+ return AgentVerdict{}, false
+ }
+ verdict, err := AgentReadiness(ctx, q, agent)
+ if err != nil {
+ return AgentVerdict{}, false
}
- return true
+ return verdict, !verdict.Blocked()
}
func (s *IssueService) shouldEnqueueSquadLeaderOnAssign(ctx context.Context, issue db.Issue) bool {
@@ -653,11 +683,11 @@ func (s *IssueService) isSquadLeaderReady(ctx context.Context, issue db.Issue) b
if err != nil {
return false
}
- ready, _, err := AgentReadiness(ctx, s.Queries, agent)
+ verdict, err := AgentReadiness(ctx, s.Queries, agent)
if err != nil {
return false
}
- return ready
+ return verdict.Ready()
}
func (s *IssueService) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID string) {
diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.go
index 057e04d55e..b2734a6088 100644
--- a/server/internal/service/issue_trigger.go
+++ b/server/internal/service/issue_trigger.go
@@ -162,8 +162,8 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,
if err != nil {
return IssueRunTrigger{}, false
}
- ready, _, err := AgentReadiness(ctx, s.Queries, leader)
- if err != nil || !ready {
+ verdict, err := AgentReadiness(ctx, s.Queries, leader)
+ if err != nil || !verdict.Ready() {
return IssueRunTrigger{}, false
}
if !canAccess(leader) {
diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.go
index 4e3aea88cd..d6937435b7 100644
--- a/server/internal/service/reason_code_test.go
+++ b/server/internal/service/reason_code_test.go
@@ -3,6 +3,7 @@ package service
import (
"errors"
"fmt"
+ "strings"
"testing"
"github.com/jackc/pgx/v5/pgtype"
@@ -29,27 +30,92 @@ func TestDispatchFailReasonCode(t *testing.T) {
}
}
-// TestAgentReadinessReasonCode is the regression for Elon must-fix 2, case 2: a
-// runtime-availability failure must be classified from the agent's own state,
-// not from the reason text. Since MUL-5559 the two runtime failures are
-// deliberately distinct: an agent with NO runtime needs to be bound to one
-// (agent_runtime_required), while a bound-but-offline runtime needs the machine
-// back (runtime_offline). Collapsing them sends the user looking for a computer
-// that does not exist.
-func TestAgentReadinessReasonCode(t *testing.T) {
+// TestAgentReadinessVerdict is the regression for Elon must-fix 2, case 2: a
+// runtime-availability failure must be classified from the agent's and
+// runtime's own state, not from the reason text. The three runtime failures are
+// deliberately distinct — an agent with NO runtime needs to be bound to one
+// (agent_runtime_required); a bound-but-offline runtime needs the machine back
+// (runtime_offline); a runtime whose CLI cannot be executed needs a reinstall
+// on a machine that is already connected (runtime_unusable, MUL-6164).
+// Collapsing any pair sends the user to fix the wrong thing.
+func TestAgentReadinessVerdict(t *testing.T) {
validRuntime := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
archivedAt := pgtype.Timestamptz{Valid: true}
- // No runtime bound — the state an agent lands in when its runtime is deleted.
- if got := agentReadinessReasonCode(db.Agent{}); got != dispatch.ReasonAgentRuntimeRequired {
- t.Errorf("no runtime bound: got %q, want agent_runtime_required", got)
+ // The agent-only half needs no runtime row, so AgentReadiness answers before
+ // it queries one.
+ if got, _ := AgentReadiness(t.Context(), nil, db.Agent{}); got.Reason != dispatch.ReasonAgentRuntimeRequired || !got.Blocked() {
+ t.Errorf("no runtime bound: got %+v, want blocked/agent_runtime_required", got)
}
- // Bound runtime that is offline at dispatch time.
- if got := agentReadinessReasonCode(db.Agent{RuntimeID: validRuntime}); got != dispatch.ReasonRuntimeOffline {
- t.Errorf("bound offline runtime: got %q, want runtime_offline", got)
+ if got, _ := AgentReadiness(t.Context(), nil, db.Agent{ArchivedAt: archivedAt, RuntimeID: validRuntime}); got.Reason != dispatch.ReasonTargetUnavailable || !got.Blocked() {
+ t.Errorf("archived agent: got %+v, want blocked/target_unavailable", got)
}
- // Archived agent cannot run at all.
- if got := agentReadinessReasonCode(db.Agent{ArchivedAt: archivedAt, RuntimeID: validRuntime}); got != dispatch.ReasonTargetUnavailable {
- t.Errorf("archived agent: got %q, want target_unavailable", got)
+
+ // The runtime half.
+ if got := runtimeVerdict(db.AgentRuntime{Status: "online"}); !got.Ready() {
+ t.Errorf("online runtime: got %+v, want ready", got)
+ }
+ // Offline with no explanation is the sleeping-laptop case: work waits for it,
+ // so this must NOT be blocked.
+ offline := runtimeVerdict(db.AgentRuntime{Status: "offline"})
+ if offline.Blocked() || offline.Reason != dispatch.ReasonRuntimeOffline {
+ t.Errorf("plain offline runtime: got %+v, want waitable/runtime_offline", offline)
+ }
+ // Offline because the CLI cannot be executed: waiting is futile, and the
+ // repair the daemon reported has to survive to the caller — it is the only
+ // thing that tells the user what to actually do.
+ unusable := runtimeVerdict(db.AgentRuntime{
+ Status: "offline",
+ Metadata: []byte(`{"offline_reason":{"code":"not_executable","detail":"agent CLI is not executable","repair":{"package":"@anthropic-ai/claude-code","command":"cd '/pkg' && node install.cjs"}}}`),
+ })
+ if !unusable.Blocked() || unusable.Reason != dispatch.ReasonRuntimeUnusable {
+ t.Fatalf("unusable runtime: got %+v, want blocked/runtime_unusable", unusable)
+ }
+ if unusable.Repair == nil || unusable.Repair.Command != "cd '/pkg' && node install.cjs" {
+ t.Errorf("unusable runtime lost the repair command: got %+v", unusable.Repair)
+ }
+ // An unrecognised or malformed reason must not invent a verdict: unknown
+ // causes stay in the waitable bucket they are in today.
+ for name, metadata := range map[string]string{
+ "unknown code": `{"offline_reason":{"code":"who_knows"}}`,
+ "malformed": `{"offline_reason":`,
+ "empty": ``,
+ } {
+ got := runtimeVerdict(db.AgentRuntime{Status: "offline", Metadata: []byte(metadata)})
+ if got.Blocked() {
+ t.Errorf("%s: got %+v, want the plain offline verdict", name, got)
+ }
+ }
+}
+
+// The notice is the only thing a user sees when an assignment or an
+// agent-authored mention is refused, so it has to carry the repair command when
+// there is one and stay actionable when there is not.
+func TestRuntimeUnusableNotice(t *testing.T) {
+ withRepair := RuntimeUnusableNotice("Mika", AgentVerdict{
+ Repair: &RuntimeRepair{Package: "@anthropic-ai/claude-code", Command: "cd '/pkg' && node install.cjs"},
+ })
+ if !strings.Contains(withRepair, "Mika") || !strings.Contains(withRepair, "cd '/pkg' && node install.cjs") {
+ t.Errorf("notice must name the agent and the repair command:\n%s", withRepair)
+ }
+ // The fence is labelled with the shell the command was written for: a
+ // Windows repair shown as bash is how a user ends up pasting `cd 'C:\...'`
+ // into PowerShell.
+ if !strings.Contains(withRepair, "```bash") {
+ t.Errorf("a bash repair must be fenced as bash:\n%s", withRepair)
+ }
+ windows := RuntimeUnusableNotice("Mika", AgentVerdict{
+ Repair: &RuntimeRepair{Command: "Set-Location 'C:\\pkg'\nnode install.cjs", Shell: "powershell"},
+ })
+ if !strings.Contains(windows, "```powershell") {
+ t.Errorf("a PowerShell repair must be fenced as powershell:\n%s", windows)
+ }
+
+ withoutRepair := RuntimeUnusableNotice("Mika", AgentVerdict{})
+ if strings.Contains(withoutRepair, "```") {
+ t.Errorf("no repair command is known, so none may be shown:\n%s", withoutRepair)
+ }
+ if !strings.Contains(withoutRepair, "Reinstall") {
+ t.Errorf("notice must still say what to do:\n%s", withoutRepair)
}
}
diff --git a/server/internal/service/runtime_unusable_notice.go b/server/internal/service/runtime_unusable_notice.go
new file mode 100644
index 0000000000..7a87458e57
--- /dev/null
+++ b/server/internal/service/runtime_unusable_notice.go
@@ -0,0 +1,64 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// noteRuntimeUnusable leaves the refusal on the issue when an assignment cannot
+// be enqueued because the assignee's agent CLI cannot run on its machine.
+//
+// Assignment is the trigger with no reply anyone reads: the API returns the
+// updated issue, and nothing in it says "and by the way, nothing will run".
+// Without this the user gets exactly the silence this change exists to remove
+// (MUL-6164).
+//
+// Best-effort: the refusal is correct whether or not the note lands, so a
+// failure here is logged rather than returned.
+func (s *IssueService) noteRuntimeUnusable(ctx context.Context, issue db.Issue, verdict AgentVerdict) {
+ name := ""
+ if agent, err := s.Queries.GetAgent(ctx, issue.AssigneeID); err == nil {
+ name = agent.Name
+ }
+ // author_type='system', author_id=zero UUID. The zero UUID is a valid 16
+ // byte value and the column is NOT NULL; clients branch on author_type.
+ comment, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ AuthorType: "system",
+ AuthorID: pgtype.UUID{Valid: true},
+ Content: RuntimeUnusableNotice(name, verdict),
+ Type: "system",
+ ParentID: pgtype.UUID{Valid: false},
+ })
+ if err != nil {
+ slog.Warn("runtime unusable notice: create system comment failed",
+ "error", err, "issue_id", util.UUIDToString(issue.ID))
+ return
+ }
+ if s.Bus == nil {
+ return
+ }
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventCommentCreated,
+ WorkspaceID: util.UUIDToString(issue.WorkspaceID),
+ ActorType: "system",
+ Payload: map[string]any{
+ "comment": map[string]any{
+ "id": util.UUIDToString(comment.ID),
+ "issue_id": util.UUIDToString(comment.IssueID),
+ "author_type": comment.AuthorType,
+ "author_id": util.UUIDToString(comment.AuthorID),
+ "content": comment.Content,
+ "type": comment.Type,
+ },
+ "issue_title": issue.Title,
+ },
+ })
+}
diff --git a/server/pkg/agent/exec_format.go b/server/pkg/agent/exec_format.go
index 84f22c5096..5e2912708b 100644
--- a/server/pkg/agent/exec_format.go
+++ b/server/pkg/agent/exec_format.go
@@ -38,7 +38,7 @@ import (
// preflight error travels out through the daemon's launch boundary — and a
// diagnosis printed twice is worse than the bare errno it replaced.
func ExplainExecError(err error) error {
- if err == nil || !errors.Is(err, syscall.ENOEXEC) {
+ if err == nil || !IsExecFormatError(err) {
return err
}
var explained explainedExecError
@@ -54,6 +54,20 @@ type explainedExecError struct{ error }
func (e explainedExecError) Unwrap() error { return e.error }
+// IsExecFormatError reports whether the OS refused to run a file because it is
+// not a program this machine can execute.
+//
+// This is a verdict about a file that is on disk right now, not a transient
+// launch failure: the same binary will be rejected the same way until someone
+// changes it. Callers use that to tell a permanent install problem apart from a
+// CLI that was merely busy or mid-upgrade.
+func IsExecFormatError(err error) bool {
+ if err == nil {
+ return false
+ }
+ return errors.Is(err, syscall.ENOEXEC) || isPlatformExecFormatError(err)
+}
+
// execPathFromError recovers the executable path the OS refused to run.
// os/exec reports a failed launch as *fs.PathError (fork/exec) and a failed
// lookup as *exec.Error; both carry the path, so neither call site has to
@@ -76,21 +90,91 @@ func execPathFromError(err error) string {
// daemon can observe after the fact.
const blockedPostinstallCauses = "npm 12 allowScripts, pnpm 10 approve-builds, --ignore-scripts, --omit=optional"
+// ExecFormatRepair is the machine-readable half of the diagnosis: which npm
+// package owns the unrunnable entry point, and the command that reinstalls its
+// native binary.
+//
+// The daemon reports this to the server when it takes a runtime offline, so the
+// UI can tell a user why their agent stopped and what to run — clients localize
+// the sentence around it, and only the daemon can know the path, so neither can
+// produce this pair alone. Empty Command means the layout was not recognised
+// and there is nothing more specific to offer than "reinstall the CLI".
+type ExecFormatRepair struct {
+ Package string `json:"package,omitempty"`
+ Command string `json:"command,omitempty"`
+ // Shell names the interpreter Command is written for, so whoever displays
+ // it can label the code block truthfully. The command is rendered for the
+ // machine that reported it — the only machine it can be run on — not for
+ // whoever happens to be reading.
+ Shell string `json:"shell,omitempty"`
+}
+
+// Shells a repair command can be written for. Windows gets PowerShell: it is
+// the default shell of the Windows terminal, and the alternative (cmd.exe) has
+// no syntax that also works there — `cd /d` is not a PowerShell command, and
+// PowerShell 5.1 has no `&&`.
+const (
+ shellBash = "bash"
+ shellPowerShell = "powershell"
+)
+
+// ExecFormatRepairFor returns the repair for an executable the OS refuses to
+// run, or false when execPath is not an npm bin entry whose package declares a
+// postinstall.
+func ExecFormatRepairFor(execPath string) (ExecFormatRepair, bool) {
+ return execFormatRepairForShell(execPath, hostShell())
+}
+
+func hostShell() string {
+ if runtime.GOOS == "windows" {
+ return shellPowerShell
+ }
+ return shellBash
+}
+
+func execFormatRepairForShell(execPath, shell string) (ExecFormatRepair, bool) {
+ pkg, root, script, ok := npmPackagePostinstall(execPath)
+ if !ok {
+ return ExecFormatRepair{}, false
+ }
+ return ExecFormatRepair{Package: pkg, Command: repairCommand(root, script, shell), Shell: shell}, true
+}
+
+// repairCommand renders "run this package's postinstall" for one shell.
+//
+// The postinstall has to run with the package root as the working directory —
+// npm runs it that way, and a script referencing a relative path (opencode's
+// `node ./postinstall.mjs`) breaks anywhere else — so the directory change is
+// part of the command rather than an instruction the reader has to infer.
+func repairCommand(root, script, shell string) string {
+ if shell == shellPowerShell {
+ // Two statements on two lines: PowerShell 5.1 still ships with Windows
+ // and has no `&&`, and Set-Location handles a drive change that cmd's
+ // bare `cd` silently would not.
+ return fmt.Sprintf("Set-Location %s\n%s", powerShellQuote(root), script)
+ }
+ return fmt.Sprintf("cd %s && %s", shellQuote(root), script)
+}
+
func execFormatDiagnosis(execPath string) string {
target := execPath
if target == "" {
target = "the agent CLI"
}
- pkg, command, ok := npmPackagePostinstall(execPath)
+ repair, ok := ExecFormatRepairFor(execPath)
if !ok {
return fmt.Sprintf(
"%s is not a runnable executable on %s/%s. For an agent CLI installed from npm this usually means its postinstall never ran (%s all block it), leaving the package's placeholder stub at that path. Reinstall the CLI with install scripts enabled, then retry",
target, runtime.GOOS, runtime.GOARCH, blockedPostinstallCauses,
)
}
+ // Rendered on one line here: this string is an error message, and a
+ // multi-line PowerShell repair would break the log line it lands in. The
+ // structured repair (ExecFormatRepairFor) is what surfaces verbatim.
return fmt.Sprintf(
"%s is not a runnable executable on %s/%s. It is the bin entry of npm package %s, so the usual cause is that its postinstall never ran (%s all block it), leaving the package's placeholder stub in place. Run `%s` to install the native binary, or reinstall the CLI with install scripts enabled, then retry",
- target, runtime.GOOS, runtime.GOARCH, pkg, blockedPostinstallCauses, command,
+ target, runtime.GOOS, runtime.GOARCH, repair.Package, blockedPostinstallCauses,
+ strings.ReplaceAll(repair.Command, "\n", "; "),
)
}
@@ -103,18 +187,18 @@ func execFormatDiagnosis(execPath string) string {
// the package's own manifest. That keeps it provider-agnostic: claude's
// `node install.cjs` and opencode's `node ./postinstall.mjs` are both just
// whatever scripts.postinstall says, and a CLI added later needs no change here.
-func npmPackagePostinstall(execPath string) (name, command string, ok bool) {
+func npmPackagePostinstall(execPath string) (name, root, script string, ok bool) {
if execPath == "" {
- return "", "", false
+ return "", "", "", false
}
dir := filepath.Dir(execPath)
if !strings.EqualFold(filepath.Base(dir), "bin") {
- return "", "", false
+ return "", "", "", false
}
- root := filepath.Dir(dir)
+ root = filepath.Dir(dir)
data, err := os.ReadFile(filepath.Join(root, "package.json"))
if err != nil {
- return "", "", false
+ return "", "", "", false
}
var manifest struct {
Name string `json:"name"`
@@ -123,17 +207,17 @@ func npmPackagePostinstall(execPath string) (name, command string, ok bool) {
} `json:"scripts"`
}
if err := json.Unmarshal(data, &manifest); err != nil {
- return "", "", false
+ return "", "", "", false
}
- script := strings.TrimSpace(manifest.Scripts.Postinstall)
+ script = strings.TrimSpace(manifest.Scripts.Postinstall)
if script == "" {
- return "", "", false
+ return "", "", "", false
}
name = strings.TrimSpace(manifest.Name)
if name == "" {
name = filepath.Base(root)
}
- return name, fmt.Sprintf("cd %s && %s", shellQuote(root), script), true
+ return name, root, script, true
}
// shellQuote makes an arbitrary path safe to paste into a POSIX shell. The
@@ -142,3 +226,11 @@ func npmPackagePostinstall(execPath string) (name, command string, ok bool) {
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
+
+// powerShellQuote is the same guarantee for PowerShell, where a single quote
+// inside a single-quoted string is escaped by doubling it. Windows paths are
+// exactly where this matters: "C:\\Program Files\\..." has to survive being
+// pasted, and so does a user directory with an apostrophe in it.
+func powerShellQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", "''") + "'"
+}
diff --git a/server/pkg/agent/exec_format_other.go b/server/pkg/agent/exec_format_other.go
new file mode 100644
index 0000000000..1eae47050d
--- /dev/null
+++ b/server/pkg/agent/exec_format_other.go
@@ -0,0 +1,8 @@
+//go:build !windows
+
+package agent
+
+// isPlatformExecFormatError has nothing to add outside Windows: execve reports
+// every "this file is not a program" case as ENOEXEC, which IsExecFormatError
+// already checks.
+func isPlatformExecFormatError(error) bool { return false }
diff --git a/server/pkg/agent/exec_format_test.go b/server/pkg/agent/exec_format_test.go
index 1431a20d9f..f1520cea51 100644
--- a/server/pkg/agent/exec_format_test.go
+++ b/server/pkg/agent/exec_format_test.go
@@ -179,3 +179,58 @@ func TestExplainExecErrorMatchesRealExecFailure(t *testing.T) {
t.Errorf("a real launch failure should carry the repair command: %v", ExplainExecError(err))
}
}
+
+// The repair command is meant to be pasted into a terminal on the machine that
+// reported it, so it has to be written for THAT machine's shell. Windows was
+// getting POSIX syntax: `cd 'C:\\...' && node install.cjs` is wrong twice over
+// — cmd.exe treats the quotes as literal characters, and PowerShell 5.1, which
+// still ships with Windows, has no `&&`.
+func TestRepairCommandIsWrittenForTheHostShell(t *testing.T) {
+ posix := repairCommand("/usr/lib/node_modules/@anthropic-ai/claude-code", "node install.cjs", shellBash)
+ if posix != "cd '/usr/lib/node_modules/@anthropic-ai/claude-code' && node install.cjs" {
+ t.Errorf("posix repair = %q", posix)
+ }
+
+ windows := repairCommand(`C:\Program Files\nodejs\node_modules\@anthropic-ai\claude-code`, "node install.cjs", shellPowerShell)
+ want := "Set-Location 'C:\\Program Files\\nodejs\\node_modules\\@anthropic-ai\\claude-code'\nnode install.cjs"
+ if windows != want {
+ t.Errorf("windows repair =\n%q\nwant\n%q", windows, want)
+ }
+ // No `&&` anywhere: PowerShell 5.1 would reject the whole line.
+ if strings.Contains(windows, "&&") {
+ t.Errorf("windows repair uses &&, which PowerShell 5.1 cannot run: %q", windows)
+ }
+}
+
+// Paths with a quote in them are rare and catastrophic: the pasted command
+// silently targets a different directory.
+func TestRepairCommandQuotesPathsPerShell(t *testing.T) {
+ if got := repairCommand("/home/it's mine/pkg", "node install.cjs", shellBash); got != `cd '/home/it'\''s mine/pkg' && node install.cjs` {
+ t.Errorf("posix quoting = %q", got)
+ }
+ if got := repairCommand(`C:\Users\it's mine\pkg`, "node install.cjs", shellPowerShell); got != "Set-Location 'C:\\Users\\it''s mine\\pkg'\nnode install.cjs" {
+ t.Errorf("powershell quoting = %q", got)
+ }
+}
+
+// The shell travels with the command so whoever renders it can label the code
+// block truthfully instead of guessing.
+func TestExecFormatRepairReportsItsShell(t *testing.T) {
+ _, execPath := writePlaceholderPackage(t, "@anthropic-ai/claude-code", "node install.cjs")
+
+ repair, ok := execFormatRepairForShell(execPath, shellPowerShell)
+ if !ok {
+ t.Fatal("expected a repair for a staged npm package")
+ }
+ if repair.Shell != shellPowerShell {
+ t.Errorf("repair shell = %q, want %q", repair.Shell, shellPowerShell)
+ }
+ if !strings.HasPrefix(repair.Command, "Set-Location ") {
+ t.Errorf("repair command is not PowerShell: %q", repair.Command)
+ }
+ // And the host default still resolves to something coherent.
+ host, ok := ExecFormatRepairFor(execPath)
+ if !ok || host.Shell == "" || host.Command == "" {
+ t.Errorf("host repair is incomplete: %+v", host)
+ }
+}
diff --git a/server/pkg/agent/exec_format_windows.go b/server/pkg/agent/exec_format_windows.go
new file mode 100644
index 0000000000..b8064d55b9
--- /dev/null
+++ b/server/pkg/agent/exec_format_windows.go
@@ -0,0 +1,19 @@
+package agent
+
+import (
+ "errors"
+
+ "golang.org/x/sys/windows"
+)
+
+// isPlatformExecFormatError recognises the Windows spelling of "this file is
+// not a program I can run".
+//
+// The stub problem is not POSIX-only: npm 12 blocks install scripts on Windows
+// too, so `bin/claude.exe` stays the shipped text placeholder and CreateProcess
+// rejects it with ERROR_BAD_EXE_FORMAT — Windows never reports ENOEXEC for it,
+// so without this the same broken install would read as a transient hiccup here
+// and keep its runtime online.
+func isPlatformExecFormatError(err error) bool {
+ return errors.Is(err, windows.ERROR_BAD_EXE_FORMAT)
+}
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index e712a7b538..1c7d110c1f 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -1099,6 +1099,33 @@ func (q *Queries) SetAgentRuntimeOffline(ctx context.Context, id pgtype.UUID) er
return err
}
+const setAgentRuntimeOfflineWithReason = `-- name: SetAgentRuntimeOfflineWithReason :exec
+UPDATE agent_runtime
+SET status = 'offline',
+ metadata = metadata || jsonb_build_object('offline_reason', $2::jsonb),
+ updated_at = now()
+WHERE id = $1
+`
+
+type SetAgentRuntimeOfflineWithReasonParams struct {
+ ID pgtype.UUID `json:"id"`
+ OfflineReason []byte `json:"offline_reason"`
+}
+
+// Takes a runtime offline and records WHY, for the one class of cause the user
+// has to repair before the runtime can come back (MUL-6164). Everything that
+// merely stops — daemon shutdown, laptop asleep — uses SetAgentRuntimeOffline
+// and leaves no reason, because "wait for it" needs no explanation.
+//
+// Merged into metadata rather than a column: registration overwrites metadata
+// wholesale (`metadata = EXCLUDED.metadata`), so a runtime that comes back
+// drops the reason as a side effect of being usable again — there is no stale
+// explanation to clean up and no code path that has to remember to clear it.
+func (q *Queries) SetAgentRuntimeOfflineWithReason(ctx context.Context, arg SetAgentRuntimeOfflineWithReasonParams) error {
+ _, err := q.db.Exec(ctx, setAgentRuntimeOfflineWithReason, arg.ID, arg.OfflineReason)
+ return err
+}
+
const touchAgentRuntimeLastSeen = `-- name: TouchAgentRuntimeLastSeen :execrows
UPDATE agent_runtime
SET last_seen_at = now()
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index b2d65338cd..ea2ec39020 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -197,6 +197,22 @@ UPDATE agent_runtime
SET status = 'offline', updated_at = now()
WHERE id = $1;
+-- name: SetAgentRuntimeOfflineWithReason :exec
+-- Takes a runtime offline and records WHY, for the one class of cause the user
+-- has to repair before the runtime can come back (MUL-6164). Everything that
+-- merely stops — daemon shutdown, laptop asleep — uses SetAgentRuntimeOffline
+-- and leaves no reason, because "wait for it" needs no explanation.
+--
+-- Merged into metadata rather than a column: registration overwrites metadata
+-- wholesale (`metadata = EXCLUDED.metadata`), so a runtime that comes back
+-- drops the reason as a side effect of being usable again — there is no stale
+-- explanation to clean up and no code path that has to remember to clear it.
+UPDATE agent_runtime
+SET status = 'offline',
+ metadata = metadata || jsonb_build_object('offline_reason', @offline_reason::jsonb),
+ updated_at = now()
+WHERE id = $1;
+
-- name: SelectStaleOnlineRuntimes :many
-- Lists online runtimes whose last_seen_at exceeds the stale window. The
-- sweeper uses this as a candidate set, then optionally filters via the