Skip to content

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

Go

MUL-7590: fix(execenv): support OpenClaw agents.entries per-agent workspaces (#8678)

Basuotiand2423aa35cbb
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index 7eb4be08ba..7b955c9754 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -135,9 +135,14 @@ const (
// if that did not answer. Two invocations, one deadline: they ask the same
// question and openclawActiveConfigPath shares a context between them
// precisely so the fallback cannot add a fourth budget.
-// 2. `config get agents.list --json` — pre-2026.6 agents schema
+// 2. read the per-agent config the schema is willing to show —
+// `config get agents.list --json` (pre-2026.6 `agents.list[]`), then
+// `config get agents.entries --json` (2026.8+ `agents.entries.<id>`) when
+// the first path is gone. Two invocations, one deadline, for the same
+// reason as (1): both ask what the config schema carries per agent, and
+// the second is only reached when the first reported no such path.
// 3. `agents list --json` — 2026.6+ registry fallback, only
-// reached when (2) reports the config path is missing
+// reached when (2) reports that neither config path exists
//
// It was four until managed MCP stopped reading the user's config: the reset
// stage is a file this package writes, so a managed-MCP agent now costs the same
@@ -370,7 +375,7 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
}
timeout := resolveOpenclawCLITimeout(opts.Timeout, opts.Logger)
- activePath, exists, resolvedList, agentsFromRegistry, cached, err := discoverOpenclawConfig(bin, timeout, opts)
+ activePath, exists, resolvedList, agentsSource, cached, err := discoverOpenclawConfig(bin, timeout, opts)
if err != nil {
return OpenclawConfigResult{}, err
}
@@ -447,7 +452,7 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
}
}
- cfg := buildPerTaskOpenclawConfig(activePath, exists, resetPath, resolvedList, agentsFromRegistry, workDir, managedMcp, hasManagedMcp, opts.Gateway)
+ cfg := buildPerTaskOpenclawConfig(activePath, exists, resetPath, resolvedList, agentsSource, workDir, managedMcp, hasManagedMcp, opts.Gateway)
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
@@ -479,16 +484,17 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
"active_config_exists", exists,
"include_target", includeTarget,
"include_root", result.IncludeRoot,
- "agents_from_registry", agentsFromRegistry,
+ "agents_source", string(agentsSource),
"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).
+// discoverOpenclawConfig resolves the user's active config path, the resolved
+// per-agent rows and the schema they came from, serving all three 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
@@ -498,12 +504,12 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
// 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) {
+func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConfigPrep) (activePath string, exists bool, resolvedList []any, agentsSource openclawAgentsSource, 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
+ return entry.ActiveConfigPath, true, list, openclawAgentsSource(entry.AgentsSource), true, nil
}
if opts.Logger != nil {
opts.Logger.Warn("execenv: openclaw discovery cache entry unusable; rediscovering",
@@ -513,27 +519,45 @@ func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConf
activePath, exists, err = openclawActiveConfigPath(bin, timeout)
if err != nil {
- return "", false, nil, false, false, fmt.Errorf("locate openclaw active config: %w", err)
+ return "", false, nil, "", 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
+ return activePath, false, nil, "", false, nil
}
- resolvedList, agentsFromRegistry, err = openclawResolvedAgentsList(bin, timeout)
+ resolvedList, agentsSource, err = openclawResolvedAgentsList(bin, timeout)
if err != nil {
- return "", false, nil, false, false, fmt.Errorf("read openclaw agents.list: %w", err)
+ return "", false, nil, "", false, fmt.Errorf("read openclaw agents.list: %w", err)
}
- if storeErr := storeOpenclawDiscoveryCache(cachePath, bin, activePath, resolvedList, agentsFromRegistry, time.Now()); storeErr != nil && opts.Logger != nil {
+ if storeErr := storeOpenclawDiscoveryCache(cachePath, bin, activePath, resolvedList, agentsSource, 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
+ return activePath, exists, resolvedList, agentsSource, false, nil
}
+// openclawAgentsSource names the OpenClaw surface the resolved per-agent rows
+// were read from. It is what decides how — and whether — they may be written
+// back into the per-task wrapper, so it is carried explicitly rather than
+// inferred from a boolean: `agents.list[]` and `agents.entries.<id>` are config
+// schemas this daemon can pin a per-agent `workspace` in, while registry rows
+// (`agents list --json`) are read-only and must never be emitted as config.
+type openclawAgentsSource string
+
+const (
+ // openclawAgentsSourceList — pre-2026.6 config: `agents.list[]`.
+ openclawAgentsSourceList openclawAgentsSource = "list"
+ // openclawAgentsSourceEntries — 2026.8+ config: `agents.entries.<id>`.
+ openclawAgentsSourceEntries openclawAgentsSource = "entries"
+ // openclawAgentsSourceRegistry — the sqlite-backed registry, via
+ // `openclaw agents list --json`. Read-only.
+ openclawAgentsSourceRegistry openclawAgentsSource = "registry"
+)
+
// buildPerTaskOpenclawConfig assembles the wrapper map that goes on disk.
//
// Exists=true: emit a $include link to the user's active config plus the
@@ -543,7 +567,18 @@ func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConf
// field of every resolved entry (id, model, prompts, tools, …) verbatim
// with only `workspace` rewritten — this is robust regardless of whether
// the runtime merges the sibling array or replaces it, because either way
-// the resulting list is shape-equivalent to the user's minus workspace.
+// the resulting list is shape-equivalent to the user's minus workspace. That
+// list is a lossless round-trip of the user's own file, so copying it changes
+// nothing but the one field we mean to change.
+//
+// The 2026.8+ `agents.entries.<id>` map is *not* a lossless round-trip and must
+// not be treated as one: `config get` redacts the config on its way out (a
+// sensitive value comes back as the literal `__OPENCLAW_REDACTED__`), and the
+// wrapper's sibling keys win the $include merge, so copying the resolved entry
+// would write that sentinel over the user's real secret for every task. The
+// write-back there is `workspace` alone — objects merge recursively under
+// $include, so one key per id is enough to pin the workspace and nothing else
+// is observed, copied, or dropped. See rewriteAgentsEntriesWorkspaces.
//
// Exists=false: a fresh install with no on-disk config. Emit a minimal
// config containing only the workspace override. There is no user data to
@@ -565,22 +600,36 @@ func discoverOpenclawConfig(bin string, timeout time.Duration, opts OpenclawConf
// stage has already nulled the user's server map, the resulting view of
// `mcp.servers` is exactly the managed set — including `{}` for "admin saved
// no servers" (mirrors `hasManagedCodexMcpConfig`).
-func buildPerTaskOpenclawConfig(activePath string, exists bool, resetPath string, resolvedList []any, agentsFromRegistry bool, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
+func buildPerTaskOpenclawConfig(activePath string, exists bool, resetPath string, resolvedList []any, agentsSource openclawAgentsSource, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
agents := map[string]any{
"defaults": map[string]any{"workspace": workDir},
}
- // Only write per-agent overrides back to the wrapper when they came from
- // the config-schema `agents.list` path (pre-2026.6). A registry-sourced
- // list (OpenClaw 2026.6.x+) is NOT valid `agents.list[]` config — the
- // schema validator rejects it ("agents.list.0: Invalid input") and fails
- // closed before the agent runs. 2026.6.x has no in-config path for per-
- // agent workspace pinning, so `agents.defaults.workspace` (set above) is
- // the only knob, and it is sufficient: OpenClaw applies it to the agent it
- // selects from the registry (see upstream #3028, write-side half).
- if !agentsFromRegistry {
+ // Per-agent overrides are written back only into the schema the rows were
+ // actually read from (see openclawAgentsSource). A registry-sourced list
+ // (OpenClaw 2026.6.x/2026.7.x, `agents list --json`) is *not* config — the
+ // schema validator rejects its CLI-only fields ("agents.list.0: Invalid
+ // input") and fails closed before the agent runs — so those hosts get
+ // `agents.defaults.workspace` (set above) as their only per-task knob, which
+ // is sufficient there: OpenClaw applies it to the agent it selects from the
+ // registry (see upstream #3028, write-side half).
+ //
+ // 2026.8+ moved the agents out of `agents.list` into `agents.entries.<id>`,
+ // and that schema *is* writable: a host that pins an absolute per-agent
+ // `workspace` there outranks `agents.defaults.workspace` verbatim, so
+ // without this write-back every task on such a host runs in the gateway's
+ // own workspace instead of its prepared workdir (skills/ never loads).
+ switch agentsSource {
+ case openclawAgentsSourceList:
if rewritten := rewriteAgentsListWorkspaces(resolvedList, workDir); rewritten != nil {
agents["list"] = rewritten
}
+ case openclawAgentsSourceEntries:
+ if rewritten := rewriteAgentsEntriesWorkspaces(resolvedList, workDir); rewritten != nil {
+ agents["entries"] = rewritten
+ }
+ case openclawAgentsSourceRegistry, "":
+ // Read-only source (or nothing discovered): `agents.defaults.workspace`
+ // above is the whole per-task override.
}
cfg := map[string]any{
"agents": agents,
@@ -683,6 +732,60 @@ func rewriteAgentsListWorkspaces(list []any, workDir string) []any {
return out
}
+// The resolved `agents.entries` map is carried through this package as a
+// `[]any` because that is the shape the discovery cache stores and re-reads for
+// every schema (see openclaw_config_cache.go) and because a list is what the
+// rest of the resolver contract speaks. The map key — the agent id — has no
+// field of its own inside the entry object, so it rides along out of band on
+// each row and is stripped again on the way into the wrapper: writing this key
+// into the user's config would be a schema change we have no business making.
+//
+// Nothing else about an entry is carried: `config get` hands back redacted
+// values (see rewriteAgentsEntriesWorkspaces), so keeping the payload around
+// would only create copies — in the row, in the cache file — of data that must
+// never be written back anyway.
+const openclawEntriesKeyField = "__multica_entries_key"
+
+// rewriteAgentsEntriesWorkspaces rebuilds the `agents.entries.<id>` map from a
+// resolved entries list, pinning every entry's `workspace` to workDir.
+//
+// **Each entry carries `workspace` and nothing else.** The resolved entries
+// cannot be copied through: `config get` redacts the config before extracting
+// the path it was asked for, so any sensitive per-agent field (memory search
+// API key, web fetch headers, sandbox SSH credentials, …) comes back as the
+// literal `__OPENCLAW_REDACTED__` sentinel. `$include` resolves as
+// deepMerge(included, siblings) with the wrapper's siblings winning, so copying
+// the entry would write that sentinel over the user's real secret for every
+// task, and nothing on OpenClaw's load path restores it. Emitting one key per id
+// is both sufficient — objects merge recursively, so every other field still
+// arrives from the user's own config verbatim — and safe.
+//
+// Returns nil unless *every* element carries the entries-probe key, so a list
+// from any other source never reaches the wrapper as `agents.entries`: rows
+// from the registry carry CLI-only fields OpenClaw's validator rejects
+// ("agents.entries.main: Invalid input"), and on the generations that have a
+// registry fallback the `agents.entries` path does not exist at all. An empty
+// map is nil too, so the caller omits the key entirely rather than replacing
+// whatever the $include carries with `entries: {}`.
+func rewriteAgentsEntriesWorkspaces(list []any, workDir string) map[string]any {
+ entries := make(map[string]any, len(list))
+ for _, item := range list {
+ entry, ok := item.(map[string]any)
+ if !ok {
+ return nil
+ }
+ id, ok := entry[openclawEntriesKeyField].(string)
+ if !ok || id == "" {
+ return nil
+ }
+ entries[id] = map[string]any{"workspace": workDir}
+ }
+ if len(entries) == 0 {
+ return nil
+ }
+ return entries
+}
+
// openclawActiveConfigPath discovers the path the openclaw CLI considers active.
// Returns (absolutePath, exists, error).
//
@@ -1109,56 +1212,146 @@ func isOpenclawConfigFileUnsupported(err error) bool {
(strings.Contains(msg, "unknown") && strings.Contains(msg, "config") && strings.Contains(msg, "file"))
}
-// openclawResolvedAgentsList fetches the user's resolved per-agent list and
-// reports which schema produced it. The schema matters downstream: a config-
-// sourced list is itself valid `agents.list[]` config and may be written back
-// into the wrapper to pin per-agent workspaces, whereas a registry-sourced
-// list MUST NOT be written back — see openclawRegistryAgentsList.
+// openclawResolvedAgentsList fetches the user's resolved per-agent rows and
+// reports which surface produced them (see openclawAgentsSource). The source
+// matters downstream: rows that came from a config schema may be written back
+// into the wrapper to pin per-agent workspaces, whereas registry rows MUST NOT
+// be written back at all — see openclawRegistryAgentsList.
//
-// Two schemas are supported:
+// Three schemas are supported:
//
// - Pre-2026.6: agents live in the config under `agents.list`. We read them
// via `openclaw config get agents.list --json`, which returns the post-
-// include, post-env-substitution array. fromRegistry=false.
-// - 2026.6.x and later: `agents.list` is no longer a config path — agents
-// live in a sqlite registry. `config get agents.list` exits non-zero with
-// "Config path not found: agents.list". We fall back to the
-// `openclaw agents list --json` *subcommand*. fromRegistry=true.
-//
-// Returns (nil, false, nil) when neither source yields any agents.
-func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, bool, error) {
+// include, post-env-substitution array. openclawAgentsSourceList.
+// - 2026.8+: the same CLI reports `Unknown config path: agents.list` and
+// carries the agents under `agents.entries.<id>` instead. That path *is*
+// writable, so it is read through the same deadline as the attempt above
+// and returned with only the id carried out of band; see
+// openclawResolvedAgentsEntriesOrRegistry. openclawAgentsSourceEntries —
+// a keyed entries payload is not `agents.list[]` config.
+// - 2026.6.x/2026.7.x: neither config path exists — agents live in a sqlite
+// registry. `config get agents.list` exits non-zero with "Config path not
+// found: agents.list". We fall back to the `openclaw agents list --json`
+// *subcommand*, whose rows must never be written back.
+// openclawAgentsSourceRegistry.
+//
+// Returns a nil list when a source answered with no agents; the source still
+// names what answered.
+func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, openclawAgentsSource, error) {
+ // One deadline for both config-schema probes. They ask the same question —
+ // what does the config schema carry per agent? — and the second is only
+ // reached when the first answers "no such path", exactly like
+ // `config validate --json` and its `config file` fallback in
+ // openclawActiveConfigPath. Giving the entries probe its own budget would
+ // take the worst case from three CLI deadlines to four (see
+ // openclawMaxCLIDeadlinesPerPreparation) without widening what the CLI can
+ // answer in total.
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
+ return openclawResolvedAgentsListWithinDeadline(ctx, bin, timeout)
+}
+
+// openclawResolvedAgentsListWithinDeadline is the shared-deadline half of
+// openclawResolvedAgentsList: every config-schema probe it makes runs under the
+// ctx it is handed, and only the registry fallback starts a budget of its own.
+func openclawResolvedAgentsListWithinDeadline(ctx context.Context, bin string, timeout time.Duration) ([]any, openclawAgentsSource, error) {
out, err := openclawExec(ctx, bin, "config", "get", "agents.list", "--json")
if err != nil {
if isOpenclawKeyMissingResult(out, err, "agents.list") {
- // New schema: the config path is gone; the agents live in the
- // sqlite registry. Resolve them via the subcommand instead.
+ // The config path is gone. On 2026.8+ the keyed replacement exists;
+ // below that the agents live in the sqlite registry.
+ if openclawUnknownConfigPath(out, err, "agents.list") {
+ return openclawResolvedAgentsEntriesOrRegistry(ctx, bin, timeout)
+ }
list, rerr := openclawRegistryAgentsList(bin, timeout)
- return list, true, rerr
+ return list, openclawAgentsSourceRegistry, rerr
}
- return nil, false, annotateOpenclawJSONError(err, out)
+ return nil, "", annotateOpenclawJSONError(err, out)
}
trimmed := strings.TrimSpace(out)
if trimmed == "" || trimmed == "null" {
- return nil, false, nil
+ return nil, openclawAgentsSourceList, nil
}
// An envelope that arrived without a non-zero exit must reach the same
// verdict as one that did; see openclawStdoutEnvelopeError. Missing the
// key here is what selects the registry, so letting the envelope through
// as data would turn a graceful fallback into a failed preparation.
if message, isEnvelope := openclawJSONErrorMessage(trimmed); isEnvelope {
- if strings.Contains(strings.ToLower(message), "agents.list") && isOpenclawKeyMissingMessage(message) {
+ // Matched on the path, not on the mere mention of "agents.list": the
+ // path-aware matcher knows every wording the CLI has used for "this key
+ // is not there" ("Path not found", "Config path not found",
+ // "Config path is valid but unset", "Unknown config path"), and it is
+ // what keeps an envelope about some *other* key fail-closed instead of
+ // silently downgrading this host to the registry.
+ if openclawKeyMissingMessageForPath(message, "agents.list") {
+ if openclawUnknownConfigPathMessage(message, "agents.list") {
+ return openclawResolvedAgentsEntriesOrRegistry(ctx, bin, timeout)
+ }
list, rerr := openclawRegistryAgentsList(bin, timeout)
- return list, true, rerr
+ return list, openclawAgentsSourceRegistry, rerr
}
- return nil, false, openclawStdoutEnvelopeError("config get agents.list --json", message)
+ return nil, "", openclawStdoutEnvelopeError("config get agents.list --json", message)
}
var list []any
if err := json.Unmarshal([]byte(trimmed), &list); err != nil {
- return nil, false, fmt.Errorf("parse `openclaw config get agents.list --json` output: %w", err)
+ return nil, "", fmt.Errorf("parse `openclaw config get agents.list --json` output: %w", err)
}
- return list, false, nil
+ return list, openclawAgentsSourceList, nil
+}
+
+// openclawResolvedAgentsEntriesOrRegistry runs the config-schema read that
+// 2026.8+ replaced `agents.list` with, then falls back to the registry for the
+// generations that have neither.
+//
+// `agents.entries` is a map keyed by agent id, and that key is the only place
+// the id exists — the entry object itself may carry no `id` field at all (a
+// minimal `{"workspace": "..."}` is a valid entry). Each resolved row therefore
+// carries the key out of band, and nothing else: the payload is redacted and is
+// never written back (see rewriteAgentsEntriesWorkspaces). That marker is also
+// how the write-back tells these rows apart from registry rows, which must
+// never reach the wrapper.
+//
+// Reports openclawAgentsSourceEntries when this path answered, and
+// openclawAgentsSourceRegistry when it fell back to the sqlite registry — the
+// generations where that fallback fires are exactly the ones where
+// `agents.entries` is not a valid config path, so the caller must not write the
+// rows back under that key.
+func openclawResolvedAgentsEntriesOrRegistry(ctx context.Context, bin string, timeout time.Duration) ([]any, openclawAgentsSource, error) {
+ out, err := openclawExec(ctx, bin, "config", "get", "agents.entries", "--json")
+ if err != nil {
+ if isOpenclawKeyMissingResult(out, err, "agents.entries") {
+ list, rerr := openclawRegistryAgentsList(bin, timeout)
+ return list, openclawAgentsSourceRegistry, rerr
+ }
+ return nil, "", annotateOpenclawJSONError(err, out)
+ }
+ trimmed := strings.TrimSpace(out)
+ if trimmed == "" || trimmed == "null" {
+ return nil, openclawAgentsSourceEntries, nil
+ }
+ // Same envelope rule as the `agents.list` probe above: on the generations
+ // where this path is valid but the user has not written it, the CLI reports
+ // "Config path is valid but unset: agents.entries" — which means the host has
+ // no in-config agents, and the registry is still the only place they can be.
+ if message, isEnvelope := openclawJSONErrorMessage(trimmed); isEnvelope {
+ if openclawKeyMissingMessageForPath(message, "agents.entries") {
+ list, rerr := openclawRegistryAgentsList(bin, timeout)
+ return list, openclawAgentsSourceRegistry, rerr
+ }
+ return nil, "", openclawStdoutEnvelopeError("config get agents.entries --json", message)
+ }
+ var entries map[string]any
+ if err := json.Unmarshal([]byte(trimmed), &entries); err != nil {
+ return nil, "", fmt.Errorf("parse `openclaw config get agents.entries --json` output: %w", err)
+ }
+ list := make([]any, 0, len(entries))
+ for id, raw := range entries {
+ if _, ok := raw.(map[string]any); !ok {
+ return nil, "", fmt.Errorf("parse `openclaw config get agents.entries --json` output: entry %q is not an object", id)
+ }
+ list = append(list, map[string]any{openclawEntriesKeyField: id})
+ }
+ return list, openclawAgentsSourceEntries, nil
}
// openclawRegistryAgentsList resolves agents from the sqlite-backed registry
@@ -1169,13 +1362,19 @@ func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, bool,
// (identityName, identitySource, agentDir, bindings, isDefault) that are NOT
// part of the 2026.6.x config schema's `agents.list[]` shape; OpenClaw's
// validator rejects them ("agents.list.0: Invalid input") and fails closed
-// before the agent runs. Worse, `agents.list` is no longer a valid config
-// path at all in 2026.6.x — there is no in-config way to pin a per-agent
-// workspace. The per-task workspace is instead pinned via
+// before the agent runs. Worse, `agents.list` is no longer a valid config path
+// at all in 2026.6.x. On these generations there is no in-config way to pin a
+// per-agent workspace, so the per-task workspace is pinned via
// `agents.defaults.workspace` alone, which the wrapper always sets and which
// OpenClaw applies to the agent it selects from the registry (verified on
-// 2026.6.8). Callers gate the write-back on fromRegistry from
-// openclawResolvedAgentsList.
+// 2026.6.8). 2026.8+ hosts do have a writable per-agent path again —
+// `agents.entries.<id>` — and reach it through openclawResolvedAgentsEntriesOrRegistry
+// without ever consulting this function.
+//
+// Callers gate the write-back on the source
+// openclawResolvedAgentsList reports (openclawAgentsSourceRegistry here, which
+// no write-back branch accepts); rows from this subcommand are therefore never
+// written to the wrapper by any route.
//
// Returns nil (not an error) when the registry is empty or the subcommand
// reports no agents.
@@ -1526,6 +1725,27 @@ func isOpenclawKeyMissingResult(stdout string, err error, keyPath string) bool {
return openclawKeyMissingMessageForPath(message, keyPath)
}
+// openclawUnknownConfigPath recognizes the one missing-path wording that also
+// tells us *which* generation of the schema we are talking to: 2026.8+ reports
+// `Unknown config path: agents.list` for the path it retired and carries the
+// agents under `agents.entries` instead. The older generations say "Config path
+// not found" / "Config path is valid but unset" for paths they know nothing
+// about and have no keyed replacement, so those keep the registry fallback —
+// probing `agents.entries` there would only spend a probe to be told about a
+// path that generation never had.
+func openclawUnknownConfigPath(stdout string, err error, keyPath string) bool {
+ if message, ok := openclawJSONErrorMessage(stdout); ok {
+ return openclawUnknownConfigPathMessage(message, keyPath)
+ }
+ return err != nil && openclawUnknownConfigPathMessage(err.Error(), keyPath)
+}
+
+func openclawUnknownConfigPathMessage(message, keyPath string) bool {
+ message = strings.ToLower(strings.Join(strings.Fields(message), " "))
+ keyPath = strings.ToLower(strings.TrimSpace(keyPath))
+ return keyPath != "" && openclawMessageNamesPathAfter(message, "unknown config path: ", keyPath)
+}
+
func openclawKeyMissingMessageForPath(message, keyPath string) bool {
message = strings.ToLower(strings.Join(strings.Fields(message), " "))
keyPath = strings.ToLower(strings.TrimSpace(keyPath))
diff --git a/server/internal/daemon/execenv/openclaw_config_cache.go b/server/internal/daemon/execenv/openclaw_config_cache.go
index a74f3e8caa..8152df6487 100644
--- a/server/internal/daemon/execenv/openclaw_config_cache.go
+++ b/server/internal/daemon/execenv/openclaw_config_cache.go
@@ -41,7 +41,10 @@ const (
// openclawDiscoveryCacheVersion guards the on-disk shape. A daemon that
// reads an entry written by a different version treats it as a miss.
- openclawDiscoveryCacheVersion = 1
+ // 2 — the stored rows changed shape: the source is recorded explicitly
+ // (`agents_source`) and an `agents.entries` row is the id marker alone, not a
+ // copy of the redacted entry (see openclawResolvedAgentsEntriesOrRegistry).
+ openclawDiscoveryCacheVersion = 2
// openclawDiscoveryCacheTTL bounds how long a hit can be served. The
// fingerprint catches the changes we can observe cheaply (binary swap,
@@ -94,10 +97,14 @@ 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"`
+ // AgentsList is the resolved per-agent rows, stored so a hit reproduces
+ // exactly what the source returned.
+ AgentsList json.RawMessage `json:"agents_list"`
+ // AgentsSource is the openclawAgentsSource those rows came from, which
+ // decides whether and how they may be written back into the wrapper. It is
+ // part of the cached evidence for the same reason the rows are: a hit has to
+ // rebuild the same wrapper the live run would have built.
+ AgentsSource string `json:"agents_source"`
}
// openclawDiscoveryEnvVars are the environment variables that change which
@@ -258,7 +265,7 @@ func loadOpenclawDiscoveryCache(cachePath, bin string, now time.Time) (openclawD
// 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 {
+func storeOpenclawDiscoveryCache(cachePath, bin, activeConfigPath string, agentsList []any, agentsSource openclawAgentsSource, now time.Time) error {
if cachePath == "" {
return nil
}
@@ -274,11 +281,11 @@ func storeOpenclawDiscoveryCache(cachePath, bin, activeConfigPath string, agents
return fmt.Errorf("marshal openclaw agents list: %w", err)
}
entry := openclawDiscoveryCacheEntry{
- Fingerprint: fingerprint,
- CachedAtNano: now.UnixNano(),
- ActiveConfigPath: activeConfigPath,
- AgentsList: listBytes,
- AgentsFromRegistry: agentsFromRegistry,
+ Fingerprint: fingerprint,
+ CachedAtNano: now.UnixNano(),
+ ActiveConfigPath: activeConfigPath,
+ AgentsList: listBytes,
+ AgentsSource: string(agentsSource),
}
data, err := json.Marshal(entry)
if err != nil {
diff --git a/server/internal/daemon/execenv/openclaw_config_cache_test.go b/server/internal/daemon/execenv/openclaw_config_cache_test.go
index 80c9ef1b1e..62f506c2f6 100644
--- a/server/internal/daemon/execenv/openclaw_config_cache_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_cache_test.go
@@ -309,7 +309,7 @@ func TestOpenclawDiscoveryCacheFutureDatedEntry(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
f := newOpenclawCacheFixture(t)
readerNow := time.Now()
- if err := storeOpenclawDiscoveryCache(f.cachePath(), f.bin, f.configPath, []any{map[string]any{"id": "scout"}}, false, readerNow.Add(tc.ahead)); err != nil {
+ if err := storeOpenclawDiscoveryCache(f.cachePath(), f.bin, f.configPath, []any{map[string]any{"id": "scout"}}, openclawAgentsSourceList, readerNow.Add(tc.ahead)); err != nil {
t.Fatalf("store: %v", err)
}
if _, ok := loadOpenclawDiscoveryCache(f.cachePath(), f.bin, readerNow); ok != tc.want {
@@ -345,7 +345,7 @@ func TestOpenclawDiscoveryCacheConcurrentPreparations(t *testing.T) {
// 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 {
+ if err := storeOpenclawDiscoveryCache(f.cachePath(), f.bin, f.configPath, []any{map[string]any{"id": "scout"}}, openclawAgentsSourceList, time.Now()); err != nil {
mu.Lock()
failures = append(failures, err)
mu.Unlock()
diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.go
index ce7906d130..515fad8eda 100644
--- a/server/internal/daemon/execenv/openclaw_config_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_test.go
@@ -9,6 +9,7 @@ import (
"log/slog"
"os"
"path/filepath"
+ "reflect"
"strings"
"testing"
"time"
@@ -1716,7 +1717,7 @@ func TestBuildPerTaskOpenclawConfigOmitsGatewayWhenZero(t *testing.T) {
t.Parallel()
cfg := buildPerTaskOpenclawConfig(
- "", false, "", nil, false, "/workdir", nil, false,
+ "", false, "", nil, "", "/workdir", nil, false,
OpenclawGatewayPin{},
)
if _, present := cfg["gateway"]; present {
@@ -1734,7 +1735,7 @@ func TestBuildPerTaskOpenclawConfigWritesGatewayBlock(t *testing.T) {
TLS: true,
}
cfg := buildPerTaskOpenclawConfig(
- "", false, "", nil, false, "/workdir", nil, false,
+ "", false, "", nil, "", "/workdir", nil, false,
pin,
)
@@ -1773,7 +1774,7 @@ func TestBuildPerTaskOpenclawConfigPartialGatewayOmitsZeroFields(t *testing.T) {
// fields must not land in the wrapper as empty strings/zeros — that
// would override the user's value with junk.
cfg := buildPerTaskOpenclawConfig(
- "", false, "", nil, false, "/workdir", nil, false,
+ "", false, "", nil, "", "/workdir", nil, false,
OpenclawGatewayPin{Host: "gw.internal", Port: 18789},
)
gw := cfg["gateway"].(map[string]any)
@@ -2117,6 +2118,408 @@ func TestPrepareOpenclawConfigNewSchemaEmptyRegistry(t *testing.T) {
}
}
+// ── 2026.8+ `agents.entries.<id>` schema ──
+//
+// OpenClaw 2026.8 retired `agents.list` in favour of a map keyed by agent id.
+// Unlike the sqlite-registry generations, that map is configuration the
+// per-task wrapper can override — and it has to: an entry that pins an
+// absolute `workspace` outranks `agents.defaults.workspace` verbatim, so a host
+// that pinned one for its gateway agent would run every task in that pinned
+// directory instead of the prepared workdir (skills/ never loads, and the agent
+// silently edits the wrong tree).
+//
+// The tests below are the regression coverage the reviewer of the earlier
+// attempt at this fix asked for: the new probe and its fallbacks, the write-back
+// in both the plain and the managed-MCP flow, and the fail-closed edge that must
+// not be traded away for either.
+
+// TestPrepareOpenclawConfigProbesAgentsEntriesOnCurrentWording — 2026.8.x
+// reports the retired path as `Unknown config path: agents.list`, and the
+// envelope can arrive with err == nil because the completeness rule accepts a
+// finished JSON answer from a CLI that has not exited yet (see
+// openclawStdoutEnvelopeError). That spelling has to select the entries probe: a
+// path-less "key not found" matcher cannot see it, and without the probe the
+// host silently loses its per-agent workspace pinning.
+func TestPrepareOpenclawConfigProbesAgentsEntriesOnCurrentWording(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{
+ "config file": {stdout: userConfigPath},
+ // Envelope without an exit error, in the shape 2026.8.1-beta.3 emits.
+ "config get agents.list --json": {
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Unknown config path: agents.list"}}`,
+ },
+ "config get agents.entries --json": {
+ stdout: `{"main":{"workspace":"/Users/cob/.openclaw/workspace"}}`,
+ },
+ // Answerable on purpose: a regression that consults the registry here
+ // must fail the call-graph assertion below rather than the stub's
+ // unexpected-args guard, so the diagnostic says which wire was crossed.
+ "agents list --json": {stdout: `[{"id":"main"}]`},
+ })
+
+ if _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: stub.bin}); err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+
+ var invocations []string
+ for _, call := range stub.calls {
+ invocations = append(invocations, strings.Join(call.args, " "))
+ }
+ want := []string{
+ "config validate --json",
+ "config get agents.list --json",
+ "config get agents.entries --json",
+ }
+ if strings.Join(invocations, " | ") != strings.Join(want, " | ") {
+ t.Errorf("call graph on a 2026.8 host:\n got: %v\nwant: %v", invocations, want)
+ }
+}
+
+// TestPrepareOpenclawConfigPinsAgentsEntriesWorkspaces — the whole point of the
+// probe: every `agents.entries.<id>.workspace` lands on the task workdir, and
+// nothing else about the entry does. The wrapper is a sibling of the user's
+// config in the $include merge, so anything echoed back from the resolved entry
+// would override the user's own value — including values `config get` has
+// already replaced with `__OPENCLAW_REDACTED__` (covered on its own by
+// TestPrepareOpenclawConfigEntriesWriteBackDropsRedactedFields).
+func TestPrepareOpenclawConfigPinsAgentsEntriesWorkspaces(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)
+ }
+
+ // The multi-agent shape from the field: the gateway's own agent pinned to
+ // its workspace, plus a second agent pinned somewhere else. Both would win
+ // over agents.defaults.workspace if the wrapper did not rewrite them.
+ entries := `{"main":{"workspace":"/Users/cob/.openclaw/workspace","name":"Chamber",` +
+ `"memory":{"search":{"remote":{"apiKey":"__OPENCLAW_REDACTED__"}}}},` +
+ `"oncall":{"workspace":"/Users/cob/.openclaw/workspace-oncall","model":"anthropic/claude-sonnet-4-6"}}`
+ stub := installOpenclawStub(t, map[string]openclawResponse{
+ "config file": {stdout: userConfigPath},
+ "config get agents.list --json": {
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Unknown config path: agents.list"}}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ },
+ "config get agents.entries --json": {stdout: entries},
+ "agents list --json": {stdout: `[{"id":"main"}]`},
+ })
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: stub.bin})
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ got := mustReadJSON(t, result.ConfigPath)
+ agents := got["agents"].(map[string]any)
+ if agents["defaults"].(map[string]any)["workspace"] != workDir {
+ t.Errorf("defaults.workspace = %v, want %q", agents["defaults"].(map[string]any)["workspace"], workDir)
+ }
+ if _, present := agents["list"]; present {
+ t.Errorf("agents.list must be omitted on a 2026.8 host, got %v", agents["list"])
+ }
+ gotEntries, ok := agents["entries"].(map[string]any)
+ if !ok {
+ t.Fatalf("agents.entries missing from the wrapper — the pinned host workspaces would keep overriding the task workspace: %v", agents)
+ }
+ if len(gotEntries) != 2 {
+ t.Errorf("agents.entries has %d entries, want 2: %v", len(gotEntries), gotEntries)
+ }
+ for _, id := range []string{"main", "oncall"} {
+ entry, ok := gotEntries[id].(map[string]any)
+ if !ok {
+ t.Fatalf("agents.entries.%s is not an object: %v", id, gotEntries[id])
+ }
+ if entry["workspace"] != workDir {
+ t.Errorf("agents.entries.%s.workspace = %v, want %q", id, entry["workspace"], workDir)
+ }
+ if len(entry) != 1 {
+ t.Errorf("agents.entries.%s = %v; the wrapper must pin `workspace` alone, because $include gives these siblings precedence over the user's own config", id, entry)
+ }
+ }
+
+ wrapper, err := os.ReadFile(result.ConfigPath)
+ if err != nil {
+ t.Fatalf("read wrapper: %v", err)
+ }
+ for _, banned := range []string{"__multica_entries_", "__OPENCLAW_REDACTED__", `"name"`, `"model"`, `"memory"`} {
+ if strings.Contains(string(wrapper), banned) {
+ t.Errorf("the wrapper carries %s, which belongs to the user's config rather than to this package: %s", banned, wrapper)
+ }
+ }
+ for _, call := range stub.calls {
+ if strings.Join(call.args, " ") == "agents list --json" {
+ t.Errorf("registry consulted on a host whose agents came from agents.entries: %v", call.args)
+ }
+ }
+}
+
+// TestPrepareOpenclawConfigPinsAgentsEntriesWorkspacesWithManagedMcp — a
+// managed mcp_config does not change which CLI calls preparation makes, and it
+// must not change the entries write-back either: the wrapper still pins the
+// task workspace and still carries the managed `mcp.servers` beside it.
+func TestPrepareOpenclawConfigPinsAgentsEntriesWorkspacesWithManagedMcp(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{
+ "config file": {stdout: userConfigPath},
+ "config get agents.list --json": {
+ stdout: `{"error":"Unknown config path: agents.list"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ },
+ "config get agents.entries --json": {
+ stdout: `{"main":{"workspace":"/Users/cob/.openclaw/workspace"}}`,
+ },
+ })
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
+ OpenclawBin: stub.bin,
+ McpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"managed"}}}`),
+ })
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ got := mustReadJSON(t, result.ConfigPath)
+ agents := got["agents"].(map[string]any)
+ entry, ok := agents["entries"].(map[string]any)["main"].(map[string]any)
+ if !ok {
+ t.Fatalf("agents.entries.main missing under managed MCP: %v", agents)
+ }
+ if entry["workspace"] != workDir {
+ t.Errorf("agents.entries.main.workspace = %v, want %q", entry["workspace"], workDir)
+ }
+ if len(entry) != 1 {
+ t.Errorf("agents.entries.main = %v, want `workspace` alone", entry)
+ }
+ mcp, ok := got["mcp"].(map[string]any)
+ if !ok {
+ t.Fatalf("wrapper has no mcp block under managed MCP: %v", got)
+ }
+ servers, ok := mcp["servers"].(map[string]any)
+ if !ok || len(servers) != 1 {
+ t.Errorf("mcp.servers = %v, want exactly the managed set", mcp["servers"])
+ }
+}
+
+// TestPrepareOpenclawConfigEntriesWriteBackDropsRedactedFields — the write-back
+// must not copy the resolved entry. `config get` runs the config through
+// redaction before it extracts the path it was asked for, so a sensitive
+// per-agent value comes back as the literal `__OPENCLAW_REDACTED__`. The
+// wrapper is a sibling of the user's config in the $include merge and siblings
+// win, so echoing that sentinel back would replace the user's real secret — a
+// memory search API key, a web fetch header, sandbox SSH credentials — for
+// every task on the host, and nothing on OpenClaw's load path restores it.
+// Emitting `{"<id>": {"workspace": ...}}` leaves every other field coming from
+// the user's own file, untouched.
+func TestPrepareOpenclawConfigEntriesWriteBackDropsRedactedFields(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)
+ }
+
+ // The shapes upstream's own redaction regression covers, nested inside the
+ // one entry that carries the pinned workspace.
+ entries := `{"main":{"workspace":"/Users/cob/.openclaw/workspace",` +
+ `"memory":{"search":{"remote":{"apiKey":"__OPENCLAW_REDACTED__"}}},` +
+ `"tools":{"web":{"fetch":{"headers":{"Authorization":"__OPENCLAW_REDACTED__"}}}},` +
+ `"sandbox":{"ssh":{"password":"__OPENCLAW_REDACTED__"}}}}`
+ stub := installOpenclawStub(t, map[string]openclawResponse{
+ "config file": {stdout: userConfigPath},
+ "config get agents.list --json": {
+ stdout: `{"ok":false,"error":{"type":"cli_error","message":"Unknown config path: agents.list"}}`,
+ },
+ "config get agents.entries --json": {stdout: entries},
+ })
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: stub.bin})
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ wrapper, err := os.ReadFile(result.ConfigPath)
+ if err != nil {
+ t.Fatalf("read wrapper: %v", err)
+ }
+ if strings.Contains(string(wrapper), "__OPENCLAW_REDACTED__") {
+ t.Errorf("the wrapper carries a redaction sentinel, which would override the user's real secret through the $include merge: %s", wrapper)
+ }
+
+ got := mustReadJSON(t, result.ConfigPath)
+ entry, ok := got["agents"].(map[string]any)["entries"].(map[string]any)["main"].(map[string]any)
+ if !ok {
+ t.Fatalf("agents.entries.main missing — the task workspace would not be pinned: %v", got)
+ }
+ if entry["workspace"] != workDir {
+ t.Errorf("agents.entries.main.workspace = %v, want %q", entry["workspace"], workDir)
+ }
+ if len(entry) != 1 {
+ t.Errorf("agents.entries.main = %v, want `workspace` alone", entry)
+ }
+}
+
+// TestPrepareOpenclawConfigFallsBackToRegistryWhenEntriesPathIsUnset — on
+// 2026.8 the entries path exists but may carry nothing, which the CLI reports as
+// "Config path is valid but unset: agents.entries" (again with err == nil when
+// the envelope arrives without an exit). That is a host whose agents live in the
+// registry, so the fallback has to run — and its rows still must not reach the
+// wrapper.
+func TestPrepareOpenclawConfigFallsBackToRegistryWhenEntriesPathIsUnset(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{
+ "config file": {stdout: userConfigPath},
+ "config get agents.list --json": {
+ stdout: `{"error":"Unknown config path: agents.list"}`,
+ },
+ "config get agents.entries --json": {
+ stdout: `{"error":"Config path is valid but unset: agents.entries"}`,
+ },
+ "agents list --json": {stdout: `[{"id":"main","identityName":"Beau","agentDir":"/Users/cob/.openclaw/agents/main/agent","workspace":"/Users/cob/.openclaw/workspace","isDefault":true}]`},
+ })
+
+ result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: stub.bin})
+ if err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ got := mustReadJSON(t, result.ConfigPath)
+ agents := got["agents"].(map[string]any)
+ if agents["defaults"].(map[string]any)["workspace"] != workDir {
+ t.Errorf("defaults.workspace not pinned to workDir: %v", agents["defaults"])
+ }
+ if _, present := agents["entries"]; present {
+ t.Errorf("agents.entries must be omitted for a registry-sourced host, got %v", agents["entries"])
+ }
+ if _, present := agents["list"]; present {
+ t.Errorf("agents.list must be omitted for a registry-sourced host, got %v", agents["list"])
+ }
+ wrapper, err := os.ReadFile(result.ConfigPath)
+ if err != nil {
+ t.Fatalf("read wrapper: %v", err)
+ }
+ if strings.Contains(string(wrapper), "Config path is valid but unset") {
+ t.Errorf("wrapper carries the CLI error envelope: %s", wrapper)
+ }
+}
+
+// TestPrepareOpenclawConfigFailsClosedOnUnrelatedConfigPathEnvelope — the
+// missing-path verdict is matched on the path the probe asked for, not on the
+// presence of the words. An envelope about a different key is not permission to
+// downgrade this host to `agents.defaults.workspace` and call the task prepared:
+// it is a CLI whose answer we did not understand, and preparation fails closed.
+func TestPrepareOpenclawConfigFailsClosedOnUnrelatedConfigPathEnvelope(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{
+ "config file": {stdout: userConfigPath},
+ // A different key, so the probe's question is still unanswered.
+ "config get agents.list --json": {
+ stdout: `{"error":"Unknown config path: agents.defaults"}`,
+ },
+ "config get agents.entries --json": {
+ stdout: `{"main":{"workspace":"/Users/cob/.openclaw/workspace"}}`,
+ },
+ "agents list --json": {stdout: `[{"id":"main"}]`},
+ })
+
+ _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{OpenclawBin: stub.bin})
+ if err == nil {
+ t.Fatal("prepareOpenclawConfig accepted an envelope about an unrelated config path")
+ }
+ if !strings.Contains(err.Error(), "Unknown config path: agents.defaults") {
+ t.Errorf("error %q does not carry the CLI's own diagnostic", err.Error())
+ }
+ for _, call := range stub.calls {
+ switch strings.Join(call.args, " ") {
+ case "config get agents.entries --json", "agents list --json":
+ t.Errorf("`openclaw %s` must not run for an envelope naming another path", strings.Join(call.args, " "))
+ }
+ }
+ if _, statErr := os.Stat(filepath.Join(envRoot, openclawConfigFile)); !os.IsNotExist(statErr) {
+ t.Errorf("a failed preparation wrote a wrapper (stat err: %v)", statErr)
+ }
+}
+
+// TestRewriteAgentsEntriesWorkspacesRefusesRegistryRows pins the write-back
+// gate at the unit level: registry rows carry the CLI-only fields OpenClaw's
+// validator rejects, so any element that did not come from the entries probe
+// must sink the whole map rather than be filtered out quietly. What an entries
+// row carries is the id alone — the payload is redacted and must not be copied.
+func TestRewriteAgentsEntriesWorkspacesRefusesRegistryRows(t *testing.T) {
+ t.Parallel()
+ registryRows := []any{
+ map[string]any{"id": "main", "workspace": "/Users/cob/.openclaw/workspace", "identityName": "Beau"},
+ }
+ if got := rewriteAgentsEntriesWorkspaces(registryRows, "/workdir"); got != nil {
+ t.Errorf("registry rows were written back as agents.entries: %v", got)
+ }
+ if got := rewriteAgentsEntriesWorkspaces(nil, "/workdir"); got != nil {
+ t.Errorf("an empty resolved list must omit the key, got %v", got)
+ }
+ // Half-marked: a regression that filters quietly instead of refusing would
+ // still pin the marked id, and the unmarked row's source would go unexamined.
+ mixed := []any{
+ map[string]any{openclawEntriesKeyField: "main"},
+ map[string]any{"id": "oncall", "workspace": "/Users/cob/.openclaw/workspace-oncall"},
+ }
+ if got := rewriteAgentsEntriesWorkspaces(mixed, "/workdir"); got != nil {
+ t.Errorf("a list with an unmarked row was written back: %v", got)
+ }
+ entries := []any{
+ map[string]any{
+ openclawEntriesKeyField: "main",
+ // Anything else riding on the row is ignored on purpose — the
+ // payload `config get` returns carries redaction sentinels.
+ "workspace": "/Users/cob/.openclaw/workspace",
+ "name": "Chamber",
+ },
+ }
+ got := rewriteAgentsEntriesWorkspaces(entries, "/workdir")
+ want := map[string]any{"main": map[string]any{"workspace": "/workdir"}}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("rewritten entries = %#v, want %#v", got, want)
+ }
+}
+
// TestExpandOpenclawPathTildeSeparators — `openclaw config file` shortens the
// home prefix using its host OS's separator, so Windows reports
// `~\.openclaw\openclaw.json`. Matching only `~/` left that form unexpanded;
diff --git a/server/internal/daemon/execenv/openclaw_config_timeout_test.go b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
index ced3c66853..66cd32d829 100644
--- a/server/internal/daemon/execenv/openclaw_config_timeout_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
@@ -212,6 +212,14 @@ func TestOpenclawActiveConfigPathSpendsOneBudgetAcrossBothAttempts(t *testing.T)
// reads anything (see TestPrepareOpenclawConfigManagedMcpCostsNoExtraCLICall), so
// this drives the managed path too and still expects four invocations across
// three deadlines: path resolution's two share one.
+//
+// The config-schema read is itself a two-invocation chain now — 2026.8 hosts are
+// asked for `agents.entries` when `agents.list` is gone — and those two share a
+// budget for the same reason path resolution's pair does: they ask one question,
+// and the second is only reached when the first says the path is not there. The
+// worst case is therefore five invocations across three deadlines, and the
+// registry fallback — a different question, answered from sqlite — still starts a
+// deadline of its own.
func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
@@ -228,8 +236,11 @@ func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
"config validate --json": {err: errors.New("error: unknown command 'validate'")},
// 1b. fallback path resolution, under the same deadline as 1a
"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")},
+ // 2a. the schema generation whose per-agent list this host retired
+ "config get agents.list --json": {err: errors.New("Unknown config path: agents.list")},
+ // 2b. its keyed replacement, under the same deadline as 2a, on a host
+ // whose agents live in the registry
+ "config get agents.entries --json": {stdout: `{"error":"Config path is valid but unset: agents.entries"}`},
// 3. registry fallback
"agents list --json": {stdout: `[{"id":"scout"}]`},
// No fourth entry, and the managed mcp_config below is why that is worth
@@ -263,6 +274,7 @@ func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
"config validate --json",
"config file",
"config get agents.list --json",
+ "config get agents.entries --json",
"agents list --json",
}
if strings.Join(invocations, " | ") != strings.Join(wantInvocations, " | ") {
@@ -282,4 +294,18 @@ func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
"share one budget",
stub.calls[0].deadline, stub.calls[1].deadline)
}
+ // And that the config-schema pair shares its budget the same way, since a
+ // fresh deadline there is exactly what took the old ceiling to four.
+ if len(stub.calls) >= 4 {
+ if stub.calls[2].deadline != stub.calls[3].deadline {
+ t.Errorf("`config get agents.list --json` and `config get agents.entries --json` ran "+
+ "under separate deadlines (%v vs %v); they answer the same question and must "+
+ "share one budget, or the worst case grows a deadline",
+ stub.calls[2].deadline, stub.calls[3].deadline)
+ }
+ if stub.calls[4].deadline == stub.calls[2].deadline {
+ t.Errorf("the registry fallback shares the config-schema deadline; it reads a " +
+ "different source and must keep its own budget")
+ }
+ }
}