Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(openclaw): unblock the OpenClaw runtime on slow hosts (MUL-6321) (#7142)
Bohan Jiang4d5a679b9bf4
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex ffe3ce2066..fb98f9ddaf 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -307,6 +307,7 @@ Agent-specific overrides:| `MULTICA_OPENCODE_MODEL` | Override the OpenCode model used || `MULTICA_OPENCLAW_PATH` | Custom path to the `openclaw` binary || `MULTICA_OPENCLAW_MODEL` | Override the OpenClaw model used |+| `MULTICA_OPENCLAW_CLI_TIMEOUT` | Deadline for each `openclaw config ...` call during task preparation (default 30s; accepts `45s` or `45`). Raise it when the local CLI is slow to start; the daemon also reads it from `backends.openclaw.cli_timeout` in the CLI config || `MULTICA_HERMES_PATH` | Custom path to the `hermes` binary || `MULTICA_HERMES_MODEL` | Override the Hermes model used || `MULTICA_PI_PATH` | Custom path to the `pi` binary |diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 6a87d1e1b3..cd72952b88 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -211,6 +211,7 @@ Agent-specific overrides:| `MULTICA_OPENCODE_MODEL` | Override the OpenCode model used || `MULTICA_OPENCLAW_PATH` | Custom path to the `openclaw` binary || `MULTICA_OPENCLAW_MODEL` | Override the OpenClaw model used |+| `MULTICA_OPENCLAW_CLI_TIMEOUT` | Deadline for each `openclaw config ...` call during task preparation (default 30s; accepts `45s` or `45`). Raise it when the local CLI is slow to start; the daemon also reads it from `backends.openclaw.cli_timeout` in the CLI config || `MULTICA_HERMES_PATH` | Custom path to the `hermes` binary || `MULTICA_HERMES_MODEL` | Override the Hermes model used || `MULTICA_PI_PATH` | Custom path to the `pi` binary |diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsxindex d4b2d9c151..3cdbcb6a20 100644--- a/apps/mobile/components/issue/run-row.tsx+++ b/apps/mobile/components/issue/run-row.tsx@@ -169,6 +169,7 @@ const FAILURE_REASON_LABEL: Record<string, string> = {agent_blocked: "Needs input",api_invalid_request: "Request rejected",skill_bundle_unavailable: "Skill download failed",+ runtime_cli_timeout: "Runtime CLI timeout","agent_error.provider_auth_or_access": "Auth failed","agent_error.provider_quota_limit": "Quota exhausted",diff --git a/apps/mobile/lib/failure-reason-label.ts b/apps/mobile/lib/failure-reason-label.tsindex 7a641c6cd5..20a7adb067 100644--- a/apps/mobile/lib/failure-reason-label.ts+++ b/apps/mobile/lib/failure-reason-label.ts@@ -27,6 +27,7 @@ const LABELS: Record<string, string> = {agent_blocked: "Waiting on human input",api_invalid_request: "Rejected by the model API",skill_bundle_unavailable: "Couldn't download the agent's skills",+ runtime_cli_timeout: "Local runtime CLI timed out",// Agent process side — provider."agent_error.provider_auth_or_access": "Provider auth failed",diff --git a/packages/core/dashboard/failure-class.ts b/packages/core/dashboard/failure-class.tsindex 0bea6ac546..a374442447 100644--- a/packages/core/dashboard/failure-class.ts+++ b/packages/core/dashboard/failure-class.ts@@ -65,6 +65,11 @@ const REASON_CLASS: Record<string, FailureClass> = {// operator response is "check the daemon's link to Multica", the same as a// daemon that went offline — the model provider is not involved.skill_bundle_unavailable: "runtime",+ // The local runtime CLI (OpenClaw config discovery today) missed its+ // deadline during preparation. "runtime" for the same reason: the operator+ // fix is on the host running the daemon — a faster CLI or a raised timeout —+ // not with the model provider, which was never contacted.+ runtime_cli_timeout: "runtime",// The agent process itself produced the failure."agent_error.process_failure": "agent",diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex 01277f1d98..175ac8dfa1 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -25,6 +25,7 @@ const REASON_LABEL: Record<string, string> = {agent_blocked: "Waiting on human input",api_invalid_request: "Rejected by the model API",skill_bundle_unavailable: "Couldn't download the agent's skills",+ runtime_cli_timeout: "Local runtime CLI timed out",// Agent process side — provider."agent_error.provider_auth_or_access": "Provider auth failed",diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex c56414491d..ca3e31400b 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -947,6 +947,7 @@ function FailureBubble({manual: t(($) => $.message_list.failure.manual),cancelled: t(($) => $.message_list.failure.manual),skill_bundle_unavailable: t(($) => $.message_list.failure.skill_bundle_unavailable),+ runtime_cli_timeout: t(($) => $.message_list.failure.runtime_cli_timeout),"agent_error.provider_network": t(($) => $.message_list.failure.provider_network),"agent_error.provider_auth_or_access": t(($) => $.message_list.failure.provider_auth_or_access),"agent_error.provider_quota_limit": t(($) => $.message_list.failure.provider_quota_limit),diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex d9995cddd7..6439192bdd 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -59,6 +59,7 @@"runtime_recovery": "The agent restarted before it could finish. Please try again.","manual": "This reply was cancelled.","skill_bundle_unavailable": "The agent's skills couldn't be downloaded, so it never got started. This is usually a connection problem — please try again.",+ "runtime_cli_timeout": "The local OpenClaw CLI didn't answer in time, so this run never started. It's a local startup timeout, not a network problem — retrying won't help until the CLI gets faster or the timeout is raised (MULTICA_OPENCLAW_CLI_TIMEOUT).","provider_network": "The connection to the model provider dropped before the reply finished. Check your network and try again.","provider_auth_or_access": "The agent's model account isn't signed in any more. Sign in again, then retry.","provider_quota_limit": "The agent's model account has run out of credit. Top it up or switch accounts, then retry.",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex e87f177278..a58f0ec9c6 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -57,6 +57,7 @@"runtime_recovery": "完了する前にエージェントが再起動しました。もう一度お試しください。","manual": "この返信はキャンセルされました。","skill_bundle_unavailable": "エージェントの skill をダウンロードできず、返信を開始できませんでした。多くの場合はネットワークの問題です。もう一度お試しください。",+ "runtime_cli_timeout": "ローカルの OpenClaw CLI が時間内に応答せず、この実行は開始されませんでした。ネットワークではなくローカルの起動タイムアウトです。CLI が速くなるか、タイムアウト(MULTICA_OPENCLAW_CLI_TIMEOUT)を延ばすまで再試行しても成功しません。","provider_network": "モデルサービスとの接続が切断され、返信を完了できませんでした。ネットワークを確認してから再度お試しください。","provider_auth_or_access": "エージェントのモデルアカウントのログインが無効になりました。再度ログインしてからお試しください。","provider_quota_limit": "エージェントのモデルアカウントの残高が不足しています。チャージするかアカウントを切り替えてからお試しください。",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 3b46ffd723..6f6c6e1131 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -57,6 +57,7 @@"runtime_recovery": "완료 전에 에이전트가 다시 시작되었습니다. 다시 시도해 주세요.","manual": "이 답변이 취소되었습니다.","skill_bundle_unavailable": "에이전트의 skill을 내려받지 못해 답변을 시작하지 못했습니다. 대개 네트워크 연결 문제입니다. 다시 시도해 주세요.",+ "runtime_cli_timeout": "로컬 OpenClaw CLI가 제한 시간 안에 응답하지 않아 이번 실행이 시작되지 못했습니다. 네트워크 문제가 아니라 로컬 실행 지연입니다. CLI가 빨라지거나 제한 시간(MULTICA_OPENCLAW_CLI_TIMEOUT)을 늘리기 전에는 다시 시도해도 실패합니다.","provider_network": "모델 서비스와의 연결이 끊겨 답변을 완료하지 못했습니다. 네트워크를 확인한 뒤 다시 시도해 주세요.","provider_auth_or_access": "에이전트의 모델 계정 로그인이 만료되었습니다. 다시 로그인한 뒤 시도해 주세요.","provider_quota_limit": "에이전트의 모델 계정 잔액이 부족합니다. 충전하거나 계정을 변경한 뒤 시도해 주세요.",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex 3e0e58481a..d9a8025c6e 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -57,6 +57,7 @@"runtime_recovery": "智能体在完成前重启了。请重试。","manual": "这次回复已取消。","skill_bundle_unavailable": "没能下载到智能体的 skill,这次回复没有启动。通常是网络连接问题,请重试。",+ "runtime_cli_timeout": "本机 OpenClaw CLI 没能在超时时间内响应,这次运行没有启动。这是本地启动超时,不是网络问题——除非 CLI 变快或调大超时(MULTICA_OPENCLAW_CLI_TIMEOUT),否则重试也不会成功。","provider_network": "与模型服务的连接中断,回复没能完成。检查网络后重试。","provider_auth_or_access": "智能体的模型账号登录已失效。重新登录后再试。","provider_quota_limit": "智能体的模型账号额度已用尽。充值或更换账号后再试。",diff --git a/server/internal/cli/config.go b/server/internal/cli/config.goindex aad6c9e64a..a972a9fa2a 100644--- a/server/internal/cli/config.go+++ b/server/internal/cli/config.go@@ -176,6 +176,7 @@ type BackendOverrides struct {//// BinaryPath: MULTICA_OPENCLAW_PATH (env) > backends.openclaw.binary_path > PATH lookup// StateDir: OPENCLAW_STATE_DIR (env) > backends.openclaw.state_dir > OpenClaw's built-in default (~/.openclaw)+// CLITimeout: MULTICA_OPENCLAW_CLI_TIMEOUT (env) > backends.openclaw.cli_timeout > built-in default//// The StateDir env var here is OpenClaw's own OPENCLAW_STATE_DIR — NOT a new// MULTICA_OPENCLAW_STATE_DIR. Rationale: OpenClaw already honors its own env@@ -199,6 +200,17 @@ type BackendOverrides struct {type OpenClawOverride struct {BinaryPath string `json:"binary_path,omitempty"`StateDir string `json:"state_dir,omitempty"`+ // CLITimeout raises (or lowers) the per-invocation deadline the daemon+ // applies to `openclaw config ...` during task preparation. Accepts a Go+ // duration ("45s") or bare seconds ("45"); out-of-range values are clamped+ // and unparseable ones ignored by the daemon. Empty keeps the built-in+ // default, which fits every host measured so far — this exists for the+ // slow-CLI tail (#7112), where discovery legitimately needs longer than the+ // default and the user previously had no way to say so.+ //+ // Resolution mirrors the fields above: MULTICA_OPENCLAW_CLI_TIMEOUT (env) >+ // backends.openclaw.cli_timeout > built-in default.+ CLITimeout string `json:"cli_timeout,omitempty"`}// CLIConfigPath returns the default path for the CLI config file.diff --git a/server/internal/cli/config_test.go b/server/internal/cli/config_test.goindex 1e643a572d..c71e96ce00 100644--- a/server/internal/cli/config_test.go+++ b/server/internal/cli/config_test.go@@ -434,3 +434,39 @@ func TestCLIConfig_TaskRootMustBeAbsolute(t *testing.T) {t.Fatalf("CLIConfigPath error = %v, want absolute path validation", err)}}++// TestCLIConfig_OpenClawCLITimeout_RoundTrip covers the knob added for #7112:+// a host whose openclaw CLI is slower than the built-in default needs to+// record that in the config file, not just in a shell export the GUI-launched+// daemon never sees.+func TestCLIConfig_OpenClawCLITimeout_RoundTrip(t *testing.T) {+ tmp := t.TempDir()+ t.Setenv("HOME", tmp)++ original := CLIConfig{+ ServerURL: "https://api.multica.ai",+ Token: "mul_xyz",+ Backends: &BackendOverrides{+ OpenClaw: &OpenClawOverride{CLITimeout: "45s"},+ },+ }+ if err := SaveCLIConfig(original); err != nil {+ t.Fatal(err)+ }++ loaded, err := LoadCLIConfig()+ if err != nil {+ t.Fatal(err)+ }+ if loaded.Backends == nil || loaded.Backends.OpenClaw == nil {+ t.Fatalf("Backends.OpenClaw should be non-nil after round-trip, got %+v", loaded.Backends)+ }+ if got := loaded.Backends.OpenClaw.CLITimeout; got != "45s" {+ t.Errorf("CLITimeout round-trip: got %q, want %q", got, "45s")+ }+ // The other fields stay omitted so they keep falling through to env /+ // discovery instead of being pinned to an empty string.+ if got := loaded.Backends.OpenClaw.BinaryPath; got != "" {+ t.Errorf("BinaryPath should stay empty, got %q", got)+ }+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 9fe54719f7..8c884d1961 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -14,6 +14,7 @@ import ("github.com/mattn/go-shellwords""github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon/execenv""github.com/multica-ai/multica/server/pkg/agent")@@ -198,6 +199,8 @@ func LoadConfig(overrides Overrides) (Config, error) {// binary lookup; pre-existing path.// - OPENCLAW_STATE_DIR: OpenClaw's own env var; the daemon already// forwards it to spawned children via mergeEnv (server/pkg/agent/...).+ // - MULTICA_OPENCLAW_CLI_TIMEOUT: read by execenv when it sets the+ // deadline on each `openclaw config ...` call during task prep.//// Precedence is "env wins over config wins over default" — same shape// users already get with MULTICA_OPENCLAW_PATH today. We achieve it with@@ -1076,7 +1079,8 @@ func openclawOverrideFrom(cfg cli.CLIConfig) *cli.OpenClawOverride {//// Side-effecting on os.Setenv is intentional and scoped://-// - The two vars touched (MULTICA_OPENCLAW_PATH, OPENCLAW_STATE_DIR) are+// - The three vars touched (MULTICA_OPENCLAW_PATH, OPENCLAW_STATE_DIR,+// MULTICA_OPENCLAW_CLI_TIMEOUT) are// OpenClaw-specific. Other backends do not read them; setting them in the// daemon process has no observable effect on, e.g., Claude Code or Codex// spawn behavior.@@ -1098,4 +1102,9 @@ func applyOpenclawOverride(oc *cli.OpenClawOverride) {_ = os.Setenv("OPENCLAW_STATE_DIR", oc.StateDir)}}+ if oc.CLITimeout != "" {+ if _, set := os.LookupEnv(execenv.OpenclawCLITimeoutEnv); !set {+ _ = os.Setenv(execenv.OpenclawCLITimeoutEnv, oc.CLITimeout)+ }+ }}diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex cb4f102c4f..49d21142a6 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -15,6 +15,7 @@ import ("time""github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon/execenv")func TestResolveAgentExecutablePath_PreservesDispatchShimName(t *testing.T) {@@ -1454,3 +1455,41 @@ func agentKeys(m map[string]AgentEntry) []string {sort.Strings(keys)return keys}++// TestApplyOpenclawOverride_CLITimeout covers the #7112 knob on the same+// precedence contract as binary_path / state_dir: the config file supplies it+// when the environment does not, and an environment value the user exported+// upstream always wins.+func TestApplyOpenclawOverride_CLITimeout(t *testing.T) {+ t.Run("config file supplies the value", func(t *testing.T) {+ os.Unsetenv(execenv.OpenclawCLITimeoutEnv)+ t.Cleanup(func() { os.Unsetenv(execenv.OpenclawCLITimeoutEnv) })++ applyOpenclawOverride(&cli.OpenClawOverride{CLITimeout: "45s"})++ if got := os.Getenv(execenv.OpenclawCLITimeoutEnv); got != "45s" {+ t.Errorf("%s: got %q, want 45s", execenv.OpenclawCLITimeoutEnv, got)+ }+ })++ t.Run("env wins over config", func(t *testing.T) {+ t.Setenv(execenv.OpenclawCLITimeoutEnv, "20s")++ applyOpenclawOverride(&cli.OpenClawOverride{CLITimeout: "45s"})++ if got := os.Getenv(execenv.OpenclawCLITimeoutEnv); got != "20s" {+ t.Errorf("%s: env should win, got %q want 20s", execenv.OpenclawCLITimeoutEnv, got)+ }+ })++ t.Run("unset field leaves the env alone", func(t *testing.T) {+ os.Unsetenv(execenv.OpenclawCLITimeoutEnv)+ t.Cleanup(func() { os.Unsetenv(execenv.OpenclawCLITimeoutEnv) })++ applyOpenclawOverride(&cli.OpenClawOverride{StateDir: "/from/config/state"})++ if _, set := os.LookupEnv(execenv.OpenclawCLITimeoutEnv); set {+ t.Errorf("%s must not be set when the field is empty", execenv.OpenclawCLITimeoutEnv)+ }+ })+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6fee42f1b3..6646a009dd 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5216,6 +5216,15 @@ func taskRunFailureReason(err error) string {if errors.Is(err, errSkillBundleUnavailable) {return taskfailure.ReasonSkillBundleUnavailable.String()}+ // Structural, not textual: the message ends in "context deadline exceeded",+ // which Classify routes to agent_error.provider_network — "the connection to+ // the model provider dropped, check your network" for a stall that is purely+ // local, plus an auto-retry of a failure that is deterministic on the host.+ // The sentinel survives the preparation helper boundary via+ // preparationErrorKind (#7112).+ if errors.Is(err, execenv.ErrOpenclawCLITimeout) {+ return taskfailure.ReasonRuntimeCLITimeout.String()+ }return taskfailure.Classify(err.Error()).String()}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex f8b96e50c6..8c7d1c68ce 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -584,6 +584,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {if params.Provider == "openclaw" {result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: params.OpenclawBin,+ CacheDir: openclawProfileCacheDir(params.Profile, logger),McpConfig: params.McpConfig,Gateway: params.OpenclawGateway,Logger: logger,@@ -863,6 +864,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {if params.Provider == "openclaw" {result, err := prepareOpenclawConfig(env.RootDir, params.WorkDir, OpenclawConfigPrep{OpenclawBin: params.OpenclawBin,+ CacheDir: openclawProfileCacheDir(params.Profile, logger),McpConfig: params.McpConfig,Gateway: params.OpenclawGateway,Logger: logger,diff --git a/server/internal/daemon/execenv/isolation.go b/server/internal/daemon/execenv/isolation.goindex 60b83c10b8..b4b4384d0c 100644--- a/server/internal/daemon/execenv/isolation.go+++ b/server/internal/daemon/execenv/isolation.go@@ -56,6 +56,50 @@ type preparationRequestPayload struct {type preparationResponse struct {Environment *Environment `json:"environment,omitempty"`Error string `json:"error,omitempty"`+ // ErrorKind names the error class the parent must be able to recognise+ // structurally. Error itself only crosses the pipe as text, so an+ // errors.Is-based classification on the daemon side would otherwise be+ // impossible — the daemon would be back to substring-matching, which is+ // exactly what routed a local openclaw CLI stall into+ // agent_error.provider_network. Empty means "no special class".+ ErrorKind string `json:"error_kind,omitempty"`+}++// preparationErrorKindOpenclawCLITimeout marks a helper failure caused by the+// local openclaw CLI missing its deadline (ErrOpenclawCLITimeout).+const preparationErrorKindOpenclawCLITimeout = "openclaw_cli_timeout"++// preparationKindError re-attaches a sentinel to an error that crossed the+// helper boundary as text, so the daemon's classifier sees the same+// errors.Is result it would have seen in-process.+type preparationKindError struct {+ msg string+ kind error+}++func (e *preparationKindError) Error() string { return e.msg }++func (e *preparationKindError) Unwrap() error { return e.kind }++// preparationErrorKind names the class of err for the wire, or "" when it has+// none.+func preparationErrorKind(err error) string {+ if errors.Is(err, ErrOpenclawCLITimeout) {+ return preparationErrorKindOpenclawCLITimeout+ }+ return ""+}++// rehydratePreparationError rebuilds a typed error from the wire pair. An+// unknown kind (helper newer than the daemon) degrades to a plain error with+// the original message rather than being dropped.+func rehydratePreparationError(message, kind string) error {+ switch kind {+ case preparationErrorKindOpenclawCLITimeout:+ return &preparationKindError{msg: message, kind: ErrOpenclawCLITimeout}+ default:+ return errors.New(message)+ }}// PrepareIsolated executes Prepare in a killable helper process. command must@@ -161,7 +205,7 @@ func runPreparationProcess(ctx context.Context, command []string, request preparreturn nil, fmt.Errorf("execenv: decode preparation response: %w", err)}if response.Error != "" {- return nil, errors.New(response.Error)+ return nil, rehydratePreparationError(response.Error, response.ErrorKind)}if response.Environment != nil {// logger is intentionally omitted from JSON. Reattach the owning daemon's@@ -222,6 +266,7 @@ func RunPreparationHelper(in io.Reader, out io.Writer, logger *slog.Logger) erroresponse.Environment = envif err != nil {response.Error = err.Error()+ response.ErrorKind = preparationErrorKind(err)}case preparationActionReuse:if request.Reuse == nil || request.Prepare != nil {diff --git a/server/internal/daemon/execenv/isolation_test.go b/server/internal/daemon/execenv/isolation_test.goindex f74288fe13..381fc0d794 100644--- a/server/internal/daemon/execenv/isolation_test.go+++ b/server/internal/daemon/execenv/isolation_test.go@@ -4,10 +4,15 @@ import ("bytes""context""encoding/json"+ "errors"+ "fmt""io""log/slog""os"+ "os/exec""path/filepath"+ "runtime"+ "strings""testing""time")@@ -191,3 +196,65 @@ func TestPreparationRequestPreservesOpenclawGatewayForHelper(t *testing.T) {})}}++// TestPreparationHelperPreservesOpenclawTimeoutKind covers the boundary that+// makes structural classification possible. Prepare runs in a one-shot helper+// process and its error reaches the daemon as JSON text, so an+// errors.Is-based check would silently degrade to "unknown error" — and the+// daemon would fall back to matching "deadline exceeded" in the message, which+// is exactly the misclassification this change removes (#7112).+func TestPreparationHelperPreservesOpenclawTimeoutKind(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell shim shape is covered by the windows-tagged tests")+ }+ sleepBin, err := exec.LookPath("sleep")+ if err != nil {+ t.Skipf("no sleep binary available to build a slow shim: %v", err)+ }+ // A CLI slower than the deadline, which the child process inherits through+ // the environment. openclawCLIMinTimeout is the floor, so the shim has to+ // outlast a full second.+ shim := writeShim(t, t.TempDir(), "#!/bin/sh\n"+sleepBin+" 5\n", "")+ t.Setenv(OpenclawCLITimeoutEnv, "1s")++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ _, err = PrepareIsolated(ctx, preparationHelperTestCommand(), PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-helper-openclaw-timeout",+ TaskID: "11111111-2222-3333-4444-555555555555",+ Provider: "openclaw",+ OpenclawBin: shim,+ Task: TaskContextForEnv{IssueID: "issue-helper-openclaw-timeout"},+ }, logger)+ if err == nil {+ t.Fatal("expected preparation to fail when the openclaw CLI outlasts its deadline")+ }+ if !errors.Is(err, ErrOpenclawCLITimeout) {+ t.Errorf("the timeout sentinel must survive the helper boundary\ngot: %s", err)+ }+ if !strings.Contains(err.Error(), "openclaw config file") {+ t.Errorf("the original diagnostic must survive too\ngot: %s", err)+ }+}++// TestRehydratePreparationErrorUnknownKind pins the mixed-version direction of+// the same wire: a helper newer than the daemon may name a kind this build has+// never heard of, and the error must still arrive with its message intact+// rather than being dropped or mislabelled.+func TestRehydratePreparationErrorUnknownKind(t *testing.T) {+ err := rehydratePreparationError("prepare failed somehow", "some_future_kind")+ if err == nil || err.Error() != "prepare failed somehow" {+ t.Fatalf("rehydratePreparationError dropped the message: %v", err)+ }+ if errors.Is(err, ErrOpenclawCLITimeout) {+ t.Error("an unknown kind must not be reported as an openclaw CLI timeout")+ }+ if kind := preparationErrorKind(errors.New("plain failure")); kind != "" {+ t.Errorf("preparationErrorKind(plain) = %q, want empty", kind)+ }+ if kind := preparationErrorKind(fmt.Errorf("wrapped: %w", ErrOpenclawCLITimeout)); kind != preparationErrorKindOpenclawCLITimeout {+ t.Errorf("preparationErrorKind(timeout) = %q, want %q", kind, preparationErrorKindOpenclawCLITimeout)+ }+}diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.goindex feed1df6be..46ec7b1228 100644--- a/server/internal/daemon/execenv/openclaw_config.go+++ b/server/internal/daemon/execenv/openclaw_config.go@@ -29,9 +29,24 @@ const openclawConfigFile = "openclaw-config.json"// at 0o600 next to the wrapper.const openclawUserSnapshotFile = "openclaw-user-snapshot.json"-// openclawCLITimeout is the context deadline set on each `openclaw config ...`-// invocation during task setup. The CLI is fast (<200ms normal); 5s leaves-// headroom for a cold node start.+// openclawCLITimeout is the default context deadline set on each+// `openclaw config ...` invocation during task setup.+//+// It used to be 5s, on the assumption that the CLI answers in <200ms and 5s is+// pure cold-start headroom. Field data (#7112) retired that assumption: on a+// 2020 Intel MacBook Pro, `openclaw config file` takes 8.4–10.9s and+// `config get agents.list --json` 4.3s, every time — so the runtime was+// unusable on that host, with no user-side way to raise the limit. For scale,+// the same commands take 0.7s / 0.3s on an M-series Mac, i.e. the real spread+// across supported hardware is wider than the old margin.+//+// 30s is ~3x the slowest measured call, and even the worst case+// (openclawMaxCLICallsPerPreparation serial calls at that budget) fits inside+// the outer 5-minute task preparation deadline, so a genuinely hung CLI fails+// with this specific, actionable reason instead of the generic prepare+// timeout. Hosts outside that envelope can override with+// MULTICA_OPENCLAW_CLI_TIMEOUT (or backends.openclaw.cli_timeout in the CLI+// config, which the daemon translates into the same env var).//// It is a deadline, not a guaranteed cap — see the gap below.//@@ -51,19 +66,124 @@ const openclawUserSnapshotFile = "openclaw-user-snapshot.json"// deadline can terminate the whole tree, which is its own change with its own// risk surface. Tracked in MUL-5467; this file intentionally keeps the existing// behaviour rather than shipping half of it.-const openclawCLITimeout = 5 * time.Second+const openclawCLITimeout = 30 * time.Second++// OpenclawCLITimeoutEnv overrides openclawCLITimeout. Accepts a Go duration+// ("45s", "2m") or a bare number of seconds ("45"). Values outside+// [openclawCLIMinTimeout, openclawCLIMaxTimeout] are clamped, and anything+// unparseable is ignored, so a typo degrades to the default instead of+// disabling the deadline.+const OpenclawCLITimeoutEnv = "MULTICA_OPENCLAW_CLI_TIMEOUT"++const (+ // openclawCLIMinTimeout keeps an override from being so small that no real+ // CLI can answer; 1s is already below every measured healthy host.+ openclawCLIMinTimeout = time.Second+ // openclawCLIMaxTimeout keeps config discovery inside the outer task+ // preparation budget (daemon.defaultTaskPrepareTimeout, 5 minutes). The+ // worst case is openclawMaxCLICallsPerPreparation serial calls, so the+ // ceiling is set so that even then (4 x 60s = 4m) the failure surfaces as a+ // specific, actionable CLI timeout with room to spare, instead of colliding+ // with the outer deadline and collapsing into the generic — and retryable —+ // prepare-timeout reason.+ openclawCLIMaxTimeout = 60 * time.Second+)++// openclawMaxCLICallsPerPreparation is how many serial `openclaw ...`+// invocations one task preparation can make in the worst case. Each one gets+// its own deadline, so this is the multiplier that decides whether+// openclawCLIMaxTimeout still fits inside the outer preparation budget.+//+// The four call sites, in the order they can fire:+//+// 1. `config file` — locate the active config+// 2. `config get agents.list --json` — pre-2026.6 agents schema+// 3. `agents list --json` — 2026.6+ registry fallback, only+// reached when (2) reports the config path is missing+// 4. `config get --json` — full resolved config, only for an+// agent with a managed mcp_config+//+// Adding a fifth call means re-deriving the ceiling; the budget test fails+// loudly if this constant and the real call graph drift apart.+const openclawMaxCLICallsPerPreparation = 4++// ErrOpenclawCLITimeout marks a task preparation that failed because the local+// openclaw CLI did not answer within the deadline. It is a sentinel rather+// than a message-matched string for a reason: the daemon classifies on it+// structurally (taskRunFailureReason), and the old text-matching path routed+// every "deadline exceeded" into agent_error.provider_network — telling the+// user to check their network for a purely local stall, and auto-retrying a+// failure that is deterministic on the affected host.+//+// Preparation runs in a helper process, so the sentinel is re-attached on the+// daemon side of that boundary; see preparationErrorKindOpenclawCLITimeout.+var ErrOpenclawCLITimeout = errors.New("openclaw cli timeout")++// openclawCLITimeoutError carries the CLI's own diagnostic text while still+// matching both ErrOpenclawCLITimeout (our classifier) and the wrapped+// context error (callers that check cancellation the standard way).+type openclawCLITimeoutError struct {+ msg string+ cause error+}++func (e *openclawCLITimeoutError) Error() string { return e.msg }++func (e *openclawCLITimeoutError) Unwrap() []error {+ return []error{e.cause, ErrOpenclawCLITimeout}+}++// resolveOpenclawCLITimeout picks the deadline for one CLI invocation:+// explicit (tests) > MULTICA_OPENCLAW_CLI_TIMEOUT > openclawCLITimeout.+func resolveOpenclawCLITimeout(explicit time.Duration, logger *slog.Logger) time.Duration {+ if explicit > 0 {+ return explicit+ }+ raw := strings.TrimSpace(os.Getenv(OpenclawCLITimeoutEnv))+ if raw == "" {+ return openclawCLITimeout+ }+ parsed, err := time.ParseDuration(raw)+ if err != nil {+ // Bare number means seconds. Parsed as a duration string rather than+ // Atoi * time.Second, which overflows into a negative (or absurdly+ // large) duration for big inputs instead of failing cleanly.+ if secondsParsed, secErr := time.ParseDuration(raw + "s"); secErr == nil {+ parsed, err = secondsParsed, nil+ }+ }+ if err != nil || parsed <= 0 {+ if logger != nil {+ logger.Warn("execenv: ignoring unusable openclaw CLI timeout override; using default",+ "env", OpenclawCLITimeoutEnv, "value", raw, "default", openclawCLITimeout)+ }+ return openclawCLITimeout+ }+ clamped := min(max(parsed, openclawCLIMinTimeout), openclawCLIMaxTimeout)+ if clamped != parsed && logger != nil {+ logger.Warn("execenv: clamping openclaw CLI timeout override",+ "env", OpenclawCLITimeoutEnv, "value", raw, "applied", clamped)+ }+ return clamped+}// OpenclawConfigPrep is the input to prepareOpenclawConfig. Only OpenclawBin-// is meaningful in production — Timeout is here for tests that need a tight-// deadline to assert error paths.+// and CacheDir are meaningful in production — Timeout is here for tests that+// need a tight deadline to assert error paths.type OpenclawConfigPrep struct {// OpenclawBin is the openclaw CLI binary to invoke for config introspection.// Empty means resolve "openclaw" from PATH at exec time.OpenclawBin string// Timeout sets the context deadline for each CLI invocation — not a// guaranteed cap on how long the call takes; see openclawCLITimeout. Zero- // falls back to openclawCLITimeout.+ // falls back to the MULTICA_OPENCLAW_CLI_TIMEOUT override, then to+ // openclawCLITimeout.Timeout time.Duration+ // CacheDir is the directory holding this daemon profile's shared+ // discovery cache. Empty disables caching entirely — every task then pays+ // the full CLI cost, which is correct but slow. See+ // openclaw_config_cache.go for what is cached and how it is invalidated.+ CacheDir string// McpConfig is the agent's saved `mcp_config` JSON (Claude-style// `{"mcpServers": {"<name>": {...}}}`). When non-null the wrapper pins// `mcp.servers` to the managed set so OpenClaw resolves MCP from the@@ -208,14 +328,11 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Opif bin == "" {bin = "openclaw"}- timeout := opts.Timeout- if timeout <= 0 {- timeout = openclawCLITimeout- }+ timeout := resolveOpenclawCLITimeout(opts.Timeout, opts.Logger)- activePath, exists, err := openclawActiveConfigPath(bin, timeout)+ activePath, exists, resolvedList, agentsFromRegistry, cached, err := discoverOpenclawConfig(bin, timeout, opts)if err != nil {- return OpenclawConfigResult{}, fmt.Errorf("locate openclaw active config: %w", err)+ return OpenclawConfigResult{}, err}if !exists && opts.Logger != nil {// Not an error — a genuine fresh install lands here legitimately.@@ -227,15 +344,6 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op"reported_path", activePath)}- var resolvedList []any- var agentsFromRegistry bool- if exists {- resolvedList, agentsFromRegistry, err = openclawResolvedAgentsList(bin, timeout)- if err != nil {- return OpenclawConfigResult{}, fmt.Errorf("read openclaw agents.list: %w", err)- }- }-// Parse the agent's managed mcp_config (if any) before writing the wrapper// so a malformed value fails the prepare step rather than crashing the// openclaw subprocess later. Same fail-closed posture as Codex's@@ -320,11 +428,60 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op"include_target", includeTarget,"include_root", result.IncludeRoot,"agents_from_registry", agentsFromRegistry,+ "discovery_cached", cached,"managed_mcp", hasManagedMcp)}return result, nil}+// discoverOpenclawConfig resolves the user's active config path and resolved+// agents.list, serving both from the shared per-profile cache when the cached+// evidence still matches the host (see openclaw_config_cache.go).+//+// The two are cached as one unit because they are read as one unit: a hit that+// covered only the path would still pay the second CLI call, which on the host+// in #7112 is 4.3s of the 12.7s total.+//+// Cache faults are never fatal. A miss, an unreadable entry, or a failed store+// only costs the CLI round-trips this call was going to make anyway, so+// discovery keeps its existing fail-closed contract: only a real CLI failure+// fails the task.+func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConfigPrep) (activePath string, exists bool, resolvedList []any, agentsFromRegistry bool, cached bool, err error) {+ cachePath := openclawDiscoveryCachePath(opts.CacheDir)+ if entry, ok := loadOpenclawDiscoveryCache(cachePath, bin, time.Now()); ok {+ list, decodeErr := decodeOpenclawCachedAgentsList(entry.AgentsList)+ if decodeErr == nil {+ return entry.ActiveConfigPath, true, list, entry.AgentsFromRegistry, true, nil+ }+ if opts.Logger != nil {+ opts.Logger.Warn("execenv: openclaw discovery cache entry unusable; rediscovering",+ "cache", cachePath, "error", decodeErr)+ }+ }++ activePath, exists, err = openclawActiveConfigPath(bin, timeout)+ if err != nil {+ return "", false, nil, false, false, fmt.Errorf("locate openclaw active config: %w", err)+ }+ if !exists {+ // Deliberately not cached: "no config on disk" is the one state that+ // flips the moment the user runs OpenClaw's own setup, and caching it+ // would keep a freshly configured host running without its models and+ // auth profiles for the rest of the TTL.+ return activePath, false, nil, false, false, nil+ }++ resolvedList, agentsFromRegistry, err = openclawResolvedAgentsList(bin, timeout)+ if err != nil {+ return "", false, nil, false, false, fmt.Errorf("read openclaw agents.list: %w", err)+ }+ if storeErr := storeOpenclawDiscoveryCache(cachePath, bin, activePath, resolvedList, agentsFromRegistry, time.Now()); storeErr != nil && opts.Logger != nil {+ opts.Logger.Warn("execenv: could not cache openclaw discovery; next task will rerun the CLI",+ "cache", cachePath, "error", storeErr)+ }+ return activePath, exists, resolvedList, agentsFromRegistry, false, nil+}+// buildPerTaskOpenclawConfig assembles the wrapper map that goes on disk.//// Exists=true: emit a $include link to the user's active config plus the@@ -872,6 +1029,26 @@ func execOpenclawCLI(ctx context.Context, bin string, args ...string) (string, eif err != nil {stderrMsg := strings.TrimSpace(stderr.String())if ctxErr := ctx.Err(); ctxErr != nil {+ msg := fmt.Sprintf("openclaw %s: %v (process: %v)", strings.Join(args, " "), ctxErr, err)+ if stderrMsg != "" {+ msg = fmt.Sprintf("openclaw %s: %v (process: %v; stderr: %s)", strings.Join(args, " "), ctxErr, err, stderrMsg)+ }+ // A deadline is reported through openclawCLITimeoutError so the+ // daemon can recognise a local CLI stall structurally+ // (ErrOpenclawCLITimeout) instead of string-matching "deadline+ // exceeded" — which routed it into agent_error.provider_network,+ // i.e. "check your network" copy plus an auto-retry, for a failure+ // that is local and deterministic.+ //+ // Cancellation deliberately does NOT get the sentinel: a daemon+ // shutdown or a cancelled task is not a slow CLI, and labelling it+ // as one would tell the user to raise a timeout that was never the+ // problem. Both keep the wrapped context error, so+ // errors.Is(err, context.DeadlineExceeded) / context.Canceled work+ // exactly as before.+ if errors.Is(ctxErr, context.DeadlineExceeded) {+ return stdout, &openclawCLITimeoutError{msg: msg, cause: ctxErr}+ }if stderrMsg != "" {return stdout, fmt.Errorf("openclaw %s: %w (process: %v; stderr: %s)", strings.Join(args, " "), ctxErr, err, stderrMsg)}diff --git a/server/internal/daemon/execenv/openclaw_config_cache.go b/server/internal/daemon/execenv/openclaw_config_cache.gonew file mode 100644index 0000000000..183f5b3388--- /dev/null+++ b/server/internal/daemon/execenv/openclaw_config_cache.go@@ -0,0 +1,314 @@+package execenv++import (+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"++ "github.com/multica-ai/multica/server/internal/cli"+)++// OpenClaw config discovery costs two serial CLI round-trips per task+// preparation in the common case (`config file`, then+// `config get agents.list --json`; see openclawMaxCLICallsPerPreparation for+// the worst case). On a fast host that is ~1s total; on the Intel Mac in #7112+// it is ~12.7s, and it is paid again for every task — including every chat+// message, because Reuse runs the same preparation path as Prepare. Raising+// the deadline alone would turn a hard failure into a per-message stall, so+// the discovery result is cached.+//+// The cache lives on disk rather than in package memory on purpose:+// Prepare/Reuse run inside a one-shot preparation helper process+// (PrepareIsolated / ReuseIsolated), so an in-process cache would never+// survive to the next task.+//+// What is NOT cached: the fully resolved config read by+// openclawResolvedFullConfig. That payload carries the user's API keys and+// model-provider tokens, and copying it into a long-lived shared file is a+// secret-spill surface the wrapper flow does not need — that call already+// only happens for agents with a managed mcp_config.+const (+ // openclawDiscoveryCacheFile is the per-profile cache file name. It sits+ // in the profile directory (~/.multica[/profiles/<name>]) so every task on+ // this daemon shares one entry.+ openclawDiscoveryCacheFile = "openclaw-discovery-cache.json"++ // openclawDiscoveryCacheVersion guards the on-disk shape. A daemon that+ // reads an entry written by a different version treats it as a miss.+ openclawDiscoveryCacheVersion = 1++ // openclawDiscoveryCacheTTL bounds how long a hit can be served. The+ // fingerprint catches the changes we can observe cheaply (binary swap,+ // OpenClaw path env, active config rewrite), but not the ones we cannot:+ // a nested `$include` target edited in place, or an agent added through+ // OpenClaw's own SQLite registry, neither of which touches the top-level+ // config file. The TTL is the backstop that keeps those visible, at the+ // cost of re-running discovery at most once a minute.+ openclawDiscoveryCacheTTL = time.Minute+)++// openclawDiscoveryFingerprint is the "is this entry still true?" evidence+// captured when discovery ran. Every field must match on lookup; anything+// unequal (or unstattable) is a miss and the CLI runs again.+type openclawDiscoveryFingerprint struct {+ Version int `json:"version"`+ // Binary identity: the resolved absolute path plus size/mtime, so an+ // upgrade in place or a PATH change to a different install invalidates.+ BinPath string `json:"bin_path"`+ BinSize int64 `json:"bin_size"`+ BinModTimeNano int64 `json:"bin_mod_time_nano"`+ // Env is the fingerprint of the environment variables that can move+ // OpenClaw's active config out from under us. Values are compared, not+ // hashed: they are paths, not secrets.+ Env string `json:"env"`+ // Active config stat, keyed to the path discovery reported.+ ConfigPath string `json:"config_path"`+ ConfigSize int64 `json:"config_size"`+ ConfigModTimeNano int64 `json:"config_mod_time_nano"`+}++// openclawDiscoveryCacheEntry is one cached successful discovery.+type openclawDiscoveryCacheEntry struct {+ Fingerprint openclawDiscoveryFingerprint `json:"fingerprint"`+ CachedAtNano int64 `json:"cached_at_nano"`+ ActiveConfigPath string `json:"active_config_path"`+ // AgentsList is the resolved `agents.list` array, stored verbatim so a hit+ // reproduces exactly what the CLI returned.+ AgentsList json.RawMessage `json:"agents_list"`+ AgentsFromRegistry bool `json:"agents_from_registry"`+}++// openclawDiscoveryEnvVars are the environment variables that change which+// config OpenClaw considers active. HOME / USERPROFILE are included because+// every default candidate path is derived from them, and the CLAWDBOT_* pair+// because openclawFallbackConfigCandidates still honours those legacy names —+// a cache that ignored them could keep serving the pre-switch config for a+// full TTL after the user pointed the daemon somewhere else.+var openclawDiscoveryEnvVars = []string{+ "OPENCLAW_CONFIG_PATH",+ "OPENCLAW_HOME",+ "OPENCLAW_STATE_DIR",+ "CLAWDBOT_CONFIG_PATH",+ "CLAWDBOT_STATE_DIR",+ "HOME",+ "USERPROFILE",+}++func openclawDiscoveryEnvFingerprint() string {+ parts := make([]string, 0, len(openclawDiscoveryEnvVars))+ for _, key := range openclawDiscoveryEnvVars {+ parts = append(parts, key+"="+os.Getenv(key))+ }+ return strings.Join(parts, "\x00")+}++// resolveOpenclawBinPath expands a bare command name through PATH so the+// fingerprint records the binary that actually ran, not the string "openclaw".+// A lookup failure returns the input unchanged; the stat below then fails and+// the caller takes the miss path.+func resolveOpenclawBinPath(bin string) string {+ if bin == "" {+ bin = "openclaw"+ }+ if strings.ContainsRune(bin, filepath.Separator) {+ return bin+ }+ if resolved, err := exec.LookPath(bin); err == nil {+ return resolved+ }+ return bin+}++// openclawProfileCacheDir resolves the directory this daemon profile shares+// across tasks (~/.multica, or ~/.multica/profiles/<name>). A resolution+// failure only disables caching — preparation still works, it just pays the+// CLI cost every time.+func openclawProfileCacheDir(profile string, logger *slog.Logger) string {+ dir, err := cli.ProfileDir(profile)+ if err != nil {+ if logger != nil {+ logger.Warn("execenv: openclaw discovery cache disabled; could not resolve profile dir",+ "profile", profile, "error", err)+ }+ return ""+ }+ return dir+}++// openclawDiscoveryCachePath returns the cache file inside dir, or "" when+// caching is disabled (no directory configured).+func openclawDiscoveryCachePath(dir string) string {+ if strings.TrimSpace(dir) == "" {+ return ""+ }+ return filepath.Join(dir, openclawDiscoveryCacheFile)+}++// buildOpenclawDiscoveryFingerprint captures the current evidence for bin and+// configPath. It returns an error when either file cannot be stat'ed, which+// callers treat as "do not cache / do not trust the cache" rather than as a+// task failure.+func buildOpenclawDiscoveryFingerprint(bin, configPath string) (openclawDiscoveryFingerprint, error) {+ binPath := resolveOpenclawBinPath(bin)+ binInfo, err := os.Stat(binPath)+ if err != nil {+ return openclawDiscoveryFingerprint{}, fmt.Errorf("stat openclaw binary: %w", err)+ }+ cfgInfo, err := os.Stat(configPath)+ if err != nil {+ return openclawDiscoveryFingerprint{}, fmt.Errorf("stat openclaw active config: %w", err)+ }+ return openclawDiscoveryFingerprint{+ Version: openclawDiscoveryCacheVersion,+ BinPath: binPath,+ BinSize: binInfo.Size(),+ BinModTimeNano: binInfo.ModTime().UnixNano(),+ Env: openclawDiscoveryEnvFingerprint(),+ ConfigPath: configPath,+ ConfigSize: cfgInfo.Size(),+ ConfigModTimeNano: cfgInfo.ModTime().UnixNano(),+ }, nil+}++// loadOpenclawDiscoveryCache returns a cached discovery for bin when one is+// present, structurally valid, still inside the TTL, and fingerprint-equal to+// the current on-disk state. Every other outcome — missing file, unreadable+// file, truncated JSON left by a killed writer, foreign version, moved binary,+// edited config — is a plain miss: the caller re-runs the CLI and stays+// fail-closed. Errors are never propagated, because a bad cache must degrade+// to "slow", never to "task failed".+func loadOpenclawDiscoveryCache(cachePath, bin string, now time.Time) (openclawDiscoveryCacheEntry, bool) {+ if cachePath == "" {+ return openclawDiscoveryCacheEntry{}, false+ }+ raw, err := os.ReadFile(cachePath)+ if err != nil {+ return openclawDiscoveryCacheEntry{}, false+ }+ var entry openclawDiscoveryCacheEntry+ if err := json.Unmarshal(raw, &entry); err != nil {+ return openclawDiscoveryCacheEntry{}, false+ }+ if entry.Fingerprint.Version != openclawDiscoveryCacheVersion {+ return openclawDiscoveryCacheEntry{}, false+ }+ // len 0 means the field was absent or empty — a truncated write, not a+ // stored result. A discovery with no agents is stored as the four bytes+ // "null" and is a legitimate hit.+ if entry.ActiveConfigPath == "" || len(entry.AgentsList) == 0 {+ return openclawDiscoveryCacheEntry{}, false+ }+ if entry.CachedAtNano <= 0 {+ return openclawDiscoveryCacheEntry{}, false+ }+ age := now.Sub(time.Unix(0, entry.CachedAtNano))+ // A negative age means the entry was written in the future — a clock jump+ // or a hand-edited file. Treat it as a miss rather than trusting it for a+ // TTL that may never expire.+ if age < 0 || age > openclawDiscoveryCacheTTL {+ return openclawDiscoveryCacheEntry{}, false+ }+ current, err := buildOpenclawDiscoveryFingerprint(bin, entry.ActiveConfigPath)+ if err != nil {+ return openclawDiscoveryCacheEntry{}, false+ }+ if current != entry.Fingerprint {+ return openclawDiscoveryCacheEntry{}, false+ }+ return entry, true+}++// storeOpenclawDiscoveryCache records a successful discovery. Only complete+// successes reach here: a fresh install with no config on disk, a CLI error,+// and a timeout all skip the write, so a transient failure can never be+// replayed from cache for the rest of the TTL.+//+// A nil agentsList is a success, not an omission: openclawResolvedAgentsList+// returns (nil, false, nil) for a config whose agents.list is null and for an+// empty 2026.6+ registry. Treating that as "incomplete" would leave exactly+// those users paying full discovery on every message, so it is stored as JSON+// null and decodes back to nil.+//+// The write is atomic (temp file + rename) so a concurrently reading task sees+// either the old entry or the new one, never a half-written file. Two tasks+// racing to store simply leave the later winner in place — both entries are+// equally valid.+func storeOpenclawDiscoveryCache(cachePath, bin, activeConfigPath string, agentsList []any, agentsFromRegistry bool, now time.Time) error {+ if cachePath == "" {+ return nil+ }+ if activeConfigPath == "" {+ return nil+ }+ fingerprint, err := buildOpenclawDiscoveryFingerprint(bin, activeConfigPath)+ if err != nil {+ return err+ }+ listBytes, err := json.Marshal(agentsList)+ if err != nil {+ return fmt.Errorf("marshal openclaw agents list: %w", err)+ }+ entry := openclawDiscoveryCacheEntry{+ Fingerprint: fingerprint,+ CachedAtNano: now.UnixNano(),+ ActiveConfigPath: activeConfigPath,+ AgentsList: listBytes,+ AgentsFromRegistry: agentsFromRegistry,+ }+ data, err := json.Marshal(entry)+ if err != nil {+ return fmt.Errorf("marshal openclaw discovery cache: %w", err)+ }+ dir := filepath.Dir(cachePath)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return fmt.Errorf("create openclaw discovery cache dir: %w", err)+ }+ tmp, err := os.CreateTemp(dir, openclawDiscoveryCacheFile+".*")+ if err != nil {+ return fmt.Errorf("create openclaw discovery cache temp: %w", err)+ }+ tmpName := tmp.Name()+ defer func() {+ // Best-effort cleanup of the temp file when the rename never happened.+ _ = os.Remove(tmpName)+ }()+ // 0o600 — the entry holds config paths and the user's agent ids, which is+ // the same posture the per-task wrapper already uses.+ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return fmt.Errorf("chmod openclaw discovery cache temp: %w", err)+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return fmt.Errorf("write openclaw discovery cache temp: %w", err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("close openclaw discovery cache temp: %w", err)+ }+ if err := os.Rename(tmpName, cachePath); err != nil {+ return fmt.Errorf("commit openclaw discovery cache: %w", err)+ }+ return nil+}++// decodeOpenclawCachedAgentsList converts a cached agents.list payload back+// into the []any shape prepareOpenclawConfig works with.+// A stored JSON null decodes to a nil slice, which is exactly the shape+// openclawResolvedAgentsList produces for "no agents", so a hit and a live run+// build the same wrapper.+func decodeOpenclawCachedAgentsList(raw json.RawMessage) ([]any, error) {+ if len(raw) == 0 {+ return nil, errors.New("empty cached agents list")+ }+ var list []any+ if err := json.Unmarshal(raw, &list); err != nil {+ return nil, err+ }+ return list, nil+}diff --git a/server/internal/daemon/execenv/openclaw_config_cache_test.go b/server/internal/daemon/execenv/openclaw_config_cache_test.gonew file mode 100644index 0000000000..d66c2e7d6f--- /dev/null+++ b/server/internal/daemon/execenv/openclaw_config_cache_test.go@@ -0,0 +1,416 @@+package execenv++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++// openclawCacheFixture is one host: a real (fake) openclaw binary file, a real+// user config file, a cache directory, and a stubbed CLI that counts calls.+// The binary and config have to exist on disk because the cache fingerprint+// stats both — that is the whole invalidation mechanism.+type openclawCacheFixture struct {+ bin string+ configPath string+ cacheDir string+ stub *openclawCLIStub+}++func newOpenclawCacheFixture(t *testing.T) *openclawCacheFixture {+ t.Helper()+ dir := t.TempDir()+ bin := filepath.Join(dir, "openclaw")+ if err := os.WriteFile(bin, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {+ t.Fatalf("write fake openclaw binary: %v", err)+ }+ configPath := filepath.Join(dir, "openclaw.json")+ if err := os.WriteFile(configPath, []byte(`{ "agents": { "list": [] } }`), 0o600); err != nil {+ t.Fatalf("write user config: %v", err)+ }+ stub := installOpenclawStub(t, map[string]openclawResponse{+ "config file": {stdout: configPath + "\n"},+ "config get agents.list --json": {stdout: `[{"id":"scout"}]`},+ })+ stub.bin = bin+ return &openclawCacheFixture{+ bin: bin,+ configPath: configPath,+ cacheDir: t.TempDir(),+ stub: stub,+ }+}++func (f *openclawCacheFixture) prep() OpenclawConfigPrep {+ return OpenclawConfigPrep{OpenclawBin: f.bin, CacheDir: f.cacheDir}+}++// run executes one full preparation into a throwaway env root and returns how+// many CLI invocations it needed.+func (f *openclawCacheFixture) run(t *testing.T) int {+ t.Helper()+ before := len(f.stub.calls)+ envRoot := t.TempDir()+ workDir := filepath.Join(envRoot, "workdir")+ if err := os.MkdirAll(workDir, 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ if _, err := prepareOpenclawConfig(envRoot, workDir, f.prep()); err != nil {+ t.Fatalf("prepareOpenclawConfig: %v", err)+ }+ return len(f.stub.calls) - before+}++func (f *openclawCacheFixture) cachePath() string {+ return filepath.Join(f.cacheDir, openclawDiscoveryCacheFile)+}++// TestOpenclawDiscoveryCacheServesSecondPreparation is the headline behaviour.+// Discovery is two serial CLI calls that cost ~12.7s on the host in #7112, and+// every task — including every chat message, which goes through Reuse — used+// to pay them again. Raising the deadline without this would trade a hard+// failure for a per-message stall.+func TestOpenclawDiscoveryCacheServesSecondPreparation(t *testing.T) {+ f := newOpenclawCacheFixture(t)++ if got := f.run(t); got != 2 {+ t.Fatalf("cold preparation made %d CLI calls, want 2 (config file + agents.list)", got)+ }+ if got := f.run(t); got != 0 {+ t.Errorf("warm preparation made %d CLI calls, want 0 (served from cache)", got)+ }+}++// TestOpenclawDiscoveryCacheHitProducesSameWrapper guards the actual contract:+// a cache hit has to produce the byte-identical wrapper a live run would, or+// the speedup silently changes what OpenClaw loads.+func TestOpenclawDiscoveryCacheHitProducesSameWrapper(t *testing.T) {+ f := newOpenclawCacheFixture(t)++ read := func() []byte {+ t.Helper()+ envRoot := t.TempDir()+ workDir := filepath.Join(envRoot, "workdir")+ if err := os.MkdirAll(workDir, 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ result, err := prepareOpenclawConfig(envRoot, workDir, f.prep())+ if err != nil {+ t.Fatalf("prepareOpenclawConfig: %v", err)+ }+ raw, err := os.ReadFile(result.ConfigPath)+ if err != nil {+ t.Fatalf("read wrapper: %v", err)+ }+ // The workspace override is env-root specific; normalise it away so the+ // comparison is about the discovered content, not the temp path.+ return []byte(strings.ReplaceAll(string(raw), workDir, "<WORKDIR>"))+ }++ cold := read()+ warm := read()+ if string(cold) != string(warm) {+ t.Errorf("cache hit produced a different wrapper\ncold: %s\nwarm: %s", cold, warm)+ }+}++// TestOpenclawDiscoveryCacheInvalidatesOnConfigChange covers the refresh+// semantics Reuse already promised: a user who adds an agent or rotates a+// provider must not keep getting the stale list for the rest of the TTL.+func TestOpenclawDiscoveryCacheInvalidatesOnConfigChange(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ // Rewrite the active config with different content. Size changes, so this+ // is caught even on filesystems with coarse mtime granularity.+ if err := os.WriteFile(f.configPath, []byte(`{ "agents": { "list": [ { "id": "scout" } ] } }`), 0o600); err != nil {+ t.Fatalf("rewrite user config: %v", err)+ }++ if got := f.run(t); got != 2 {+ t.Errorf("preparation after a config edit made %d CLI calls, want 2 (cache must be invalid)", got)+ }+}++// TestOpenclawDiscoveryCacheInvalidatesOnBinaryChange covers an openclaw+// upgrade in place: same path, new build, potentially a different active+// config or agents schema.+func TestOpenclawDiscoveryCacheInvalidatesOnBinaryChange(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ if err := os.WriteFile(f.bin, []byte("#!/bin/sh\n# upgraded\nexit 0\n"), 0o755); err != nil {+ t.Fatalf("rewrite fake binary: %v", err)+ }++ if got := f.run(t); got != 2 {+ t.Errorf("preparation after a binary upgrade made %d CLI calls, want 2 (cache must be invalid)", got)+ }+}++// TestOpenclawDiscoveryCacheInvalidatesOnEnvChange covers the pointers that+// move the active config without touching any file we stat: OpenClaw's own+// path environment.+func TestOpenclawDiscoveryCacheInvalidatesOnEnvChange(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ t.Setenv("OPENCLAW_STATE_DIR", filepath.Join(t.TempDir(), "state"))++ if got := f.run(t); got != 2 {+ t.Errorf("preparation after an OpenClaw env change made %d CLI calls, want 2 (cache must be invalid)", got)+ }+}++// TestOpenclawDiscoveryCacheExpiresWithTTL covers the drift the fingerprint+// cannot see: a nested `$include` target edited in place, or an agent added+// through OpenClaw's own registry. Neither touches the top-level config, so+// the TTL is the only backstop.+func TestOpenclawDiscoveryCacheExpiresWithTTL(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ raw, err := os.ReadFile(f.cachePath())+ if err != nil {+ t.Fatalf("read cache: %v", err)+ }+ var entry openclawDiscoveryCacheEntry+ if err := json.Unmarshal(raw, &entry); err != nil {+ t.Fatalf("decode cache: %v", err)+ }+ entry.CachedAtNano = time.Now().Add(-openclawDiscoveryCacheTTL - time.Second).UnixNano()+ aged, err := json.Marshal(entry)+ if err != nil {+ t.Fatalf("encode aged cache: %v", err)+ }+ if err := os.WriteFile(f.cachePath(), aged, 0o600); err != nil {+ t.Fatalf("write aged cache: %v", err)+ }++ if got := f.run(t); got != 2 {+ t.Errorf("preparation past the TTL made %d CLI calls, want 2 (entry must expire)", got)+ }+}++// TestOpenclawDiscoveryCacheRejectsFutureEntry keeps a clock jump (or a+// hand-edited file) from pinning an entry that never ages out.+func TestOpenclawDiscoveryCacheRejectsFutureEntry(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ raw, err := os.ReadFile(f.cachePath())+ if err != nil {+ t.Fatalf("read cache: %v", err)+ }+ var entry openclawDiscoveryCacheEntry+ if err := json.Unmarshal(raw, &entry); err != nil {+ t.Fatalf("decode cache: %v", err)+ }+ entry.CachedAtNano = time.Now().Add(time.Hour).UnixNano()+ future, err := json.Marshal(entry)+ if err != nil {+ t.Fatalf("encode future cache: %v", err)+ }+ if err := os.WriteFile(f.cachePath(), future, 0o600); err != nil {+ t.Fatalf("write future cache: %v", err)+ }++ if got := f.run(t); got != 2 {+ t.Errorf("preparation with a future-dated entry made %d CLI calls, want 2", got)+ }+}++// TestOpenclawDiscoveryCacheIgnoresCorruptEntry covers the file a killed+// writer or a full disk can leave behind. A bad cache must degrade to slow,+// never to a failed task.+func TestOpenclawDiscoveryCacheIgnoresCorruptEntry(t *testing.T) {+ for name, body := range map[string]string{+ "truncated json": `{"fingerprint":{"version":1,"bin_pa`,+ "empty file": ``,+ "wrong shape": `["not", "an", "entry"]`,+ "foreign version": `{"fingerprint":{"version":999},"cached_at_nano":1,` ++ `"active_config_path":"/nope","agents_list":[]}`,+ } {+ t.Run(name, func(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ if err := os.WriteFile(f.cachePath(), []byte(body), 0o600); err != nil {+ t.Fatalf("write corrupt cache: %v", err)+ }++ if got := f.run(t); got != 2 {+ t.Errorf("preparation with a corrupt cache made %d CLI calls, want 2 (must fall back to the CLI)", got)+ }+ // And the bad entry must be replaced, not left to poison every+ // later task with the same fallback cost.+ if got := f.run(t); got != 0 {+ t.Errorf("preparation after recovery made %d CLI calls, want 0", got)+ }+ })+ }+}++// TestOpenclawDiscoveryCacheSkipsFreshInstall pins the one state that must+// never be cached: "the user has no config yet" flips the moment they run+// OpenClaw's setup, and a cached miss would keep the next tasks running+// without their models and auth profiles.+func TestOpenclawDiscoveryCacheSkipsFreshInstall(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ missingPath := filepath.Join(t.TempDir(), "openclaw.json")+ f.stub.responses["config file"] = openclawResponse{stdout: missingPath + "\n"}++ f.run(t)++ if _, err := os.Stat(f.cachePath()); !errors.Is(err, os.ErrNotExist) {+ t.Errorf("fresh install wrote a cache entry (stat err = %v); it must stay uncached", err)+ }+}++// TestOpenclawDiscoveryCacheSkipsFailedDiscovery keeps a transient CLI failure+// from being replayed out of cache — including the timeout this change exists+// for, which would otherwise be served instantly for the rest of the TTL.+func TestOpenclawDiscoveryCacheSkipsFailedDiscovery(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.stub.responses["config get agents.list --json"] = openclawResponse{err: errors.New("boom")}++ envRoot := t.TempDir()+ workDir := filepath.Join(envRoot, "workdir")+ if err := os.MkdirAll(workDir, 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ if _, err := prepareOpenclawConfig(envRoot, workDir, f.prep()); err == nil {+ t.Fatal("expected the agents.list failure to fail preparation")+ }++ if _, err := os.Stat(f.cachePath()); !errors.Is(err, os.ErrNotExist) {+ t.Errorf("failed discovery wrote a cache entry (stat err = %v); failures must stay uncached", err)+ }+}++// TestOpenclawDiscoveryCacheConcurrentPreparations covers several tasks+// starting at once on the same daemon: the writes are atomic, so every task+// either sees a complete old entry or a complete new one, and none of them+// fails.+func TestOpenclawDiscoveryCacheConcurrentPreparations(t *testing.T) {+ f := newOpenclawCacheFixture(t)++ const workers = 8+ var wg sync.WaitGroup+ var mu sync.Mutex+ var failures []error+ for i := 0; i < workers; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ envRoot := t.TempDir()+ workDir := filepath.Join(envRoot, "workdir")+ if err := os.MkdirAll(workDir, 0o755); err != nil {+ mu.Lock()+ failures = append(failures, err)+ mu.Unlock()+ return+ }+ // Each worker gets its own stub-free path into discovery: the+ // shared stub is not goroutine-safe, so drive the cache directly+ // with the same store/load pair preparation uses.+ if err := storeOpenclawDiscoveryCache(f.cachePath(), f.bin, f.configPath, []any{map[string]any{"id": "scout"}}, false, time.Now()); err != nil {+ mu.Lock()+ failures = append(failures, err)+ mu.Unlock()+ return+ }+ if _, ok := loadOpenclawDiscoveryCache(f.cachePath(), f.bin, time.Now()); !ok {+ mu.Lock()+ failures = append(failures, errors.New("cache load failed under concurrency"))+ mu.Unlock()+ }+ }()+ }+ wg.Wait()+ for _, err := range failures {+ t.Errorf("concurrent cache use: %v", err)+ }++ // No half-written temp files may survive a clean run.+ entries, err := os.ReadDir(f.cacheDir)+ if err != nil {+ t.Fatalf("read cache dir: %v", err)+ }+ for _, entry := range entries {+ if entry.Name() != openclawDiscoveryCacheFile {+ t.Errorf("leftover file in cache dir: %s", entry.Name())+ }+ }+}++// TestOpenclawDiscoveryCacheDisabledWithoutDir pins the opt-out: with no cache+// directory (profile resolution failed), preparation still works and simply+// pays the CLI every time.+func TestOpenclawDiscoveryCacheDisabledWithoutDir(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.cacheDir = ""++ if got := f.run(t); got != 2 {+ t.Fatalf("first preparation made %d CLI calls, want 2", got)+ }+ if got := f.run(t); got != 2 {+ t.Errorf("second preparation made %d CLI calls, want 2 (caching must stay off)", got)+ }+}++// TestOpenclawDiscoveryCacheStoresEmptyAgentsList covers Elon's must-fix 2.+// openclawResolvedAgentsList returns (nil, false, nil) for two legitimate+// successes — a config whose agents.list is null, and an empty 2026.6++// registry. Treating a nil list as "incomplete, do not cache" left exactly+// those users paying full discovery on every message, which is the cost this+// change exists to remove.+func TestOpenclawDiscoveryCacheStoresEmptyAgentsList(t *testing.T) {+ cases := map[string]map[string]openclawResponse{+ "config agents.list is null": {+ "config get agents.list --json": {stdout: "null"},+ },+ "registry is empty": {+ "config get agents.list --json": {err: errors.New("Config path not found: agents.list")},+ "agents list --json": {stdout: "[]"},+ },+ }+ for name, responses := range cases {+ t.Run(name, func(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ for args, resp := range responses {+ f.stub.responses[args] = resp+ }++ cold := f.run(t)+ if cold == 0 {+ t.Fatalf("cold preparation made no CLI calls, want a live discovery")+ }+ if got := f.run(t); got != 0 {+ t.Errorf("warm preparation made %d CLI calls, want 0: an agent-less host must be cacheable too", got)+ }+ })+ }+}++// TestOpenclawDiscoveryCacheInvalidatesOnLegacyEnvChange covers must-fix 3.+// openclawFallbackConfigCandidates still honours the CLAWDBOT_* names, so a+// user who repoints those and restarts the daemon must not keep getting the+// pre-switch config served out of a cache that never looked at them.+func TestOpenclawDiscoveryCacheInvalidatesOnLegacyEnvChange(t *testing.T) {+ for _, envVar := range []string{"CLAWDBOT_CONFIG_PATH", "CLAWDBOT_STATE_DIR"} {+ t.Run(envVar, func(t *testing.T) {+ f := newOpenclawCacheFixture(t)+ f.run(t)++ t.Setenv(envVar, filepath.Join(t.TempDir(), "legacy"))++ if got := f.run(t); got != 2 {+ t.Errorf("preparation after %s changed made %d CLI calls, want 2 (cache must be invalid)", envVar, got)+ }+ })+ }+}diff --git a/server/internal/daemon/execenv/openclaw_config_timeout_test.go b/server/internal/daemon/execenv/openclaw_config_timeout_test.gonew file mode 100644index 0000000000..f0379e5588--- /dev/null+++ b/server/internal/daemon/execenv/openclaw_config_timeout_test.go@@ -0,0 +1,234 @@+package execenv++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++// slowestMeasuredOpenclawCall is the worst `openclaw config file` timing+// reported from the field (#7112): 10.86s on a 2020 Intel MacBook Pro, with+// 8.41s and 10.35s on the same host. It is a floor for what the default+// deadline must tolerate, not a target.+const slowestMeasuredOpenclawCall = 10860 * time.Millisecond++// TestOpenclawCLIDefaultTimeoutCoversMeasuredSlowHosts is the regression for+// the reported bug. The old 5s default was written against an assumed <200ms+// CLI; the reporter's host needs twice that budget for a single call, every+// time, and had no way to raise it — so the OpenClaw runtime was unusable+// there. Anything that lowers this default back under the measured range+// re-breaks that host.+func TestOpenclawCLIDefaultTimeoutCoversMeasuredSlowHosts(t *testing.T) {+ if openclawCLITimeout <= slowestMeasuredOpenclawCall {+ t.Errorf("default openclaw CLI timeout %v must exceed the slowest measured call %v (#7112)",+ openclawCLITimeout, slowestMeasuredOpenclawCall)+ }+ // Headroom, not a bare pass: a host at the measured worst case should not+ // sit one scheduling hiccup away from failing again.+ if openclawCLITimeout < 2*slowestMeasuredOpenclawCall {+ t.Errorf("default openclaw CLI timeout %v leaves less than 2x headroom over %v",+ openclawCLITimeout, slowestMeasuredOpenclawCall)+ }+}++func TestResolveOpenclawCLITimeout(t *testing.T) {+ cases := []struct {+ name string+ explicit time.Duration+ env string+ want time.Duration+ }{+ {name: "unset uses the default", want: openclawCLITimeout},+ {name: "explicit wins over env", explicit: 3 * time.Second, env: "90s", want: 3 * time.Second},+ {name: "duration string", env: "45s", want: 45 * time.Second},+ {name: "bare seconds", env: "45", want: 45 * time.Second},+ {name: "minutes past the ceiling are clamped", env: "1m30s", want: openclawCLIMaxTimeout},+ {name: "large bare seconds are clamped", env: "3600", want: openclawCLIMaxTimeout},+ // Past time.Duration's range there is nothing to clamp: parsing fails+ // and the default applies. Worth pinning because the old Atoi path+ // silently produced a negative duration here instead of failing.+ {name: "bare seconds beyond time.Duration fall back", env: "99999999999999999999", want: openclawCLITimeout},+ // A typo must degrade to the default rather than disabling the+ // deadline or failing task preparation outright.+ {name: "unparseable falls back", env: "soon", want: openclawCLITimeout},+ {name: "empty falls back", env: " ", want: openclawCLITimeout},+ {name: "zero falls back", env: "0", want: openclawCLITimeout},+ {name: "negative falls back", env: "-5s", want: openclawCLITimeout},+ // Clamped, not honoured: too small breaks every host, too large eats+ // the outer preparation budget.+ {name: "below the floor is clamped", env: "10ms", want: openclawCLIMinTimeout},+ {name: "above the ceiling is clamped", env: "30m", want: openclawCLIMaxTimeout},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Setenv(OpenclawCLITimeoutEnv, tc.env)+ if got := resolveOpenclawCLITimeout(tc.explicit, nil); got != tc.want {+ t.Errorf("resolveOpenclawCLITimeout(%v, env=%q) = %v, want %v", tc.explicit, tc.env, got, tc.want)+ }+ })+ }+}++// TestExecOpenclawCLITimeoutIsTypedSentinel is what lets the daemon classify a+// local CLI stall structurally. Before this, the only signal was the words+// "deadline exceeded" in the message, which the shared classifier maps to+// agent_error.provider_network — "check your network" copy plus an auto-retry,+// for a failure that is local and repeats identically.+//+// The pre-existing context contract must survive alongside it: callers that+// check errors.Is(err, context.DeadlineExceeded) keep working.+func TestExecOpenclawCLITimeoutIsTypedSentinel(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell shim shape is covered by the windows-tagged tests")+ }+ sleepBin, err := exec.LookPath("sleep")+ if err != nil {+ t.Skipf("no sleep binary available to build a slow shim: %v", err)+ }+ shim := writeShim(t, t.TempDir(), "#!/bin/sh\n"+sleepBin+" 1\n", "")++ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)+ defer cancel()+ _, err = execOpenclawCLI(ctx, shim, "config", "file")+ if err == nil {+ t.Fatal("expected the timed-out invocation to fail")+ }+ if !errors.Is(err, ErrOpenclawCLITimeout) {+ t.Errorf("errors.Is(err, ErrOpenclawCLITimeout) must hold\ngot: %s", err)+ }+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Errorf("errors.Is(err, context.DeadlineExceeded) must keep holding\ngot: %s", err)+ }+ if !errors.Is(err, ErrOpenclawCLITimeout) || errors.Is(errors.New("openclaw config file: boom"), ErrOpenclawCLITimeout) {+ t.Errorf("the sentinel must not match unrelated CLI failures")+ }+}++// TestPrepareOpenclawConfigPropagatesTimeoutSentinel proves the sentinel+// survives the wrapping prepareOpenclawConfig does on the way out, which is+// what the daemon actually classifies.+func TestPrepareOpenclawConfigPropagatesTimeoutSentinel(t *testing.T) {+ stub := installOpenclawStub(t, map[string]openclawResponse{+ "config file": {err: &openclawCLITimeoutError{+ msg: "openclaw config file: context deadline exceeded (process: signal: killed)",+ cause: context.DeadlineExceeded,+ }},+ })++ envRoot := t.TempDir()+ _, err := prepareOpenclawConfig(envRoot, envRoot, OpenclawConfigPrep{OpenclawBin: stub.bin})+ if err == nil {+ t.Fatal("expected preparation to fail on a CLI timeout")+ }+ if !errors.Is(err, ErrOpenclawCLITimeout) {+ t.Errorf("wrapped preparation error must keep the sentinel\ngot: %s", err)+ }+}++// TestExecOpenclawCLICancellationIsNotATimeout keeps the sentinel honest. A+// daemon shutdown or a cancelled task also lands in the cancellation branch,+// but it is not a slow CLI — labelling it as one would tell the user to raise+// a deadline that was never involved.+func TestExecOpenclawCLICancellationIsNotATimeout(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell shim shape is covered by the windows-tagged tests")+ }+ sleepBin, err := exec.LookPath("sleep")+ if err != nil {+ t.Skipf("no sleep binary available to build a slow shim: %v", err)+ }+ shim := writeShim(t, t.TempDir(), "#!/bin/sh\n"+sleepBin+" 5\n", "")++ ctx, cancel := context.WithCancel(context.Background())+ go func() {+ time.Sleep(50 * time.Millisecond)+ cancel()+ }()+ defer cancel()+ _, err = execOpenclawCLI(ctx, shim, "config", "file")+ if err == nil {+ t.Fatal("expected the cancelled invocation to fail")+ }+ if errors.Is(err, ErrOpenclawCLITimeout) {+ t.Errorf("cancellation must not be reported as a CLI timeout\ngot: %s", err)+ }+ if !errors.Is(err, context.Canceled) {+ t.Errorf("cancellation must keep the wrapped context cause\ngot: %s", err)+ }+}++// TestOpenclawCLIMaxTimeoutFitsPreparationBudget is the arithmetic the+// override ceiling rests on. Each CLI call gets its own deadline, so the+// budget that matters is worst-case-calls x ceiling, and it has to stay under+// the daemon's 5-minute task preparation deadline with room for the rest of+// Prepare (repo checkout, skills, context files). Otherwise a user who raises+// the timeout turns a specific, non-retryable CLI timeout back into the+// generic — and retryable — prepare timeout, which is the failure mode this+// change set out to remove.+func TestOpenclawCLIMaxTimeoutFitsPreparationBudget(t *testing.T) {+ // Mirrors daemon.defaultTaskPrepareTimeout, which execenv cannot import+ // (the daemon imports this package, not the other way round).+ const taskPrepareBudget = 5 * time.Minute+ // Everything Prepare does besides openclaw config discovery.+ const nonOpenclawPrepareSlack = time.Minute++ worst := openclawMaxCLICallsPerPreparation * openclawCLIMaxTimeout+ if worst+nonOpenclawPrepareSlack > taskPrepareBudget {+ t.Errorf("worst-case openclaw discovery %v (%d calls x %v) leaves less than %v under the %v preparation budget",+ worst, openclawMaxCLICallsPerPreparation, openclawCLIMaxTimeout, nonOpenclawPrepareSlack, taskPrepareBudget)+ }+ if openclawCLITimeout > openclawCLIMaxTimeout {+ t.Errorf("default %v exceeds the override ceiling %v", openclawCLITimeout, openclawCLIMaxTimeout)+ }+}++// TestPrepareOpenclawConfigWorstCaseCLICallCount pins the multiplier the+// budget above depends on. The worst case is not the common two calls: a+// 2026.6+ host falls back to the registry subcommand, and an agent with a+// managed mcp_config additionally reads the full resolved config. Adding a+// fifth call site without re-deriving the ceiling would silently push the+// worst case past the preparation budget, so this fails instead.+func TestPrepareOpenclawConfigWorstCaseCLICallCount(t *testing.T) {+ envRoot := t.TempDir()+ workDir := filepath.Join(envRoot, "workdir")+ if err := os.MkdirAll(workDir, 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ userConfigPath := filepath.Join(t.TempDir(), "openclaw.json")+ if err := os.WriteFile(userConfigPath, []byte(`{}`), 0o600); err != nil {+ t.Fatalf("write user cfg: %v", err)+ }++ stub := installOpenclawStub(t, map[string]openclawResponse{+ // 1. locate the active config+ "config file": {stdout: userConfigPath},+ // 2. pre-2026.6 schema read, which this host does not have+ "config get agents.list --json": {err: errors.New("Config path not found: agents.list")},+ // 3. registry fallback+ "agents list --json": {stdout: `[{"id":"scout"}]`},+ // 4. full resolved config, reached only via a managed mcp_config+ "config get --json": {stdout: `{"agents":{"list":[{"id":"scout"}]}}`},+ })++ if _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{+ OpenclawBin: stub.bin,+ McpConfig: []byte(`{"mcpServers":{"fs":{"command":"fs-server"}}}`),+ }); err != nil {+ t.Fatalf("prepareOpenclawConfig: %v", err)+ }++ if got := len(stub.calls); got != openclawMaxCLICallsPerPreparation {+ var args []string+ for _, call := range stub.calls {+ args = append(args, strings.Join(call.args, " "))+ }+ t.Errorf("worst-case preparation made %d CLI calls, but openclawMaxCLICallsPerPreparation is %d\ncalls: %v",+ got, openclawMaxCLICallsPerPreparation, args)+ }+}diff --git a/server/internal/daemon/openclaw_cli_timeout_test.go b/server/internal/daemon/openclaw_cli_timeout_test.gonew file mode 100644index 0000000000..abae467b16--- /dev/null+++ b/server/internal/daemon/openclaw_cli_timeout_test.go@@ -0,0 +1,50 @@+package daemon++import (+ "context"+ "errors"+ "fmt"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++// TestTaskRunFailureReasonLabelsOpenclawCLITimeout is the daemon half of the+// #7112 fix. The error text ends in "context deadline exceeded", which+// taskfailure.Classify maps to agent_error.provider_network — so before the+// sentinel, a local `openclaw config file` stall was reported to the user as a+// dropped connection to the model provider, and auto-retried because that+// reason is on the retry allowlist. The stall is local and deterministic: the+// retry re-pays the same 8-11s and fails identically.+func TestTaskRunFailureReasonLabelsOpenclawCLITimeout(t *testing.T) {+ err := fmt.Errorf(+ "prepare execution environment: execenv: prepare openclaw config: locate openclaw active config: %w",+ fmt.Errorf("openclaw config file: context deadline exceeded (process: signal: killed): %w", execenv.ErrOpenclawCLITimeout),+ )++ want := taskfailure.ReasonRuntimeCLITimeout.String()+ if got := taskRunFailureReason(err); got != want {+ t.Errorf("taskRunFailureReason = %q, want %q", got, want)+ }++ // The reason must stay off the auto-retry allowlist (asserted next to that+ // table in internal/service): nothing about the host changes between+ // attempts, so a retry only burns another full preparation before failing+ // the same way.+}++// TestTaskRunFailureReasonKeepsProviderDeadline pins the other side of the+// same boundary: a real provider-side deadline (no sentinel) must keep landing+// in the retryable provider bucket.+func TestTaskRunFailureReasonKeepsProviderDeadline(t *testing.T) {+ err := fmt.Errorf("stream from provider: %w", context.DeadlineExceeded)++ want := taskfailure.ReasonAgentProviderNetwork.String()+ if got := taskRunFailureReason(err); got != want {+ t.Errorf("taskRunFailureReason = %q, want %q", got, want)+ }+ if errors.Is(err, execenv.ErrOpenclawCLITimeout) {+ t.Error("a bare context deadline must not match the openclaw CLI sentinel")+ }+}diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.goindex e8b21ccbf1..44e4c26611 100644--- a/server/internal/service/task_complete_race_test.go+++ b/server/internal/service/task_complete_race_test.go@@ -282,6 +282,29 @@ func TestTaskFailureClassifiers(t *testing.T) {}}+// TestRuntimeCLITimeoutIsNotAutoRetried pins the retry posture for #7112. A+// local runtime CLI that missed its preparation deadline is not transient: the+// same host runs the same CLI on the next attempt and takes the same 8-11s to+// fail again, so every retry is pure cost with a guaranteed outcome. That is+// the difference from agent_error.provider_network, which the old text-based+// classification lumped it in with — and which IS on the allowlist.+//+// Resume stays safe: the agent process never started, so the session the retry+// (or the user's next message) resumes is untouched.+func TestRuntimeCLITimeoutIsNotAutoRetried(t *testing.T) {+ const reason = "runtime_cli_timeout"++ if retryableReasons[reason] {+ t.Errorf("retryableReasons[%q] = true, want false: the stall is local and deterministic", reason)+ }+ if resumeUnsafeFailureReason(reason) {+ t.Errorf("resumeUnsafeFailureReason(%q) = true, want false: the agent never started", reason)+ }+ if !retryableReasons["agent_error.provider_network"] {+ t.Error("agent_error.provider_network must stay retryable: real provider stalls are transient")+ }+}+// TestOpencodeStreamEndedFailureRetries walks the full chain for #6522: the// error string pkg/agent/opencode.go's terminal-signal guard produces, through// taskfailure.Classify, into the retry gate.diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex dfa72b9d73..af451f5ae6 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -371,6 +371,32 @@ var legacyContextOverflowReasons = map[string]bool{"agent_error": true,}+// legacyOpenclawCLITimeoutWitnesses identify an OpenClaw config-discovery+// timeout in the wire text of a daemon that predates the sentinel+// (execenv.ErrOpenclawCLITimeout). Both halves must appear: the prep-stage+// wrapper naming this exact call site, and the deadline phrase. That pair is+// only produced by execOpenclawCLI's cancellation branch.+var legacyOpenclawCLITimeoutWitnesses = []string{+ "prepare openclaw config",+ "deadline exceeded",+}++// legacyOpenclawCLITimeoutReasons are the buckets an older daemon lands that+// timeout in. provider_network is what its own rule 7 produces from+// "deadline exceeded" text, and agent_error / agent_error.unknown cover the+// coarser pre-MUL-1949 shapes.+//+// Worth upgrading at the server rather than waiting for the fleet: the stale+// label is not merely imprecise, it is actively harmful — it puts a+// deterministic local failure on the retry allowlist (each retry re-pays the+// same 8-11s and fails identically) and shows "check your network" copy for a+// stall that has nothing to do with the network (#7112).+var legacyOpenclawCLITimeoutReasons = map[string]bool{+ string(ReasonAgentUnknown): true,+ string(ReasonAgentProviderNetwork): true,+ "agent_error": true,+}+// opencodeStreamEndedPrefix opens every failure the OpenCode terminal-signal// guard raises (pkg/agent/opencode.go). Exactly one code path emits it, and it// is a PREFIX of the whole error rather than a phrase somewhere inside it, so@@ -438,9 +464,30 @@ func NormalizeDaemonReason(reason, rawError string) Reason {strings.HasPrefix(strings.ToLower(strings.TrimSpace(rawError)), opencodeStreamEndedPrefix) {return ReasonAgentProviderNetwork}+ // #7112: same mixed-version gap. A daemon predating the OpenClaw CLI+ // timeout sentinel reports provider_network for a local config-discovery+ // stall, which both misleads the user and burns auto-retries on a failure+ // that cannot succeed until the host gets faster or the deadline is raised.+ if legacyOpenclawCLITimeoutReasons[reason] &&+ containsAll(strings.ToLower(rawError), legacyOpenclawCLITimeoutWitnesses...) {+ return ReasonRuntimeCLITimeout+ }return Reason(reason)}+// containsAll reports whether s contains every one of the supplied substrings.+// Used where a single phrase would be ambiguous and only the combination+// identifies the failure. Caller pre-lowercases s, same contract as+// containsAny.+func containsAll(s string, subs ...string) bool {+ for _, sub := range subs {+ if !strings.Contains(s, sub) {+ return false+ }+ }+ return len(subs) > 0+}+// containsAny reports whether s contains any of the supplied substrings.// Caller is responsible for lowercasing s ahead of time so the helper// stays cheap on the hot path — pre-lowercasing once is faster thandiff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.goindex 1d3e2454ab..84de211164 100644--- a/server/pkg/taskfailure/classify_test.go+++ b/server/pkg/taskfailure/classify_test.go@@ -498,3 +498,72 @@ func TestProviderUnconfiguredAgreesWithClassify(t *testing.T) {t.Errorf("Classify(%q) = %q, want %q", errText, got, ReasonAgentMissingConfig)}}++// TestNormalizeDaemonReasonUpgradesOpenclawCLITimeout covers the mixed-version+// window for #7112. A daemon that predates the timeout sentinel classifies the+// failure from its text and lands on agent_error.provider_network, which is+// worse than merely imprecise: that reason is on the auto-retry allowlist, so+// every attempt re-pays the same 8-11s stall and fails identically, and the+// chat bubble tells the user to check a network that was never involved.+// Recognising the wire shape fixes both the moment the server deploys.+func TestNormalizeDaemonReasonUpgradesOpenclawCLITimeout(t *testing.T) {+ t.Parallel()++ const rawError = "prepare execution environment: execenv: prepare openclaw config: " ++ "locate openclaw active config: openclaw config file: context deadline exceeded " ++ "(process: signal: killed)"++ for _, legacy := range []string{+ string(ReasonAgentProviderNetwork),+ string(ReasonAgentUnknown),+ "agent_error",+ } {+ if got := NormalizeDaemonReason(legacy, rawError); got != ReasonRuntimeCLITimeout {+ t.Errorf("NormalizeDaemonReason(%q, openclaw timeout) = %q, want %q", legacy, got, ReasonRuntimeCLITimeout)+ }+ }++ // A current daemon already reports the precise reason; normalization must+ // leave it alone.+ if got := NormalizeDaemonReason(string(ReasonRuntimeCLITimeout), rawError); got != ReasonRuntimeCLITimeout {+ t.Errorf("NormalizeDaemonReason(runtime_cli_timeout) = %q, want it preserved", got)+ }++ // Both witnesses are required. A real provider-side deadline, and an+ // openclaw prep failure that is not a timeout, must keep their own+ // classification — the global "deadline exceeded" rule still belongs to+ // genuine network stalls.+ unrelated := map[string]struct {+ reason string+ rawError string+ want Reason+ }{+ "provider deadline stays provider_network": {+ reason: string(ReasonAgentProviderNetwork),+ rawError: "API Error: context deadline exceeded while streaming from provider",+ want: ReasonAgentProviderNetwork,+ },+ "openclaw prep failure without a timeout is untouched": {+ reason: string(ReasonAgentUnknown),+ rawError: "execenv: prepare openclaw config: read openclaw agents.list: exit status 1",+ want: ReasonAgentUnknown,+ },+ }+ for name, tc := range unrelated {+ if got := NormalizeDaemonReason(tc.reason, tc.rawError); got != tc.want {+ t.Errorf("%s: NormalizeDaemonReason = %q, want %q", name, got, tc.want)+ }+ }+}++// TestClassifyKeepsDeadlineExceededAsProviderNetwork pins the rule the fix+// deliberately did NOT touch. Local runtime CLI timeouts are recognised+// structurally, upstream of Classify; the text rule still has to serve real+// provider stalls, which are transient and retryable.+func TestClassifyKeepsDeadlineExceededAsProviderNetwork(t *testing.T) {+ t.Parallel()++ if got := Classify("post to provider: context deadline exceeded"); got != ReasonAgentProviderNetwork {+ t.Errorf("Classify(provider deadline) = %q, want %q", got, ReasonAgentProviderNetwork)+ }+}diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex 430e7be85d..2a3846e646 100644--- a/server/pkg/taskfailure/failure.go+++ b/server/pkg/taskfailure/failure.go@@ -25,7 +25,8 @@//// queued_expired, runtime_offline, runtime_reconnect_timeout,// runtime_recovery, timeout, iteration_limit, agent_blocked,-// api_invalid_request, skill_bundle_unavailable+// api_invalid_request, skill_bundle_unavailable,+// runtime_cli_timeout//// - 14 agent-side values (with `agent_error.` prefix) produced by// Classify(rawError) when the agent process surfaced an error string.@@ -117,6 +118,19 @@ const (// taskRunFailureReason in daemon/daemon.go.ReasonSkillBundleUnavailable Reason = "skill_bundle_unavailable"+ // ReasonRuntimeCLITimeout: a local runtime CLI the daemon must call+ // during task preparation did not answer within its deadline — today+ // that is OpenClaw config discovery (`openclaw config file`), which on+ // a slow host takes 8-11s against a deadline that used to be 5s+ // (#7112). Platform-side: the agent process was never launched and no+ // provider was contacted. Deliberately NOT retryable — the stall is+ // local and deterministic, so retrying re-pays the same wall-clock and+ // fails identically. The user-facing fix is to raise+ // MULTICA_OPENCLAW_CLI_TIMEOUT or speed the CLI up, which is why the+ // copy names the CLI instead of blaming the network. Written by+ // taskRunFailureReason in daemon/daemon.go.+ ReasonRuntimeCLITimeout Reason = "runtime_cli_timeout"+// Agent process side: failure surfaced by the agent CLI / SDK as// an error string. Classify(rawError) is responsible for picking// the right sub-reason from the string. IsAgentError returns true@@ -192,7 +206,7 @@ const (ReasonAgentUnknown Reason = "agent_error.unknown")-// allReasons is the canonical ordered list of the 22 reasons. Order is+// allReasons is the canonical ordered list of the 24 reasons. Order is// stable so callers (e.g. Prometheus collectors that pre-warm series via// AllReasons) can build deterministic label sets across restarts.//@@ -212,6 +226,7 @@ var allReasons = []Reason{ReasonAgentBlocked,ReasonAPIInvalidRequest,ReasonSkillBundleUnavailable,+ ReasonRuntimeCLITimeout,// Agent process side: provider errors.ReasonAgentProviderAuthOrAccess,diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.goindex 1080fff541..ac9f619602 100644--- a/server/pkg/taskfailure/failure_test.go+++ b/server/pkg/taskfailure/failure_test.go@@ -114,8 +114,8 @@ func TestAllReasonsContents(t *testing.T) {t.Parallel()got := AllReasons()- if len(got) != 23 {- t.Fatalf("AllReasons() returned %d entries, want 23", len(got))+ if len(got) != 24 {+ t.Fatalf("AllReasons() returned %d entries, want 24", len(got))}seen := make(map[Reason]bool, len(got))@@ -132,8 +132,8 @@ func TestAllReasonsContents(t *testing.T) {}}- if platformCount != 9 {- t.Errorf("AllReasons(): platform-side count = %d, want 9", platformCount)+ if platformCount != 10 {+ t.Errorf("AllReasons(): platform-side count = %d, want 10", platformCount)}if agentCount != 14 {t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)@@ -148,6 +148,7 @@ func TestAllReasonsContents(t *testing.T) {ReasonRuntimeRecovery,ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,+ ReasonRuntimeCLITimeout,ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,ReasonAgentProviderNetwork, ReasonAgentProcessFailure,