Skip to content

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

Go

feat(daemon): configurable OpenClaw binary path / state dir via CLIConfig.Backends (MUL-3157)

Chenyu-246018b94764c4717
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index 5188116ab5..0419f23dcc 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -16,6 +16,56 @@ type CLIConfig struct {
AppURL string `json:"app_url,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
Token string `json:"token,omitempty"`
+
+ // Backends contains per-backend overrides for users who want to point
+ // the daemon at non-default tool installations (e.g. an OpenClaw bundled
+ // inside another desktop app, or multiple isolated profiles on the same
+ // machine). Empty / absent means "discover from PATH and use vendor
+ // defaults" — the historical behavior. See issue #3875.
+ Backends *BackendOverrides `json:"backends,omitempty"`
+}
+
+// BackendOverrides holds per-backend configuration overrides. Each field is
+// optional; nil means "no override for this backend". Keep new fields additive
+// and tagged with `json:",omitempty"` so empty values do not change the saved
+// config shape. Unknown-key preservation is a separate forward-compat concern:
+// Go's encoding/json drops fields that are not represented in this struct on
+// load/save round-trip (see TestCLIConfig_UnknownFieldsArePreserved).
+type BackendOverrides struct {
+ OpenClaw *OpenClawOverride `json:"openclaw,omitempty"`
+}
+
+// OpenClawOverride configures the OpenClaw backend. All fields are optional;
+// empty values fall through to the existing discovery path (PATH lookup for
+// BinaryPath, default `~/.openclaw/` for StateDir).
+//
+// Resolution precedence (env beats config beats default, for back-compat):
+//
+// 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)
+//
+// 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
+// var, the daemon already forwards inherited env to spawned children via
+// `mergeEnv`, and a user who exports OPENCLAW_STATE_DIR in their shell
+// already gets the right behavior with zero daemon changes today. This field
+// is purely additive: when set, the daemon injects OPENCLAW_STATE_DIR=<value>
+// into the spawned child's env unless the user already exported one upstream.
+// (If a future use case needs daemon-namespaced isolation distinct from
+// OpenClaw's own env, MULTICA_OPENCLAW_STATE_DIR can be layered on top
+// without breaking this contract — see #3875 discussion.)
+//
+// Setting StateDir is the fix for the long-standing usability gap where
+// users with non-default OpenClaw installations — multiple isolated
+// profiles (dev/staging/prod, multiple accounts), containerized / CI
+// deployments where ~/.openclaw isn't writable, or third-party desktop
+// apps that bundle their own OpenClaw runtime — had to write a wrapper
+// shell script to inject OPENCLAW_STATE_DIR + run `launchctl setenv`
+// for GUI-launched daemons. With this field, those workarounds become
+// unnecessary.
+type OpenClawOverride struct {
+ BinaryPath string `json:"binary_path,omitempty"`
+ StateDir string `json:"state_dir,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.go
new file mode 100644
index 0000000000..93ad4cb295
--- /dev/null
+++ b/server/internal/cli/config_test.go
@@ -0,0 +1,213 @@
+package cli
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// TestCLIConfig_BackwardCompat_OldFileLoadsWithNilBackends verifies that a
+// config.json written by an older daemon (no `backends` key at all) loads
+// correctly into the new schema, with Backends == nil. This is the most
+// important guarantee of issue #3875's PR: existing on-disk configs MUST
+// continue to work byte-for-byte.
+func TestCLIConfig_BackwardCompat_OldFileLoadsWithNilBackends(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+
+ // Write a 4-field config exactly as the historical daemon would have.
+ cfgDir := filepath.Join(tmp, ".multica")
+ if err := os.MkdirAll(cfgDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ historical := `{
+ "server_url": "https://api.multica.ai",
+ "app_url": "https://app.multica.ai",
+ "workspace_id": "ws-123",
+ "token": "mul_abcdef"
+}`
+ if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), []byte(historical), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg, err := LoadCLIConfig()
+ if err != nil {
+ t.Fatalf("LoadCLIConfig on historical file: %v", err)
+ }
+
+ if cfg.ServerURL != "https://api.multica.ai" {
+ t.Errorf("ServerURL: got %q, want historical value", cfg.ServerURL)
+ }
+ if cfg.Token != "mul_abcdef" {
+ t.Errorf("Token: got %q, want historical value", cfg.Token)
+ }
+ if cfg.Backends != nil {
+ t.Errorf("Backends should be nil for historical config, got %+v", cfg.Backends)
+ }
+}
+
+// TestCLIConfig_BackwardCompat_NilBackendsOmittedFromJSON verifies that
+// saving a config without backend overrides does NOT add a `backends` key
+// to the on-disk JSON. This matters for users who never set overrides —
+// their config files must stay byte-identical, so a future downgrade to
+// an older daemon doesn't trip on an empty `backends: null` line.
+func TestCLIConfig_BackwardCompat_NilBackendsOmittedFromJSON(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+
+ cfg := CLIConfig{
+ ServerURL: "https://api.multica.ai",
+ Token: "mul_xyz",
+ }
+ if err := SaveCLIConfig(cfg); err != nil {
+ t.Fatal(err)
+ }
+
+ data, err := os.ReadFile(filepath.Join(tmp, ".multica", "config.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) == "" {
+ t.Fatal("config file is empty")
+ }
+
+ // The omitempty tag on Backends should keep it out of the JSON entirely.
+ var raw map[string]any
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("unmarshal saved config: %v", err)
+ }
+ if _, ok := raw["backends"]; ok {
+ t.Errorf("backends key should be omitted when nil, got: %s", string(data))
+ }
+}
+
+// TestCLIConfig_OpenClawOverride_RoundTrip verifies that setting BinaryPath
+// and StateDir survives a save/load cycle.
+func TestCLIConfig_OpenClawOverride_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{
+ BinaryPath: "/opt/openclaw-prod/bin/openclaw",
+ StateDir: "/var/lib/openclaw-prod",
+ },
+ },
+ }
+ 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 loaded.Backends.OpenClaw.BinaryPath != original.Backends.OpenClaw.BinaryPath {
+ t.Errorf("BinaryPath round-trip: got %q, want %q",
+ loaded.Backends.OpenClaw.BinaryPath, original.Backends.OpenClaw.BinaryPath)
+ }
+ if loaded.Backends.OpenClaw.StateDir != original.Backends.OpenClaw.StateDir {
+ t.Errorf("StateDir round-trip: got %q, want %q",
+ loaded.Backends.OpenClaw.StateDir, original.Backends.OpenClaw.StateDir)
+ }
+}
+
+// TestCLIConfig_OpenClawOverride_PartialFieldsOmitted verifies that an
+// override with only one field set does not emit empty strings for the
+// unset field. Important so users can intentionally set only BinaryPath
+// (or only StateDir) and have the other follow the historical default,
+// without an empty string overriding env-var precedence.
+func TestCLIConfig_OpenClawOverride_PartialFieldsOmitted(t *testing.T) {
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+
+ cfg := CLIConfig{
+ ServerURL: "https://api.multica.ai",
+ Token: "mul_xyz",
+ Backends: &BackendOverrides{
+ OpenClaw: &OpenClawOverride{
+ StateDir: "/var/lib/openclaw-prod",
+ // BinaryPath intentionally left empty
+ },
+ },
+ }
+ if err := SaveCLIConfig(cfg); err != nil {
+ t.Fatal(err)
+ }
+
+ data, err := os.ReadFile(filepath.Join(tmp, ".multica", "config.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var raw map[string]any
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatal(err)
+ }
+
+ openclaw, ok := raw["backends"].(map[string]any)["openclaw"].(map[string]any)
+ if !ok {
+ t.Fatalf("could not navigate to backends.openclaw in: %s", string(data))
+ }
+ if _, present := openclaw["binary_path"]; present {
+ t.Errorf("binary_path should be omitted when empty, got: %s", string(data))
+ }
+ if _, present := openclaw["state_dir"]; !present {
+ t.Errorf("state_dir should be present when set, got: %s", string(data))
+ }
+}
+
+// TestCLIConfig_UnknownFieldsArePreserved verifies forward-compat: a future
+// daemon that adds, say, a `backends.codex` key should not have its data
+// destroyed when an older daemon (without knowledge of that key) reads and
+// re-saves the file. Today Go's encoding/json silently DROPS unknown fields
+// on round-trip. This test documents the gap so future maintainers know.
+//
+// Skipped today (encoding/json does not preserve unknown fields), but the
+// test is written so a future change to a preserve-unknown encoder
+// (json.RawMessage, mapstructure, etc.) will pick it up.
+func TestCLIConfig_UnknownFieldsArePreserved(t *testing.T) {
+ t.Skip("documenting known limitation: encoding/json drops unknown fields on round-trip; future PR can switch to a preserving encoder")
+
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+
+ cfgDir := filepath.Join(tmp, ".multica")
+ if err := os.MkdirAll(cfgDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ withFutureField := `{
+ "server_url": "https://api.multica.ai",
+ "token": "mul_xyz",
+ "backends": {
+ "openclaw": {"state_dir": "/x"},
+ "future_backend_xyz": {"some_setting": "preserve me"}
+ }
+}`
+ if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), []byte(withFutureField), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg, err := LoadCLIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SaveCLIConfig(cfg); err != nil {
+ t.Fatal(err)
+ }
+
+ // After round-trip, future_backend_xyz should still be in the file.
+ data, _ := os.ReadFile(filepath.Join(cfgDir, "config.json"))
+ if !strings.Contains(string(data), "future_backend_xyz") {
+ t.Error("unknown field future_backend_xyz was dropped on round-trip")
+ }
+}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 336e8f5ce9..de6160980c 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -3,6 +3,7 @@ package daemon
import (
"context"
"fmt"
+ "log/slog"
"net/url"
"os"
"os/exec"
@@ -12,6 +13,8 @@ import (
"time"
"github.com/mattn/go-shellwords"
+
+ "github.com/multica-ai/multica/server/internal/cli"
)
const (
@@ -137,6 +140,37 @@ func LoadConfig(overrides Overrides) (Config, error) {
return Config{}, err
}
+ // Apply backend overrides from the CLI config file (issue #3875).
+ //
+ // CLIConfig.Backends.OpenClaw lets users record "which OpenClaw on this
+ // machine, and where its state lives" in a versioned, UI-editable file
+ // instead of a launchctl env hack. We translate those fields into the
+ // same env vars the rest of LoadConfig already honors:
+ //
+ // - MULTICA_OPENCLAW_PATH: read by probe() via envOrDefault for the
+ // 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/...).
+ //
+ // Precedence is "env wins over config wins over default" — same shape
+ // users already get with MULTICA_OPENCLAW_PATH today. We achieve it with
+ // LookupEnv guards: if the user already exported the env var (in their
+ // shell, via launchctl, or via the systemd unit), we leave it alone;
+ // otherwise we Setenv from the config file. This keeps every downstream
+ // consumer (probe, buildEnv, child processes) on the existing code path
+ // without inventing a new plumbing channel.
+ //
+ // Errors loading CLIConfig are non-fatal: a missing or malformed config
+ // file should not prevent daemon startup, since the daemon can still run
+ // purely from env-var configuration. We log a warning and proceed with
+ // no overrides.
+ if cliCfg, err := cli.LoadCLIConfigForProfile(overrides.Profile); err != nil {
+ slog.Warn("could not load CLI config for backend overrides; proceeding without",
+ "profile", overrides.Profile, "err", err)
+ } else if oc := openclawOverrideFrom(cliCfg); oc != nil {
+ applyOpenclawOverride(oc)
+ }
+
// Probe available agent CLIs. exec.LookPath is the primary path, but on
// macOS/Linux a GUI-launched daemon (Electron, Launchpad) does not
// inherit the user's interactive shell PATH — fnm/nvm/volta multishells,
@@ -783,3 +817,46 @@ func isSafeAgentName(s string) bool {
}
return true
}
+
+// openclawOverrideFrom returns the OpenClaw override block from a loaded
+// CLIConfig, or nil when no override is configured. Centralized here so
+// the LoadConfig path and tests share one navigation predicate over the
+// nullable-pointer chain.
+func openclawOverrideFrom(cfg cli.CLIConfig) *cli.OpenClawOverride {
+ if cfg.Backends == nil {
+ return nil
+ }
+ return cfg.Backends.OpenClaw
+}
+
+// applyOpenclawOverride translates the config-file overrides into process
+// env vars, which the existing probe() / buildEnv code paths already honor.
+// Env-set-by-user wins over config-set-by-file: we only Setenv when the var
+// is not already present, preserving the back-compat contract documented
+// on cli.OpenClawOverride.
+//
+// Side-effecting on os.Setenv is intentional and scoped:
+//
+// - The two vars touched (MULTICA_OPENCLAW_PATH, OPENCLAW_STATE_DIR) 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.
+// - LoadConfig runs once during daemon startup, before any backend Execute.
+// Concurrent reads of os.Environ() in spawned children see a stable view.
+// - We deliberately do not unset on later reload: the daemon's lifecycle is
+// "exit and respawn" (cmd_daemon.go), not in-process reconfigure.
+func applyOpenclawOverride(oc *cli.OpenClawOverride) {
+ if oc == nil {
+ return
+ }
+ if oc.BinaryPath != "" {
+ if _, set := os.LookupEnv("MULTICA_OPENCLAW_PATH"); !set {
+ _ = os.Setenv("MULTICA_OPENCLAW_PATH", oc.BinaryPath)
+ }
+ }
+ if oc.StateDir != "" {
+ if _, set := os.LookupEnv("OPENCLAW_STATE_DIR"); !set {
+ _ = os.Setenv("OPENCLAW_STATE_DIR", oc.StateDir)
+ }
+ }
+}
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 39ac509690..1a92faffb3 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -6,9 +6,12 @@ import (
"path/filepath"
"reflect"
"runtime"
+ "sort"
"strings"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/internal/cli"
)
func TestPatternsFromEnv_DefaultsWhenUnset(t *testing.T) {
@@ -594,3 +597,263 @@ func pinNonCodexAgentsToMissingPaths(t *testing.T) {
t.Setenv(name, filepath.Join(missingDir, strings.ToLower(name)))
}
}
+
+// =============================================================================
+// CLI config Backends.OpenClaw overrides (issue #3875)
+// =============================================================================
+
+// writeCLIConfigForProfile is a minimal helper for the override tests:
+// stages a HOME, writes a config.json under the given profile (empty profile
+// = default), and returns the resolved path so tests can assert against it.
+func writeCLIConfigForProfile(t *testing.T, profile string, cfg cli.CLIConfig) {
+ t.Helper()
+ tmp := t.TempDir()
+ t.Setenv("HOME", tmp)
+ if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {
+ t.Fatalf("write cli config: %v", err)
+ }
+}
+
+// TestApplyOpenclawOverride_DoesNothingWhenNil verifies the early-return
+// path. A daemon started with no override should not Setenv anything; the
+// existing probe / spawn flow remains undisturbed.
+func TestApplyOpenclawOverride_DoesNothingWhenNil(t *testing.T) {
+ // Pre-set both env vars to known values; verify they survive untouched.
+ t.Setenv("MULTICA_OPENCLAW_PATH", "/before/openclaw")
+ t.Setenv("OPENCLAW_STATE_DIR", "/before/state")
+
+ applyOpenclawOverride(nil)
+
+ if got := os.Getenv("MULTICA_OPENCLAW_PATH"); got != "/before/openclaw" {
+ t.Errorf("MULTICA_OPENCLAW_PATH mutated: got %q, want /before/openclaw", got)
+ }
+ if got := os.Getenv("OPENCLAW_STATE_DIR"); got != "/before/state" {
+ t.Errorf("OPENCLAW_STATE_DIR mutated: got %q, want /before/state", got)
+ }
+}
+
+// TestApplyOpenclawOverride_SetsBothWhenEnvUnset verifies the happy path:
+// neither env var is set, the override has both fields, both env vars get
+// set to the override values.
+func TestApplyOpenclawOverride_SetsBothWhenEnvUnset(t *testing.T) {
+ t.Setenv("MULTICA_OPENCLAW_PATH", "")
+ t.Setenv("OPENCLAW_STATE_DIR", "")
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ t.Cleanup(func() {
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ })
+
+ applyOpenclawOverride(&cli.OpenClawOverride{
+ BinaryPath: "/from/config/openclaw",
+ StateDir: "/from/config/state",
+ })
+
+ if got := os.Getenv("MULTICA_OPENCLAW_PATH"); got != "/from/config/openclaw" {
+ t.Errorf("MULTICA_OPENCLAW_PATH: got %q, want /from/config/openclaw", got)
+ }
+ if got := os.Getenv("OPENCLAW_STATE_DIR"); got != "/from/config/state" {
+ t.Errorf("OPENCLAW_STATE_DIR: got %q, want /from/config/state", got)
+ }
+}
+
+// TestApplyOpenclawOverride_EnvWinsOverConfig is the precedence test
+// agreed with @YOMXXX in #3875 review: an env var set upstream by the user
+// (shell export, launchctl, systemd unit) MUST take precedence over the
+// config-file value. This is the back-compat contract — anyone with
+// MULTICA_OPENCLAW_PATH already in their environment must not see the
+// daemon silently change its meaning when they later add a config file.
+func TestApplyOpenclawOverride_EnvWinsOverConfig(t *testing.T) {
+ // User has already exported these in their shell.
+ t.Setenv("MULTICA_OPENCLAW_PATH", "/from/env/openclaw")
+ t.Setenv("OPENCLAW_STATE_DIR", "/from/env/state")
+
+ applyOpenclawOverride(&cli.OpenClawOverride{
+ BinaryPath: "/from/config/openclaw",
+ StateDir: "/from/config/state",
+ })
+
+ if got := os.Getenv("MULTICA_OPENCLAW_PATH"); got != "/from/env/openclaw" {
+ t.Errorf("MULTICA_OPENCLAW_PATH: env should win, got %q want /from/env/openclaw", got)
+ }
+ if got := os.Getenv("OPENCLAW_STATE_DIR"); got != "/from/env/state" {
+ t.Errorf("OPENCLAW_STATE_DIR: env should win, got %q want /from/env/state", got)
+ }
+}
+
+// TestApplyOpenclawOverride_PartialFields_OnlySetsConfigured verifies that
+// an override with only one field set leaves the other env var alone (does
+// not Setenv to ""). This matters: a user who only configures state_dir
+// must not have their MULTICA_OPENCLAW_PATH discovery path forcibly
+// short-circuited to an empty string.
+func TestApplyOpenclawOverride_PartialFields_OnlySetsConfigured(t *testing.T) {
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ t.Cleanup(func() {
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ })
+
+ applyOpenclawOverride(&cli.OpenClawOverride{
+ StateDir: "/from/config/state",
+ // BinaryPath intentionally empty — must NOT call Setenv("MULTICA_OPENCLAW_PATH", "")
+ })
+
+ if _, set := os.LookupEnv("MULTICA_OPENCLAW_PATH"); set {
+ t.Errorf("MULTICA_OPENCLAW_PATH should remain unset when BinaryPath is empty; got %q", os.Getenv("MULTICA_OPENCLAW_PATH"))
+ }
+ if got := os.Getenv("OPENCLAW_STATE_DIR"); got != "/from/config/state" {
+ t.Errorf("OPENCLAW_STATE_DIR: got %q, want /from/config/state", got)
+ }
+}
+
+// TestOpenclawOverrideFrom_NavigationCases verifies the nullable-pointer
+// chain into Backends.OpenClaw. Three cases that all must safely return
+// nil without panicking: nil Backends, nil OpenClaw inside Backends, and
+// the happy path (returns the inner override unchanged).
+func TestOpenclawOverrideFrom_NavigationCases(t *testing.T) {
+ if got := openclawOverrideFrom(cli.CLIConfig{}); got != nil {
+ t.Errorf("nil Backends should produce nil override, got %+v", got)
+ }
+ if got := openclawOverrideFrom(cli.CLIConfig{Backends: &cli.BackendOverrides{}}); got != nil {
+ t.Errorf("nil OpenClaw inside Backends should produce nil override, got %+v", got)
+ }
+ want := &cli.OpenClawOverride{StateDir: "/x"}
+ got := openclawOverrideFrom(cli.CLIConfig{Backends: &cli.BackendOverrides{OpenClaw: want}})
+ if got != want {
+ t.Errorf("happy path should return inner pointer; got %p want %p", got, want)
+ }
+}
+
+// TestLoadConfig_AppliesBackendOverridesFromConfigFile is the integration
+// test that ties commit 1's schema to commit 2's wire-up: write a config
+// file with backends.openclaw.{binary_path,state_dir}, call LoadConfig
+// (with no env vars set), and verify the openclaw probe picked up the
+// configured BinaryPath and the OPENCLAW_STATE_DIR env var was injected.
+func TestLoadConfig_AppliesBackendOverridesFromConfigFile(t *testing.T) {
+ stageFakeAgent(t)
+ // stageFakeAgent left "claude" on PATH; we also need a fake "openclaw"
+ // at a custom path that the config file points at (mimicking a non-default
+ // installation: another bundled / isolated / CI deployment, etc).
+ customDir := t.TempDir()
+ customOpenclaw := filepath.Join(customDir, "non-default-openclaw")
+ if err := os.WriteFile(customOpenclaw, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
+ t.Fatalf("write fake openclaw: %v", err)
+ }
+
+ // Make sure no env-var override is leaking in from the test runner.
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ t.Cleanup(func() {
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ })
+
+ // Drop a CLI config under the user's HOME (already pointed at TempDir
+ // by stageFakeAgent's t.Setenv chain — but reassert here for clarity).
+ homeForCLIConfig := t.TempDir()
+ t.Setenv("HOME", homeForCLIConfig)
+ cfg := cli.CLIConfig{
+ ServerURL: "http://localhost:8080",
+ Backends: &cli.BackendOverrides{
+ OpenClaw: &cli.OpenClawOverride{
+ BinaryPath: customOpenclaw,
+ StateDir: "/var/lib/openclaw-isolated",
+ },
+ },
+ }
+ if err := cli.SaveCLIConfig(cfg); err != nil {
+ t.Fatalf("save cli config: %v", err)
+ }
+
+ loaded, err := LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+
+ openclaw, ok := loaded.Agents["openclaw"]
+ if !ok {
+ t.Fatalf("agents map missing 'openclaw' key; got keys=%v", agentKeys(loaded.Agents))
+ }
+ if openclaw.Path != customOpenclaw {
+ t.Errorf("openclaw.Path: got %q, want %q (the binary configured in CLI config)", openclaw.Path, customOpenclaw)
+ }
+ if got := os.Getenv("OPENCLAW_STATE_DIR"); got != "/var/lib/openclaw-isolated" {
+ t.Errorf("OPENCLAW_STATE_DIR: got %q, want injected from config", got)
+ }
+}
+
+// TestLoadConfig_BackendOverrides_BackwardCompat_NoConfigFile verifies that
+// the override mechanism is purely additive: a daemon started without any
+// CLI config file (or with an empty one) behaves identically to before
+// commit 1 — agents discovered from PATH, no env injection.
+func TestLoadConfig_BackendOverrides_BackwardCompat_NoConfigFile(t *testing.T) {
+ stageFakeAgent(t)
+
+ // Point HOME at an empty dir — no config.json present.
+ t.Setenv("HOME", t.TempDir())
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ t.Cleanup(func() {
+ os.Unsetenv("MULTICA_OPENCLAW_PATH")
+ os.Unsetenv("OPENCLAW_STATE_DIR")
+ })
+
+ _, err := LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig with no config file should not fail: %v", err)
+ }
+
+ if _, set := os.LookupEnv("OPENCLAW_STATE_DIR"); set {
+ t.Errorf("OPENCLAW_STATE_DIR should remain unset when no config file is present; got %q", os.Getenv("OPENCLAW_STATE_DIR"))
+ }
+}
+
+// TestLoadConfig_BackendOverrides_MalformedConfigFileNonFatal verifies the
+// fail-soft contract documented inline in LoadConfig: a corrupt config.json
+// must not prevent daemon startup. This matters for diskcorruption /
+// partial-write recovery — the daemon should log and proceed using
+// env-var-only configuration.
+func TestLoadConfig_BackendOverrides_MalformedConfigFileNonFatal(t *testing.T) {
+ stageFakeAgent(t)
+ homeDir := t.TempDir()
+ t.Setenv("HOME", homeDir)
+
+ // Write malformed JSON.
+ cfgDir := filepath.Join(homeDir, ".multica")
+ if err := os.MkdirAll(cfgDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), []byte("{not valid json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err := LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig should not fail on malformed config.json: %v", err)
+ }
+ // Should also have logged a slog Warn — we don't assert on the log
+ // output here (avoids brittle string matching), but the build does
+ // make sure log/slog stays imported.
+}
+
+// agentKeys is a tiny helper to make agent-map missing-key error messages
+// readable. Returns sorted keys.
+func agentKeys(m map[string]AgentEntry) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}