Skip to content

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

Go

fix(daemon): own the openclaw CLI process tree so its deadline is enforceable (MUL-5467, MUL-5630, MUL-6736) (#6275)

VvV7d128b5a45eb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index deb4fbeb7c..01e6b56d31 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -657,6 +657,21 @@ jobs:
# -v makes RUN/PASS evidence explicit in CI logs.
run: go test ./pkg/agent -v -run '^(TestStartOwnedProcessTreeCapturesImmediateDescendants|TestStartOwnedProcessTreeLeavesNoSuspendedChild|TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed|TestCodexInitializeRetrySupportedWithOwnedProcessTree|TestCodexWindowsDescendantsDieWithTheOwnedProcessTree)$' -count=1 -timeout=5m
+ - name: Test bounded CLI output collection on Windows
+ if: ${{ needs.changes.outputs.backend == 'true' }}
+ working-directory: server
+ # MUL-5467: RunCollect / RunCollectQuiet own the pipes as well as the
+ # process tree on the OpenClaw CLI paths, which outputOwned cannot. A real
+ # Windows host proves its Job Object owns and
+ # terminates descendants, a CLI that prints its answer and then refuses
+ # to exit still yields that answer, a response still streaming at the
+ # deadline is NOT reported as success, and no collector goroutine
+ # outlives the call. Unix uses process groups, so it cannot exercise this
+ # platform lifecycle.
+ # -v so a skip (a -run pattern that stops matching) is visible in the log
+ # instead of passing as "ok".
+ run: go test ./pkg/agent -v -run '^TestWindowsRunCollect' -count=1 -timeout=5m
+
- name: Test Windows OpenClaw npm shim interpreter resolution
if: ${{ needs.changes.outputs.backend == 'true' }}
working-directory: server
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index 5fcbb79000..c7a394d5e5 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -8,11 +8,12 @@ import (
"fmt"
"log/slog"
"os"
- "os/exec"
"path/filepath"
"sort"
"strings"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
)
// openclawConfigFile is the per-task synthesized OpenClaw config the daemon
@@ -41,31 +42,45 @@ const openclawUserSnapshotFile = "openclaw-user-snapshot.json"
// 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
+// (openclawMaxCLIDeadlinesPerPreparation serial steps 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.
+// The gap that used to be documented here — that this was a deadline and not a
+// cap — is closed as of MUL-5467. Keeping the measurements, because they are
+// what the fix has to hold against: CommandContext kills only the direct child,
+// and cmd.Output() blocks in Wait() until the stdout pipe closes, so a CLI that
+// leaves a descendant holding stdout ran for the descendant's lifetime.
+// Measured on linux/dash: a shim whose backgrounded child slept 6s took 6.01s
+// against a 150ms deadline. An npm shim is that shape on Windows (cmd.exe →
+// node). A cmd.WaitDelay backstop bounded the call but left the descendant
+// running (measured: returns in 2.17s with the grandchild still in state S),
+// trading a hang for a process leak, and on Unix nothing reaped it because
+// preparationProcessController.finish() is a no-op there.
+//
+// execOpenclawCLI goes through agent.RunCollectQuiet, which owns the pipes and
+// the process tree (Unix process group, Windows Job Object). Owning the pipes is
+// what makes the deadline enforceable: os/exec's own Wait cannot return while a
+// descendant holds an output pipe, so the bound has to come from somewhere else,
+// and a caller-side bound that reports failure would fail a call whose answer
+// arrived. Owning the tree is what stops the descendant becoming an orphan.
//
-// Known gap (deliberately not fixed here): this deadline does not actually
-// bound the call when the CLI leaves a descendant holding stdout.
-// CommandContext kills only the direct child, and cmd.Output() blocks in
-// Wait() until the stdout pipe closes, so the call runs for the descendant's
-// lifetime. Measured on linux/dash: a shim whose backgrounded child slept 6s
-// took 6.01s against a 150ms deadline. An npm shim is that shape on Windows
-// (cmd.exe → node).
+// Two limits on that claim, both deliberate:
//
-// A cmd.WaitDelay backstop bounds the call but leaves the descendant running
-// (measured: returns in 2.17s with the grandchild still in state S), trading a
-// hang for a process leak — and on Unix nothing reaps it, because
-// preparationProcessController.finish() is a no-op there. Closing this properly
-// needs process-tree ownership (Unix process group, Windows Job Object) so the
-// 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.
+// - "Enforceable", not "nothing survives": `openclaw-config` was measured with
+// its own PGID and SID, so on Unix no group signal reaches it. The deadline
+// holds anyway, because it is pipe ownership rather than the kill that makes
+// the call return.
+// - Returning before the CLI exits requires a completeness rule that the CLI's
+// pre-answer output cannot satisfy, which in practice means `--json` (see
+// openclawOutputComplete). Without one — `config file` as the fallback — this
+// deadline is what the call is bounded by, and reaching it is a failure. That
+// is a deliberate trade: an earlier revision judged `config file`'s stdout by
+// shape and review showed it returning a path-shaped *warning* line as the
+// answer.
const openclawCLITimeout = 30 * time.Second
// OpenclawCLITimeoutEnv overrides openclawCLITimeout. Accepts a Go duration
@@ -81,31 +96,39 @@ const (
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
+ // worst case is openclawMaxCLIDeadlinesPerPreparation serial steps, 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.
+ // prepare-timeout reason. A step may make more than one invocation — path
+ // resolution falls back from `config validate --json` to `config file` under
+ // one shared deadline — which is why the multiplier counts deadlines.
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.
+// openclawMaxCLIDeadlinesPerPreparation is how many CLI deadlines one task
+// preparation can consume in the worst case. Deadlines, not invocations: each
+// deadline bounds one *step*, and it is the sum of the steps that has to fit
+// inside the outer preparation budget, so this is the multiplier
+// openclawCLIMaxTimeout is derived from.
//
-// The four call sites, in the order they can fire:
+// The four steps, in the order they can fire:
//
-// 1. `config file` — locate the active config
+// 1. locate the active config — `config validate --json`, then `config file`
+// 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 fifth budget.
// 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
+// Adding a fifth deadline-bearing step means re-deriving the ceiling. The
+// worst-case test counts distinct deadlines rather than calls, so a new
+// invocation that shares an existing budget is free and one that brings its own
+// fails loudly.
+const openclawMaxCLIDeadlinesPerPreparation = 4
// ErrOpenclawCLITimeout marks a task preparation that failed because the local
// openclaw CLI did not answer within the deadline. It is a sentinel rather
@@ -648,23 +671,80 @@ func stripUserMcpServers(resolved map[string]any) {
}
}
-// openclawActiveConfigPath runs `openclaw config file` to discover the path
-// the openclaw CLI considers active. Returns (absolutePath, exists, error).
+// openclawActiveConfigPath discovers the path the openclaw CLI considers active.
+// Returns (absolutePath, exists, error).
//
// The CLI handles the full resolution chain — explicit config path, state
// directory, OPENCLAW_HOME / default home, legacy locations, migration, and `~`
// expansion — so we prefer it when the installed CLI supports the command.
//
+// `config validate --json` is asked first, and `config file` is only the
+// fallback, because the two differ in whether the answer can be recognised:
+//
+// - `config validate --json` puts the path in a named `path` field of a JSON
+// document, and its stdout is that document and nothing else. Measured on
+// OpenClaw 2026.7.1-2 with a warning-producing config: 715 bytes, one line,
+// parseable whole. The Doctor and plugin warnings do not disappear — they
+// arrive as a `warnings` array *inside* the payload, which is what keeps the
+// stream parseable rather than merely quieter. (Upstream also has a
+// console-log reroute for `--json` argv, `withConsoleLogsRoutedToStderrForJson`,
+// but the structured payload is what was observed doing the work here.)
+// - `config file` prints the path as its *last line*, after any Doctor and
+// plugin warnings, on stdout. Deciding "is the answer in yet" then means
+// asking whether the last line looks like a path — and a warning line that
+// names one is indistinguishable. Review demonstrated it: a stub printing an
+// existing `plugin-cache.json` path, then pausing, then printing the real
+// path had the warning accepted as the answer.
+//
+// Both commands perform the same `readConfigFileSnapshot()` read upstream
+// (checked at `v2026.7.1`: `runConfigFile` prints `shortenHomePath(snapshot.path)`
+// and `runConfigValidate` reports `snapshot.path`, `snapshot.exists` and
+// `snapshot.valid` from that same snapshot), so validation is already part of the
+// read `config file` does. Measured, the JSON form is not merely no worse but
+// meaningfully cheaper: 1.65/1.66/1.65s against 6.36/4.16/4.06s for `config file`
+// over three runs each on the same host and config, which tracks the output it
+// does not have to render — 715 bytes of JSON against 2663 bytes and 28 lines of
+// warning UI.
+//
+// `config validate --json` has carried the `path` field on every branch since
+// `v2026.5.5`, which is minOpenclawVersion. Two of those branches exit non-zero —
+// a missing file and an invalid config, both with the path in the payload and
+// stderr empty — so the exit status must not be read as "no answer"; see
+// openclawValidatedConfigPath.
+//
// OpenClaw 2026.2.x briefly rejected `openclaw config file` with the generic
// "too many arguments for 'config'" error. For that command-shape failure only,
// fall back to the same active-config candidate shape so task prep can still
// continue without losing upgraded users' legacy config files.
//
-// The reported path uses `~` shorthand for the user's home; we expand it
-// so the $include reference we write is unambiguous absolute.
+// A reported path may use `~` or `$OPENCLAW_HOME` shorthand; we expand it so the
+// $include reference we write is unambiguously absolute.
func openclawActiveConfigPath(bin string, timeout time.Duration) (string, bool, error) {
+ // One deadline for the question, not one per attempt. Both invocations answer
+ // "where is the active config", so they are a single step of preparation with
+ // a preferred and a fallback way of asking — and the budget that has to hold
+ // is the step's. Giving the fallback a fresh full deadline made the worst case
+ // five deadlines against a ceiling derived from four: at the 60s override
+ // ceiling that is 5m of CLI time alone, landing exactly on
+ // daemon.defaultTaskPrepareTimeout, which collapses the specific
+ // non-retryable ErrOpenclawCLITimeout back into the generic retryable prepare
+ // timeout — the outcome openclawCLIMaxTimeout exists to prevent.
+ //
+ // The consequence is deliberate: a `config validate --json` that burns the
+ // whole budget leaves the fallback none, and openclawExec then fails
+ // immediately on the expired context — os/exec's Start reports it, and
+ // execOpenclawCLI attributes ctx first, so it still surfaces as
+ // ErrOpenclawCLITimeout. That is the right report. A CLI that cannot say where
+ // its config is within the entire deadline will not answer the same question
+ // on a second one; a fresh budget would only double the time to an identical
+ // conclusion, and spend it inside the outer preparation deadline.
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
+
+ if path, ok := openclawValidatedConfigPath(ctx, bin); ok {
+ return openclawStatConfigPath(path)
+ }
+
out, err := openclawExec(ctx, bin, "config", "file")
if err != nil {
if isOpenclawConfigFileUnsupported(err) {
@@ -679,6 +759,66 @@ func openclawActiveConfigPath(bin string, timeout time.Duration) (string, bool,
return openclawParseActiveConfigPath(out)
}
+// openclawValidatedConfigPath asks `openclaw config validate --json` for the
+// active config path, and reports whether the answer was unambiguous.
+//
+// It takes the caller's ctx rather than its own timeout: this attempt and the
+// `config file` fallback share one deadline, because they are two ways of asking
+// the same question. See openclawActiveConfigPath.
+//
+// The exit status is deliberately not consulted, and that is the common case
+// rather than a corner: measured on 2026.7.1-2, upstream exits 1 both for a
+// missing config file (`{"valid":false,"path":"…","error":"file not found"}`) and
+// for an invalid one (`{"valid":false,"path":"…","issues":[…]}`), with stderr empty
+// and the path present in both. A fresh install is the missing-file case, so
+// reading a non-zero exit as "no answer" would break first run. Whether the user's
+// config parses is not this function's question either — openclaw itself reports
+// that when it runs; all that is owed here is where the file is.
+//
+// Failure is silent by design: every failure mode here is a reason to ask
+// `config file` instead, and reporting one would turn "this CLI answered in a
+// shape we do not understand" into a task failure. The only requirement is that
+// the path be absolute after expansion, which is what distinguishes a real answer
+// from the `CONFIG_PATH ?? "openclaw.json"` fallback upstream prints when it
+// throws before reading the snapshot.
+func openclawValidatedConfigPath(ctx context.Context, bin string) (string, bool) {
+ out, _ := openclawExec(ctx, bin, "config", "validate", "--json")
+ trimmed := strings.TrimSpace(out)
+ if trimmed == "" {
+ return "", false
+ }
+ var payload struct {
+ Path string `json:"path"`
+ }
+ if err := json.Unmarshal([]byte(trimmed), &payload); err != nil {
+ return "", false
+ }
+ reported := strings.TrimSpace(payload.Path)
+ if reported == "" {
+ return "", false
+ }
+ // The reported value must already name an absolute location, before any
+ // expansion. Upstream prints `CONFIG_PATH ?? "openclaw.json"` when it throws
+ // before reading the snapshot, and expandOpenclawPath would turn that bare
+ // relative literal into a confident `<daemon cwd>/openclaw.json` — the #6630
+ // failure shape, arrived at from a different direction. The `~` and
+ // `$OPENCLAW_HOME` forms are absolute once resolved, so they are allowed
+ // through; anything else relative is not an answer, and `config file` gets
+ // asked instead.
+ if !filepath.IsAbs(reported) {
+ _, isTilde := openclawTildeRest(reported)
+ _, isHome := openclawHomeRest(reported)
+ if !isTilde && !isHome {
+ return "", false
+ }
+ }
+ expanded, err := expandOpenclawPath(reported)
+ if err != nil || !filepath.IsAbs(expanded) {
+ return "", false
+ }
+ return expanded, true
+}
+
func openclawParseActiveConfigPath(out string) (string, bool, error) {
// OpenClaw may print terminal UI borders (e.g., Doctor warnings) before
// the actual path. The path is always the last non-empty line.
@@ -827,7 +967,11 @@ func openclawTildeRest(path string) (string, bool) {
// `src/cli/config-cli.ts`'s `runConfigFile` prints `shortenHomePath(...)`, and
// `src/utils.ts:147-157` uses the `$OPENCLAW_HOME` prefix whenever that variable
// is non-empty and `~` otherwise — so setting the variable is what selects this
-// form.
+// form. Still true at `v2026.7.1`: `runConfigFile` is unchanged, and
+// `resolveHomeDisplayPrefix` there returns `$OPENCLAW_HOME` on a non-empty
+// trimmed `OPENCLAW_HOME` and `~` otherwise, with the separator coming from the
+// original path rather than being inserted — which is why the rest is sliced
+// after the prefix here rather than trimmed of a leading separator.
//
// Only the bare spelling is emitted by that code path. `${OPENCLAW_HOME}` is
// accepted as defense against a release that spells it the other way, not
@@ -975,6 +1119,12 @@ func openclawResolvedFullConfig(bin string, timeout time.Duration) (map[string]a
if trimmed == "" || trimmed == "null" {
return nil, nil
}
+ // This target is an object, so an envelope decodes cleanly and would be
+ // carried into the sanitized snapshot as if it were the user's config. There
+ // is no graceful reading of an error here: fail closed.
+ if message, isEnvelope := openclawJSONErrorMessage(trimmed); isEnvelope {
+ return nil, openclawStdoutEnvelopeError("config get --json", message)
+ }
var cfg map[string]any
if err := json.Unmarshal([]byte(trimmed), &cfg); err != nil {
return nil, fmt.Errorf("parse `openclaw config get --json` output: %w", err)
@@ -1016,6 +1166,17 @@ func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, bool,
if trimmed == "" || trimmed == "null" {
return nil, false, 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) {
+ list, rerr := openclawRegistryAgentsList(bin, timeout)
+ return list, true, rerr
+ }
+ return nil, false, 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)
@@ -1060,6 +1221,14 @@ func openclawRegistryAgentsList(bin string, timeout time.Duration) ([]any, error
if trimmed == "" || trimmed == "null" {
return nil, nil
}
+ // Same reasoning as the resolver above: without a non-zero exit the envelope
+ // only shows up here.
+ if message, isEnvelope := openclawJSONErrorMessage(trimmed); isEnvelope {
+ if isOpenclawKeyMissingMessage(message) || isOpenclawUnknownSubcommandMessage(message) {
+ return nil, nil
+ }
+ return nil, openclawStdoutEnvelopeError("agents list --json", message)
+ }
var list []any
if err := json.Unmarshal([]byte(trimmed), &list); err != nil {
return nil, fmt.Errorf("parse `openclaw agents list --json` output: %w", err)
@@ -1072,6 +1241,56 @@ func openclawRegistryAgentsList(bin string, timeout time.Duration) ([]any, error
// to avoid spawning a real binary. Production code never reassigns it.
var openclawExec = execOpenclawCLI
+// openclawLastNonEmptyLine returns the last non-empty, trimmed line of out.
+// Used by openclawParseActiveConfigPath for the `config file` fallback, where the
+// path is the last line the CLI prints.
+func openclawLastNonEmptyLine(out string) string {
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ for i := len(lines) - 1; i >= 0; i-- {
+ if trimmed := strings.TrimSpace(lines[i]); trimmed != "" {
+ return trimmed
+ }
+ }
+ return ""
+}
+
+// openclawOutputComplete returns the rule that decides whether the bytes
+// captured so far are a finished answer for this openclaw subcommand, for
+// agent.RunCollectQuiet's early return.
+//
+// Only `--json` commands get one, and that is the whole design rather than a gap
+// to fill in later. Two properties make a JSON answer recognisable, and neither
+// has an equivalent for human-readable output:
+//
+// - The document has to parse *as a whole*, so a response still being written
+// cannot satisfy the rule, no matter how long the writer pauses mid-way.
+// - A `--json` stdout carries the document and nothing else. Measured on
+// 2026.7.1-2 with a warning-producing config, `config validate --json` emitted
+// one 715-byte line that parses whole, with the Doctor and plugin warnings
+// carried as a `warnings` array inside it. Without `--json` those same
+// warnings are 28 lines of UI sharing stdout with the answer.
+//
+// An earlier revision of this branch also had a rule for `config file`: accept
+// the buffer once its last non-empty line looks like a path. Review broke it with
+// a stub that prints an existing `plugin-cache.json` path, pauses past any fixed
+// grace, and then prints the real path — the warning was returned as the answer.
+// That is not fixable by waiting longer, because the pause is the host's plugin
+// and Doctor work and has no bound; it is fixable by not asking a question that
+// content cannot answer. openclawActiveConfigPath now prefers
+// `config validate --json`, whose path arrives in a named field.
+//
+// A nil result means "no rule for this shape", which makes RunCollectQuiet wait
+// for the process to exit — the conservative behaviour, and what `config file`
+// now gets when it is used as the fallback.
+func openclawOutputComplete(args []string) agent.OutputComplete {
+ for _, a := range args {
+ if a == "--json" {
+ return agent.JSONOutputComplete
+ }
+ }
+ return nil
+}
+
// execOpenclawCLI executes an openclaw subcommand and returns its stdout,
// including stdout captured before a non-zero exit. Failed stdout stays in the
// separate return value and this execution layer never appends it to the error:
@@ -1102,14 +1321,21 @@ var openclawExec = execOpenclawCLI
// check cancellation the standard way. The process error is still printed for
// diagnosis, just not as the wrapped cause.
func execOpenclawCLI(ctx context.Context, bin string, args ...string) (string, error) {
- cmd := exec.CommandContext(ctx, bin, args...)
- cmd.Env = os.Environ()
- var stderr strings.Builder
- cmd.Stderr = &stderr
- raw, err := cmd.Output()
+ // agent.RunCollectQuiet, not cmd.Output(): this package owns the pipes and
+ // the process tree, which is what makes the deadline above enforceable at all
+ // (MUL-5467 — see openclawCLITimeout). The per-subcommand rule from
+ // openclawOutputComplete additionally lets a CLI that prints its answer and
+ // then refuses to exit be treated as finished, so `openclaw config file` no
+ // longer has to reach the deadline to be useful.
+ //
+ // Every error shape below is unchanged, including returning captured stdout
+ // alongside the error: annotateOpenclawJSONError reads it, and the typed
+ // timeout sentinel is what lets the daemon classify a local stall
+ // structurally.
+ raw, stderrOut, _, err := agent.RunCollectQuiet(ctx, os.Environ(), 0, openclawOutputComplete(args), bin, args...)
stdout := string(raw)
if err != nil {
- stderrMsg := strings.TrimSpace(stderr.String())
+ stderrMsg := strings.TrimSpace(stderrOut)
if ctxErr := ctx.Err(); ctxErr != nil {
msg := fmt.Sprintf("openclaw %s: %v (process: %v)", strings.Join(args, " "), ctxErr, err)
if stderrMsg != "" {
@@ -1240,11 +1466,32 @@ func annotateOpenclawJSONError(err error, stdout string) error {
if !ok {
return err
}
+ return fmt.Errorf("%w (json error: %s)", err, openclawBoundedJSONErrorMessage(message))
+}
+
+func openclawBoundedJSONErrorMessage(message string) string {
runes := []rune(message)
if len(runes) > openclawJSONErrorMaxRunes {
- message = string(runes[:openclawJSONErrorMaxRunes]) + "…"
+ return string(runes[:openclawJSONErrorMaxRunes]) + "…"
}
- return fmt.Errorf("%w (json error: %s)", err, message)
+ return message
+}
+
+// openclawStdoutEnvelopeError turns a CLI error envelope that arrived on stdout
+// *without* a non-zero exit into an error.
+//
+// The completeness rules let RunCollectQuiet accept a finished-looking answer
+// from a CLI that has printed it but not exited yet (see openclawOutputComplete),
+// and a JSON error envelope is itself valid JSON, so JSONOutputComplete accepts
+// one. The exit-status path therefore no longer sees every CLI error: a build
+// that prints `{"error": "..."}` and then lingers past the idle grace hands back
+// err == nil with the envelope sitting in stdout. Callers must check for that
+// explicitly, because decoding an envelope as data is silent for an object
+// target — it would be written straight into the generated config — and only
+// accidentally noisy for a list target, where the type mismatch surfaces as an
+// opaque parse error instead of the CLI's own message.
+func openclawStdoutEnvelopeError(command, message string) error {
+ return fmt.Errorf("`openclaw %s` reported: %s", command, openclawBoundedJSONErrorMessage(message))
}
// isOpenclawKeyMissingResult recognizes the JSON error envelope observed in
@@ -1296,7 +1543,11 @@ func isOpenclawUnknownSubcommand(err error) bool {
if err == nil {
return false
}
- msg := strings.ToLower(err.Error())
+ return isOpenclawUnknownSubcommandMessage(err.Error())
+}
+
+func isOpenclawUnknownSubcommandMessage(msg string) bool {
+ msg = strings.ToLower(msg)
return strings.Contains(msg, "unknown command") ||
strings.Contains(msg, "unknown option") ||
strings.Contains(msg, "does not recognize") ||
diff --git a/server/internal/daemon/execenv/openclaw_config_cache.go b/server/internal/daemon/execenv/openclaw_config_cache.go
index 09bff0c32b..1d3d06e17e 100644
--- a/server/internal/daemon/execenv/openclaw_config_cache.go
+++ b/server/internal/daemon/execenv/openclaw_config_cache.go
@@ -15,8 +15,8 @@ import (
)
// 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
+// preparation in the common case (`config validate --json`, then
+// `config get agents.list --json`; see openclawMaxCLIDeadlinesPerPreparation 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
diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.go
index 55d6f21037..835ee6bbac 100644
--- a/server/internal/daemon/execenv/openclaw_config_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_test.go
@@ -11,6 +11,7 @@ import (
"path/filepath"
"strings"
"testing"
+ "time"
)
// openclawCLIStub captures one or more (subcommand, response) pairs and
@@ -27,6 +28,12 @@ type openclawCLIStub struct {
type openclawCall struct {
bin string
args []string
+ // deadline is the ctx deadline this invocation ran under, zero if it had
+ // none. Recorded because the budget the ceiling is derived from counts
+ // deadlines, not calls: path resolution makes two invocations under one
+ // shared deadline, and a test that counted calls could not tell that apart
+ // from a fifth budget. See TestPrepareOpenclawConfigWorstCaseCLIBudgets.
+ deadline time.Time
}
type openclawResponse struct {
@@ -47,14 +54,53 @@ func installOpenclawStub(t *testing.T, responses map[string]openclawResponse) *o
return stub
}
-func (s *openclawCLIStub) exec(_ context.Context, bin string, args ...string) (string, error) {
- s.calls = append(s.calls, openclawCall{bin: bin, args: append([]string(nil), args...)})
+func (s *openclawCLIStub) exec(ctx context.Context, bin string, args ...string) (string, error) {
+ deadline, _ := ctx.Deadline()
+ s.calls = append(s.calls, openclawCall{bin: bin, args: append([]string(nil), args...), deadline: deadline})
key := strings.Join(args, " ")
- resp, ok := s.responses[key]
+ if resp, ok := s.responses[key]; ok {
+ return resp.stdout, resp.err
+ }
+ if key == "config validate --json" {
+ return s.derivedValidateResponse()
+ }
+ return "", fmt.Errorf("openclawCLIStub: unexpected args %q", key)
+}
+
+// derivedValidateResponse answers `config validate --json` from the registered
+// `config file` response when a test did not register one itself.
+//
+// openclawActiveConfigPath asks `config validate --json` first because its answer
+// arrives in a named field (see there). Almost every test in this package fixes
+// the *outcome* of path resolution — which file the wrapper $includes, how many
+// CLI calls a cold preparation makes, what happens when the CLI is missing — and
+// not which subcommand supplies it. Deriving keeps those tests stating what they
+// are about; hand-writing a second response into 30-odd maps would turn the next
+// change to this boundary into a 30-site edit and bury the two tests that do care.
+//
+// A test that cares registers "config validate --json" explicitly:
+// TestOpenclawActiveConfigPathIgnoresAPathShapedWarning and the fallback cases in
+// openclaw_process_tree_test.go drive the real binary instead, so they are
+// unaffected by this.
+func (s *openclawCLIStub) derivedValidateResponse() (string, error) {
+ resp, ok := s.responses["config file"]
if !ok {
- return "", fmt.Errorf("openclawCLIStub: unexpected args %q", key)
+ return "", fmt.Errorf("openclawCLIStub: no `config file` response to derive validate from")
+ }
+ // An unusable `config file` means an unusable CLI for this purpose: report the
+ // same failure so the test exercises whatever fallback it is about.
+ if resp.err != nil {
+ return "", resp.err
+ }
+ path := strings.TrimSpace(resp.stdout)
+ if path == "" {
+ return "", nil
}
- return resp.stdout, resp.err
+ payload, err := json.Marshal(map[string]any{"valid": true, "path": path})
+ if err != nil {
+ return "", err
+ }
+ return string(payload) + "\n", nil
}
func mustReadJSON(t *testing.T, path string) map[string]any {
@@ -246,11 +292,23 @@ func TestPrepareOpenclawConfigFallsBackWhenConfigFileUnsupported(t *testing.T) {
if len(list) != 1 || list[0].(map[string]any)["workspace"] != workDir {
t.Errorf("agents.list workspace rewrite after fallback = %v, want workDir %q", list, workDir)
}
- if len(stub.calls) != 2 {
- t.Fatalf("openclaw calls = %d, want 2: %+v", len(stub.calls), stub.calls)
+ // Three calls, not two, and the extra one is the point of this test now: a CLI
+ // too old to support `config file` is also too old for `config validate --json`,
+ // so path resolution asks both before falling back to the candidate shape. That
+ // is one extra invocation on exactly the hosts that were already on a
+ // deprecated command shape, and it buys every current host an answer that a
+ // path-shaped warning line cannot corrupt (see openclawActiveConfigPath).
+ if len(stub.calls) != 3 {
+ t.Fatalf("openclaw calls = %d, want 3: %+v", len(stub.calls), stub.calls)
+ }
+ if got := strings.Join(stub.calls[0].args, " "); got != "config validate --json" {
+ t.Errorf("first openclaw call = %q, want config validate --json", got)
+ }
+ if got := strings.Join(stub.calls[1].args, " "); got != "config file" {
+ t.Errorf("second openclaw call = %q, want config file", got)
}
- if strings.Join(stub.calls[1].args, " ") != "config get agents.list --json" {
- t.Errorf("second openclaw call = %q, want config get agents.list --json", strings.Join(stub.calls[1].args, " "))
+ if strings.Join(stub.calls[2].args, " ") != "config get agents.list --json" {
+ t.Errorf("third openclaw call = %q, want config get agents.list --json", strings.Join(stub.calls[2].args, " "))
}
}
@@ -1100,6 +1158,97 @@ func TestPrepareOpenclawConfigManagedSetFreshInstall(t *testing.T) {
}
}
+// TestPrepareOpenclawConfigFallsBackToRegistryOnEnvelopeWithoutExit — the
+// completeness rule accepts a JSON error envelope as a finished answer (it is
+// valid JSON), so a CLI that prints one and then lingers past the idle grace
+// yields err == nil with the envelope in stdout. The missing-key verdict must be
+// the same as when the CLI exits non-zero: select the registry rather than
+// decoding the envelope as an agent list and failing the whole preparation.
+func TestPrepareOpenclawConfigFallsBackToRegistryOnEnvelopeWithoutExit(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)
+ }
+ userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
+ if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
+ stub := installOpenclawStub(t, map[string]openclawResponse{
+ "config file": {stdout: userCfgPath},
+ // Envelope, no error: the CLI answered and then failed to exit.
+ "config get agents.list --json": {stdout: `{"error":"Config path not found: agents.list"}`},
+ "agents list --json": {stdout: `[{"id":"scout","workspace":"/old"}]`},
+ })
+
+ // Without the envelope check this decodes as an agent list, fails to
+ // unmarshal into []any, and takes the whole preparation down.
+ if _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{}); err != nil {
+ t.Fatalf("prepareOpenclawConfig: %v", err)
+ }
+ var called []string
+ registryConsulted := false
+ for _, call := range stub.calls {
+ joined := strings.Join(call.args, " ")
+ called = append(called, joined)
+ if joined == "agents list --json" {
+ registryConsulted = true
+ }
+ }
+ if !registryConsulted {
+ t.Errorf("registry was never consulted (calls: %v), so the envelope was not recognized", called)
+ }
+ wrapper, err := os.ReadFile(filepath.Join(envRoot, openclawConfigFile))
+ if err != nil {
+ t.Fatalf("read wrapper: %v", err)
+ }
+ // A registry-sourced list is deliberately not written back as
+ // `agents.list` (see buildPerTaskOpenclawConfig), but the envelope must not
+ // reach the wrapper by any route either.
+ if strings.Contains(string(wrapper), "Config path not found") {
+ t.Errorf("wrapper %s carries the CLI error envelope", wrapper)
+ }
+}
+
+// TestPrepareOpenclawConfigFailsClosedOnResolvedConfigEnvelopeWithoutExit — the
+// object-target counterpart, and the one with a silent failure mode: an envelope
+// decoded as the user's resolved config would be sanitized and written into the
+// task's snapshot, so preparation has to fail closed with the CLI's own message.
+func TestPrepareOpenclawConfigFailsClosedOnResolvedConfigEnvelopeWithoutExit(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)
+ }
+ userCfgPath := filepath.Join(t.TempDir(), "openclaw.json")
+ if err := os.WriteFile(userCfgPath, []byte(`{}`), 0o600); err != nil {
+ t.Fatalf("write user cfg: %v", err)
+ }
+ installOpenclawStub(t, map[string]openclawResponse{
+ "config file": {stdout: userCfgPath},
+ "config get agents.list --json": {stdout: "null"},
+ "config get --json": {
+ stdout: `{"error":"schema validation failed","resolved":{"apiKey":"must-not-leak"}}`,
+ },
+ })
+
+ _, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
+ McpConfig: json.RawMessage(`{"mcpServers": {"context7": {"command": "uvx"}}}`),
+ })
+ if err == nil {
+ t.Fatal("prepareOpenclawConfig succeeded on an error envelope that arrived without a non-zero exit")
+ }
+ if !strings.Contains(err.Error(), "schema validation failed") {
+ t.Errorf("error %q omits the CLI's own diagnostic", err.Error())
+ }
+ if strings.Contains(err.Error(), "must-not-leak") {
+ t.Errorf("error leaked a non-diagnostic JSON field: %q", err.Error())
+ }
+ if _, statErr := os.Stat(filepath.Join(envRoot, openclawUserSnapshotFile)); !os.IsNotExist(statErr) {
+ t.Errorf("snapshot exists after fail-closed: %v", statErr)
+ }
+}
+
// TestPrepareOpenclawConfigFailsClosedOnResolvedConfigError — when the
// user has a config on disk and the agent has managed mcp_config but
// `openclaw config get --json` errors, the preparer must NOT fall back to
diff --git a/server/internal/daemon/execenv/openclaw_config_timeout_test.go b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
index f0379e5588..7ecd3891ed 100644
--- a/server/internal/daemon/execenv/openclaw_config_timeout_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
@@ -164,10 +164,10 @@ func TestExecOpenclawCLICancellationIsNotATimeout(t *testing.T) {
}
// 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
+// override ceiling rests on. Each preparation *step* gets its own deadline, so
+// the budget that matters is worst-case-deadlines 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.
@@ -178,23 +178,82 @@ func TestOpenclawCLIMaxTimeoutFitsPreparationBudget(t *testing.T) {
// Everything Prepare does besides openclaw config discovery.
const nonOpenclawPrepareSlack = time.Minute
- worst := openclawMaxCLICallsPerPreparation * openclawCLIMaxTimeout
+ worst := openclawMaxCLIDeadlinesPerPreparation * 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)
+ t.Errorf("worst-case openclaw discovery %v (%d deadlines x %v) leaves less than %v under the %v preparation budget",
+ worst, openclawMaxCLIDeadlinesPerPreparation, 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) {
+// TestOpenclawActiveConfigPathSpendsOneBudgetAcrossBothAttempts is the
+// consequence of sharing that deadline, asserted rather than left implicit.
+//
+// A `config validate --json` that burns the whole budget leaves the `config file`
+// fallback none, and the call fails on the shared deadline instead of starting a
+// second full one. That is the intended trade: a CLI that cannot say where its
+// config is inside the entire deadline will not answer the same question on a
+// fresh one, and the failure still carries ErrOpenclawCLITimeout — the specific,
+// non-retryable reason — rather than doubling the time spent inside the outer
+// preparation budget to reach an identical conclusion.
+func TestOpenclawActiveConfigPathSpendsOneBudgetAcrossBothAttempts(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)
+ }
+ // `config validate --json` hangs; `config file` would answer instantly if it
+ // were ever given the chance.
+ shim := writeShim(t, t.TempDir(),
+ "#!/bin/sh\n"+
+ "case \"$*\" in\n"+
+ " 'config validate --json') "+sleepBin+" 30 ;;\n"+
+ " 'config file') printf '/tmp/openclaw.json\\n' ;;\n"+
+ "esac\n", "")
+
+ const budget = 1500 * time.Millisecond
+ start := time.Now()
+ _, _, err = openclawActiveConfigPath(shim, budget)
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Fatal("expected path resolution to fail once its shared deadline expired")
+ }
+ if !errors.Is(err, ErrOpenclawCLITimeout) {
+ t.Errorf("errors.Is(err, ErrOpenclawCLITimeout) must hold so the daemon still "+
+ "reports the specific, non-retryable reason\ngot: %s", err)
+ }
+ // The point of the assertion: two budgets would take at least 2x the deadline.
+ // The margin above one budget covers the collector's reap and settle windows.
+ if elapsed >= 2*budget {
+ t.Errorf("path resolution took %v, i.e. at least two %v budgets — the "+
+ "fallback must share the deadline, not start a fresh one", elapsed, budget)
+ }
+}
+
+// TestPrepareOpenclawConfigWorstCaseCLIBudgets pins the multiplier the budget
+// above depends on, and it counts *deadlines* rather than calls.
+//
+// That distinction is the review finding it exists for. The worst case is not the
+// common two calls: `config validate --json` can fail to answer and fall back to
+// `config file`, a 2026.6+ host falls back to the registry subcommand, and an
+// agent with a managed mcp_config additionally reads the full resolved config —
+// five invocations. The previous version of this test could not see the first of
+// those, because the stub synthesizes a `config validate --json` success from the
+// `config file` response, so the two never fired in the same run. With the
+// fallback carrying a fresh full deadline, five budgets at the 60s ceiling is 5m
+// of CLI time alone, landing exactly on daemon.defaultTaskPrepareTimeout — and
+// the specific, non-retryable ErrOpenclawCLITimeout collapses back into the
+// generic retryable one.
+//
+// So this drives the real worst case and asserts both halves: the call graph is
+// five invocations, and path resolution's two share one deadline, leaving four
+// budgets.
+func TestPrepareOpenclawConfigWorstCaseCLIBudgets(t *testing.T) {
envRoot := t.TempDir()
workDir := filepath.Join(envRoot, "workdir")
if err := os.MkdirAll(workDir, 0o755); err != nil {
@@ -206,7 +265,9 @@ func TestPrepareOpenclawConfigWorstCaseCLICallCount(t *testing.T) {
}
stub := installOpenclawStub(t, map[string]openclawResponse{
- // 1. locate the active config
+ // 1a. preferred path resolution, on a CLI too old to support it
+ "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")},
@@ -223,12 +284,42 @@ func TestPrepareOpenclawConfigWorstCaseCLICallCount(t *testing.T) {
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, " "))
+ var invocations []string
+ deadlines := map[time.Time]bool{}
+ for _, call := range stub.calls {
+ invocation := strings.Join(call.args, " ")
+ invocations = append(invocations, invocation)
+ if call.deadline.IsZero() {
+ t.Errorf("`openclaw %s` ran without a deadline; every CLI step must be bounded", invocation)
+ continue
}
- t.Errorf("worst-case preparation made %d CLI calls, but openclawMaxCLICallsPerPreparation is %d\ncalls: %v",
- got, openclawMaxCLICallsPerPreparation, args)
+ deadlines[call.deadline] = true
+ }
+
+ // The call graph itself, so a new invocation stays visible here even when it
+ // costs no extra budget.
+ wantInvocations := []string{
+ "config validate --json",
+ "config file",
+ "config get agents.list --json",
+ "agents list --json",
+ "config get --json",
+ }
+ if strings.Join(invocations, " | ") != strings.Join(wantInvocations, " | ") {
+ t.Errorf("worst-case invocations:\n got: %v\nwant: %v", invocations, wantInvocations)
+ }
+
+ if got := len(deadlines); got != openclawMaxCLIDeadlinesPerPreparation {
+ t.Errorf("worst-case preparation consumed %d CLI deadlines (%d invocations), but openclawMaxCLIDeadlinesPerPreparation is %d\ncalls: %v",
+ got, len(stub.calls), openclawMaxCLIDeadlinesPerPreparation, invocations)
+ }
+
+ // And specifically that the shared budget is path resolution's, since that is
+ // the pairing the ceiling now depends on.
+ if len(stub.calls) >= 2 && stub.calls[0].deadline != stub.calls[1].deadline {
+ t.Errorf("`config validate --json` and its `config file` fallback ran under "+
+ "separate deadlines (%v vs %v); they answer the same question and must "+
+ "share one budget",
+ stub.calls[0].deadline, stub.calls[1].deadline)
}
}
diff --git a/server/internal/daemon/execenv/openclaw_process_tree_test.go b/server/internal/daemon/execenv/openclaw_process_tree_test.go
new file mode 100644
index 0000000000..ea18a36930
--- /dev/null
+++ b/server/internal/daemon/execenv/openclaw_process_tree_test.go
@@ -0,0 +1,462 @@
+//go:build !windows
+
+package execenv
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Regression tests for the task-critical half of MUL-5467. prepareOpenclawConfig
+// shells out to `openclaw config file` / `openclaw config get ...` while
+// preparing a task's execution environment, so both OpenClaw misbehaviours land
+// on the path between "task claimed" and "agent started":
+//
+// - openclaw forks a long-lived `openclaw-config` helper that inherits
+// stdout/stderr. With cmd.Output(), os/exec waits for those pipes to reach
+// EOF, which never comes while the helper lives — and cancelling the context
+// kills the direct child without unblocking that wait, so openclawCLITimeout
+// could not bound the call.
+// - `openclaw config file` and `openclaw agents list` print the correct answer
+// in ~250ms and then do not exit, so waiting for exit turned two working
+// commands into a task-fatal error.
+
+// writeHelperForkingOpenclaw creates a fake openclaw with the first shape: emit
+// JSON on stdout, fork a helper that keeps the inherited stdout/stderr open far
+// longer than the test would wait, then exit 0.
+func writeHelperForkingOpenclaw(t *testing.T, pidFile string) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ body := `#!/bin/sh
+( echo $$ > "` + pidFile + `"; sleep 300 ) &
+# Make the helper's registration deterministic: without this the parent can
+# exit and the group be reaped before the helper runs, leaving the test with
+# no pid to assert on.
+while [ ! -s "` + pidFile + `" ]; do sleep 0.01; done
+echo '{}'
+exit 0
+`
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake openclaw: %v", err)
+ }
+ return bin
+}
+
+func readHelperPid(t *testing.T, pidFile string) int {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if data, err := os.ReadFile(pidFile); err == nil {
+ if pid, convErr := strconv.Atoi(strings.TrimSpace(string(data))); convErr == nil && pid > 0 {
+ return pid
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Fatalf("helper never wrote its pid to %s", pidFile)
+ return 0
+}
+
+func helperGone(pid int, within time.Duration) bool {
+ deadline := time.Now().Add(within)
+ for time.Now().Before(deadline) {
+ if syscall.Kill(pid, 0) != nil {
+ return true
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ return false
+}
+
+// TestExecOpenclawCLIReturnsDespitePipeHoldingHelper is the assertion that
+// makes openclawCLITimeout meaningful: the call must come back on the direct
+// child's exit, not on the helper's lifetime and not on the deadline.
+func TestExecOpenclawCLIReturnsDespitePipeHoldingHelper(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ bin := writeHelperForkingOpenclaw(t, pidFile)
+
+ // A deliberately generous deadline: before the fix this hung past it, so a
+ // tight ctx would have hidden the bug behind a plausible-looking timeout.
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ start := time.Now()
+ out, err := execOpenclawCLI(ctx, bin, "config", "get", "--json")
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("execOpenclawCLI: %v", err)
+ }
+ if strings.TrimSpace(out) != "{}" {
+ t.Errorf("stdout = %q, want {}", out)
+ }
+ if elapsed > 15*time.Second {
+ t.Errorf("execOpenclawCLI took %v — it waited on the helper instead "+
+ "of returning once openclaw itself exited", elapsed)
+ }
+}
+
+// TestExecOpenclawCLIReapsForkedHelper pins the cleanup half. Task preparation
+// runs per task, and this is where the orphan `openclaw-config` processes came
+// from. It is also what the reverted cmd.WaitDelay backstop could not do.
+func TestExecOpenclawCLIReapsForkedHelper(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ bin := writeHelperForkingOpenclaw(t, pidFile)
+
+ if _, err := execOpenclawCLI(context.Background(), bin, "config", "file"); err != nil {
+ t.Fatalf("execOpenclawCLI: %v", err)
+ }
+
+ pid := readHelperPid(t, pidFile)
+ if !helperGone(pid, 5*time.Second) {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("forked helper (pid %d) survived execOpenclawCLI — the "+
+ "orphan leak is back", pid)
+ }
+}
+
+// TestExecOpenclawCLIDoesNotSalvagePartialJSON pins that a `--json` subcommand
+// still streaming when the deadline arrives is an error, not a truncated success.
+func TestExecOpenclawCLIDoesNotSalvagePartialJSON(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ body := "#!/bin/sh\nprintf '{\"agents\":['\n" +
+ "while :; do printf '{\"id\":\"a\"},'; sleep 0.12; done\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake openclaw: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+
+ out, err := execOpenclawCLI(ctx, bin, "config", "get", "--json")
+ if err == nil {
+ t.Fatalf("partial JSON reported as success: %q", out)
+ }
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Errorf("errors.Is(err, context.DeadlineExceeded) must hold\ngot: %v", err)
+ }
+}
+
+// TestOpenclawOutputCompleteRules pins which rule each subcommand shape gets, and
+// that everything else gets none — which makes RunCollectQuiet wait for exit
+// rather than guess.
+func TestOpenclawOutputCompleteRules(t *testing.T) {
+ banner := []byte("┌────┐\n│ hi │\n└────┘\n")
+ partialJSON := []byte(`{"agents":[{"id":"a"},`)
+ fullJSON := []byte("{\"agents\":[]}\n")
+
+ // Only `--json` shapes get a rule. A JSON document has to parse as a whole, so
+ // no pause mid-write can be mistaken for a finished answer, and upstream keeps
+ // incidental output off a `--json` stdout entirely.
+ cases := []struct {
+ name string
+ env map[string]string
+ args []string
+ out []byte
+ want bool
+ }{
+ {name: "json, banner before the document never parses", args: []string{"config", "validate", "--json"}, out: append(append([]byte{}, banner...), fullJSON...), want: false},
+ {name: "json, validate payload", args: []string{"config", "validate", "--json"}, out: []byte(`{"valid":true,"path":"/home/u/.openclaw/openclaw.json"}`), want: true},
+ {name: "json, partial", args: []string{"config", "get", "--json"}, out: partialJSON, want: false},
+ {name: "json, complete", args: []string{"config", "get", "--json"}, out: fullJSON, want: true},
+ {name: "json, null is a real answer", args: []string{"config", "get", "agents.list", "--json"}, out: []byte("null\n"), want: true},
+ {name: "json, empty", args: []string{"agents", "list", "--json"}, out: nil, want: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ for k, v := range tc.env {
+ t.Setenv(k, v)
+ }
+ rule := openclawOutputComplete(tc.args)
+ if rule == nil {
+ t.Fatalf("no completeness rule for %v", tc.args)
+ }
+ if got := rule(tc.out); got != tc.want {
+ t.Errorf("rule(%q) = %v, want %v", tc.out, got, tc.want)
+ }
+ })
+ }
+
+ for _, args := range [][]string{
+ {"doctor"},
+ // `config file` deliberately has no rule any more. Its answer is the last
+ // line of a stdout it shares with Doctor and plugin warnings, so a rule
+ // could only ask "does the last line look like a path" — and review broke
+ // exactly that with a warning line that was one. See
+ // openclawActiveConfigPath, which prefers `config validate --json`.
+ {"config", "file"},
+ } {
+ if rule := openclawOutputComplete(args); rule != nil {
+ t.Errorf("%v must have no completeness rule, so the runner waits for exit "+
+ "instead of judging output whose shape cannot identify the answer", args)
+ }
+ }
+}
+
+// TestExecOpenclawCLIToleratesNonExitingCLI covers the second failure mode:
+// a CLI that prints its answer and then never exits.
+//
+// Measured on a 2026.5.27 host, `openclaw config file` printed the path in ~250ms
+// and then hung until killed, which reached the user as
+//
+// agent_error.process_failure (prepare execution environment: execenv:
+// prepare openclaw config: locate openclaw active config:
+// openclaw config file: context deadline exceeded (process: signal: killed))
+//
+// while the answer had been on stdout the whole time.
+//
+// Exercised on a `--json` subcommand, because that is where the tolerance lives
+// now: a JSON document is recognisable as finished, so waiting is provably
+// unnecessary. `config file` gave up its early return — see
+// TestOpenclawActiveConfigPathFailsClosedWhenConfigFileNeverExits for what it
+// does instead.
+func TestExecOpenclawCLIToleratesNonExitingCLI(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ body := "#!/bin/sh\n" +
+ "printf '{\"mcp\":{}}\\n'\n" +
+ "sleep 300\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake openclaw: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ start := time.Now()
+ out, err := execOpenclawCLI(ctx, bin, "config", "get", "mcp", "--json")
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("execOpenclawCLI: %v", err)
+ }
+ if strings.TrimSpace(out) != `{"mcp":{}}` {
+ t.Errorf("stdout = %q, want the printed document", out)
+ }
+ // Loose on purpose: only has to sit far below the 60s ctx and the stub's 300s
+ // sleep, either of which a broken mechanism would take.
+ if elapsed > 10*time.Second {
+ t.Errorf("took %v — waited for an exit that never comes", elapsed)
+ }
+}
+
+// writeOpenclawConfigStub writes a stub CLI that answers `config validate --json`
+// with validateOut, exiting validateExit, and `config file` with fileOut, appending
+// trailing to the `config file` branch (for stubs that must linger or delay).
+//
+// validateExit is a parameter because a non-zero exit is the *normal* case for two
+// of the three states measured on a real host: upstream exits 1 both for a missing
+// config file and for an invalid one, and carries the path in the payload either
+// way. A stub that could only exit 0 would test the rarest branch.
+func writeOpenclawConfigStub(t *testing.T, validateOut string, validateExit int, fileOut, fileTrailing string) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ body := "#!/bin/sh\n" +
+ "if [ \"$1\" = \"config\" ] && [ \"$2\" = \"validate\" ]; then\n" +
+ validateOut +
+ " exit " + strconv.Itoa(validateExit) + "\n" +
+ "fi\n" +
+ "if [ \"$1\" = \"config\" ] && [ \"$2\" = \"file\" ]; then\n" +
+ fileOut +
+ fileTrailing +
+ " exit 0\n" +
+ "fi\n" +
+ "exit 9\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake openclaw: %v", err)
+ }
+ return bin
+}
+
+// TestOpenclawActiveConfigPathIgnoresAPathShapedWarning is the regression for the
+// second review finding on #6275, and the reason `config file` is no longer the
+// primary source of the config path.
+//
+// The reproduction from that review: a CLI whose last warning line is itself an
+// existing path, followed by a pause longer than any fixed grace, followed by the
+// real path. Judging `config file`'s stdout by shape returned the warning path
+// after 5.57s — before the real answer existed — and expandOpenclawPath then
+// turned it into a confident absolute path, so nothing downstream caught it.
+//
+// `config validate --json` reports the path in a named field, so the warning
+// cannot be mistaken for it however long the CLI pauses. This test keeps the
+// hostile `config file` branch in the stub precisely so that a future change that
+// reinstates shape-based parsing as the primary path fails here.
+func TestOpenclawActiveConfigPathIgnoresAPathShapedWarning(t *testing.T) {
+ dir := t.TempDir()
+ realPath := filepath.Join(dir, "openclaw.json")
+ warnPath := filepath.Join(dir, "plugin-cache.json")
+ for _, p := range []string{realPath, warnPath} {
+ if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil {
+ t.Fatalf("write %s: %v", p, err)
+ }
+ }
+
+ bin := writeOpenclawConfigStub(t,
+ " printf '{\"valid\":true,\"path\":\"%s\"}\\n' '"+realPath+"'\n", 0,
+ " printf 'plugin cache written to:\\n'\n printf '%s\\n' '"+warnPath+"'\n",
+ " sleep 6\n printf '%s\\n' '"+realPath+"'\n")
+
+ start := time.Now()
+ got, exists, err := openclawActiveConfigPath(bin, 30*time.Second)
+ elapsed := time.Since(start)
+ if err != nil {
+ t.Fatalf("openclawActiveConfigPath: %v", err)
+ }
+ if got != realPath {
+ t.Errorf("path = %q, want %q — a path-shaped warning line was accepted as the answer",
+ got, realPath)
+ }
+ if !exists {
+ t.Error("exists = false for a file that is on disk")
+ }
+ // The validate answer arrives immediately, so this must not have paid the
+ // `config file` branch's 6s pause at all.
+ if elapsed > 5*time.Second {
+ t.Errorf("took %v — the JSON answer was not preferred", elapsed)
+ }
+}
+
+// TestOpenclawActiveConfigPathFallsBackToConfigFile keeps the fallback honest: a
+// CLI whose `config validate --json` is unusable (too old, or a shape we do not
+// recognise) must still resolve through `config file`.
+func TestOpenclawActiveConfigPathFallsBackToConfigFile(t *testing.T) {
+ dir := t.TempDir()
+ realPath := filepath.Join(dir, "openclaw.json")
+ if err := os.WriteFile(realPath, []byte("{}\n"), 0o600); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ for _, tc := range []struct {
+ name string
+ validateOut string
+ validateExit int
+ }{
+ {"validate prints nothing", " :\n", 0},
+ {"validate prints non-JSON", " echo 'Unknown command: validate' >&2\n", 1},
+ {"validate omits the path field", " printf '{\"valid\":true}\\n'\n", 0},
+ {"validate reports a relative path", " printf '{\"valid\":false,\"path\":\"openclaw.json\"}\\n'\n", 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bin := writeOpenclawConfigStub(t, tc.validateOut, tc.validateExit,
+ " printf '%s\\n' '"+realPath+"'\n", "")
+ got, exists, err := openclawActiveConfigPath(bin, 30*time.Second)
+ if err != nil {
+ t.Fatalf("openclawActiveConfigPath: %v", err)
+ }
+ if got != realPath || !exists {
+ t.Errorf("path = %q exists = %v, want %q true", got, exists, realPath)
+ }
+ })
+ }
+}
+
+// TestOpenclawActiveConfigPathReadsThePathFromANonZeroExit pins the case that is
+// *normal* rather than exceptional, and which the first version of these tests
+// missed: `config validate --json` exits 1 both for a missing config file and for
+// an invalid one, and carries the path in its payload either way.
+//
+// A fresh install is the missing-file case, so treating a non-zero exit as "no
+// answer" would break the most common first-run path. Both payloads below are the
+// real shapes measured on OpenClaw 2026.7.1-2, with stderr empty in both.
+func TestOpenclawActiveConfigPathReadsThePathFromANonZeroExit(t *testing.T) {
+ dir := t.TempDir()
+ presentPath := filepath.Join(dir, "openclaw.json")
+ if err := os.WriteFile(presentPath, []byte("{}\n"), 0o600); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+ missingPath := filepath.Join(dir, "absent", "openclaw.json")
+
+ for _, tc := range []struct {
+ name string
+ payload string
+ want string
+ wantExists bool
+ }{
+ {
+ // {"valid":false,"path":"…","error":"file not found"}, exit 1.
+ name: "file not found",
+ payload: `{"valid":false,"path":"` + missingPath + `","error":"file not found"}`,
+ want: missingPath,
+ wantExists: false,
+ },
+ {
+ // {"valid":false,"path":"…","issues":[…]}, exit 1. The user's config is
+ // broken, which openclaw itself will report when it runs; all this
+ // resolution step owes the caller is where the file is.
+ name: "invalid config",
+ payload: `{"valid":false,"path":"` + presentPath + `","issues":[{"path":"<root>","message":"Invalid input"}]}`,
+ want: presentPath,
+ wantExists: true,
+ },
+ {
+ // The healthy case still carries plugin warnings *inside* the document
+ // rather than as text before it, which is what keeps stdout a single
+ // parseable object.
+ name: "valid with warnings in the payload",
+ payload: `{"valid":true,"path":"` + presentPath + `","warnings":[{"path":"plugins.allow","message":"plugin not found: openclaw-lark"}]}`,
+ want: presentPath,
+ wantExists: true,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ exit := 1
+ if strings.Contains(tc.payload, `"valid":true`) {
+ exit = 0
+ }
+ bin := writeOpenclawConfigStub(t,
+ " printf '%s\\n' '"+tc.payload+"'\n", exit,
+ " echo 'config file must not be consulted'\n", "")
+
+ got, exists, err := openclawActiveConfigPath(bin, 30*time.Second)
+ if err != nil {
+ t.Fatalf("openclawActiveConfigPath: %v", err)
+ }
+ if got != tc.want {
+ t.Errorf("path = %q, want %q — the exit status must not decide whether "+
+ "the payload carries an answer", got, tc.want)
+ }
+ if exists != tc.wantExists {
+ t.Errorf("exists = %v, want %v", exists, tc.wantExists)
+ }
+ })
+ }
+}
+
+// TestOpenclawActiveConfigPathFailsClosedWhenConfigFileNeverExits is the other
+// side of dropping the `config file` completeness rule: with no way to recognise
+// the answer, a CLI that prints something and then hangs must fail rather than
+// have its output guessed at.
+//
+// This is a deliberate loss of tolerance on that one command, taken because the
+// alternative was demonstrated to return a wrong path. The deadline is what makes
+// it bounded, and MULTICA_OPENCLAW_CLI_TIMEOUT (#7142) is what makes it tunable.
+func TestOpenclawActiveConfigPathFailsClosedWhenConfigFileNeverExits(t *testing.T) {
+ dir := t.TempDir()
+ realPath := filepath.Join(dir, "openclaw.json")
+ bin := writeOpenclawConfigStub(t,
+ " echo 'validate unsupported' >&2\n", 1,
+ " printf '%s\\n' '"+realPath+"'\n",
+ " sleep 300\n")
+
+ start := time.Now()
+ _, _, err := openclawActiveConfigPath(bin, 3*time.Second)
+ elapsed := time.Since(start)
+ if err == nil {
+ t.Fatal("a `config file` that never exits must fail closed, not have its " +
+ "stdout accepted on shape")
+ }
+ if elapsed > 20*time.Second {
+ t.Errorf("took %v — the deadline did not bound the call", elapsed)
+ }
+}
diff --git a/server/internal/daemon/execenv/openclaw_real_integration_test.go b/server/internal/daemon/execenv/openclaw_real_integration_test.go
new file mode 100644
index 0000000000..976944d903
--- /dev/null
+++ b/server/internal/daemon/execenv/openclaw_real_integration_test.go
@@ -0,0 +1,110 @@
+//go:build agentintegration
+
+package execenv
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+func realOpenclawBin(t *testing.T) string {
+ t.Helper()
+ if os.Getenv("MULTICA_RUN_REAL_AGENT_SMOKE") != "1" {
+ t.Skip("set MULTICA_RUN_REAL_AGENT_SMOKE=1 to allow real agent CLI access")
+ }
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+
+ bin := os.Getenv("MULTICA_REAL_OPENCLAW_BIN")
+ if bin == "" {
+ var err error
+ bin, err = exec.LookPath("openclaw")
+ if err != nil {
+ t.Skip("openclaw not on PATH; skipping real-binary smoke test")
+ }
+ }
+ return bin
+}
+
+func TestOpenclawDaemonEquivalentRealTask(t *testing.T) {
+ bin := realOpenclawBin(t)
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ prepareCtx, prepareCancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer prepareCancel()
+ started := time.Now()
+ environment, err := PrepareIsolated(prepareCtx, preparationHelperTestCommand(), PrepareParams{
+ WorkspacesRoot: t.TempDir(),
+ WorkspaceID: "00000000-0000-4000-8000-000000000001",
+ TaskID: "00000000-0000-4000-8000-000000000002",
+ AgentName: "openclaw-real-smoke",
+ Provider: "openclaw",
+ OpenclawBin: bin,
+ Task: TaskContextForEnv{
+ IssueID: "openclaw-real-smoke",
+ },
+ }, logger)
+ if err != nil {
+ t.Fatalf("prepare isolated daemon-equivalent environment: %v", err)
+ }
+ t.Logf("real isolated daemon-equivalent preparation completed in %s", time.Since(started))
+
+ agentEnv := map[string]string{
+ "OPENCLAW_CONFIG_PATH": environment.OpenclawConfigPath,
+ }
+ if environment.OpenclawIncludeRoot != "" {
+ roots := []string{environment.OpenclawIncludeRoot}
+ if existing := strings.TrimSpace(os.Getenv("OPENCLAW_INCLUDE_ROOTS")); existing != "" {
+ roots = append(roots, existing)
+ }
+ agentEnv["OPENCLAW_INCLUDE_ROOTS"] = strings.Join(roots, string(os.PathListSeparator))
+ }
+ backend, err := agent.ResolveBackend("openclaw", agent.Config{
+ ExecutablePath: bin,
+ Env: agentEnv,
+ Logger: logger,
+ TaskID: "00000000-0000-4000-8000-000000000002",
+ BuiltinRuntime: true,
+ })
+ if err != nil {
+ t.Fatalf("resolve real OpenClaw backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ session, err := backend.Execute(ctx, "Reply with exactly: MULTICA_DAEMON_REAL_OK", agent.ExecOptions{
+ Cwd: environment.WorkDir,
+ Model: "main",
+ Timeout: 2 * time.Minute,
+ })
+ if err != nil {
+ t.Fatalf("start real OpenClaw backend: %v", err)
+ }
+ messagesDone := make(chan struct{})
+ go func() {
+ defer close(messagesDone)
+ for range session.Messages {
+ }
+ }()
+ result, ok := <-session.Result
+ <-messagesDone
+ if !ok {
+ t.Fatal("real OpenClaw backend closed without a result")
+ }
+ if result.Status != "completed" {
+ t.Fatalf("real OpenClaw task status = %q, error = %q", result.Status, result.Error)
+ }
+ if strings.TrimSpace(result.Output) != "MULTICA_DAEMON_REAL_OK" {
+ t.Fatalf("real OpenClaw task output = %q", result.Output)
+ }
+ t.Logf("real daemon-equivalent task completed in %dms", result.DurationMs)
+}
diff --git a/server/pkg/agent/agent_test.go b/server/pkg/agent/agent_test.go
index 8c53ffe4ab..bce872b30f 100644
--- a/server/pkg/agent/agent_test.go
+++ b/server/pkg/agent/agent_test.go
@@ -130,7 +130,7 @@ func TestDetectVersionFailsForMissingBinary(t *testing.T) {
// disconnected. detectCLIVersion must bound the probe and return an error so
// the registration loop isolates the broken runtime and the rest still
// register. The script also leaves an orphaned child holding the stdout pipe
-// open after the parent is killed, exercising the cmd.WaitDelay path.
+// open after the parent is killed, exercising the process-tree collector path.
func TestDetectVersionTimesOutOnHang(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("relies on a /bin/sh hang script")
@@ -141,7 +141,7 @@ func TestDetectVersionTimesOutOnHang(t *testing.T) {
pidFile := filepath.Join(dir, "child.pid")
// The CLI hangs forever (`wait`) and backgrounds a child that inherits and
// holds our stdout pipe open even after the parent is killed on timeout —
- // the exact case cmd.WaitDelay must cover. The child records its PID so we
+ // the exact case RunCollect must cover. The child records its PID so we
// can reap it in Cleanup instead of leaking a 60s `sleep` into CI.
body := fmt.Sprintf("#!/bin/sh\nsleep 60 &\necho $! > %q\nwait\n", pidFile)
if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index fecf3f3498..c85ed7d2e3 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -1105,23 +1106,97 @@ func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {
ctx, cancel := context.WithTimeout(ctx, detectVersionTimeout)
defer cancel()
+ // outputOwned, not the collector in run_collect_quiet.go, and the difference
+ // is which signal means "the answer is in". A broken CLI (node/bun shim) can
+ // leave grandchildren that inherited and still hold our stdout pipe open, and
+ // os/exec's Wait blocks until those pipes reach EOF — which is why this call
+ // carries a WaitDelay backstop, and why the deadline above needs one at all.
+ //
+ // An earlier revision of this branch used the collector here, so that Wait
+ // returned on the *direct child's* exit whatever a descendant was holding.
+ // That is wrong on this path: a wrapper may exit successfully while the real
+ // CLI, its descendant, still owes us the version. Review measured it — the
+ // wrapper exits 0, its child prints the version 500ms later, and treating
+ // leader exit as completion killed the child and returned an empty version
+ // with a nil error, where outputOwned returns the version. Pipe EOF is the
+ // only signal that means "no more output is coming"; leader exit does not.
+ //
+ // What this branch still fixes here is the *reporting*: a lingering
+ // descendant makes Wait hit WaitDelay and report exec.ErrWaitDelay even
+ // though the version arrived, and a failed --version probe skips runtime
+ // registration entirely (#6084 reverted a WaitDelay backstop over exactly
+ // that). So the error is dropped when — and only when — the answer itself is
+ // present. See salvageProbeAnswer.
+ //
+ // Built through runtimeCmd.exec so a custom runtime's fixed_args prefix is
+ // still applied (MUL-6260).
cmd := runtimeCmd.exec(ctx, "--version")
hideAgentWindow(cmd)
- // exec.CommandContext only kills the direct child on timeout. A broken CLI
- // (node/bun shim) can leave grandchildren that inherited and still hold our
- // stdout pipe open, and cmd.Output() blocks in Wait() until that pipe
- // closes — defeating the timeout above. WaitDelay forces the pipes shut and
- // reaps shortly after the context fires so this call always returns.
cmd.WaitDelay = 2 * time.Second
data, err := outputOwned(cmd, runtimeCmd.logger)
+ version, recognised := extractVersionLine(string(data))
if err != nil {
+ // recognised, not `version != ""`. The two differ exactly where it
+ // matters: extractVersionLine falls back to the trimmed raw output when
+ // no line carries a semver token, so non-empty means "the CLI printed
+ // something", which on this path may be a banner its wrapper emitted
+ // before the real version existed. Review measured that — a stub
+ // printing "initializing plugins", exiting 0, with the version arriving
+ // after WaitDelay — registering `initializing plugins` as the version
+ // with a nil error. A salvage decision needs the stronger question, so
+ // it asks whether a version was actually recognised.
+ //
+ // The fallback still stands on the success path: a CLI that exits 0 with
+ // an unusual version format is reporting its version, and dropping that
+ // to empty would be a regression (#2516). It is only unusable as
+ // evidence that a *bounded, incomplete* read already contains the
+ // answer.
+ if salvaged := salvageProbeAnswer(runtimeCmd, "--version", recognised, err); salvaged {
+ return version, nil
+ }
// One provider-agnostic boundary for probes: DetectVersion routes every
// provider through here, so an ENOEXEC diagnosis added at this point
// reaches the reason the daemon reports for a skipped runtime
// (MUL-6164).
return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))
}
- return extractVersionLine(string(data)), nil
+ return version, nil
+}
+
+// salvageProbeAnswer decides whether a one-shot probe that produced its answer
+// may ignore the error os/exec reported, and logs the decision.
+//
+// It exists for one shape: the CLI printed what we asked for, and then something
+// about its *lifecycle* failed — a descendant held the output pipes past
+// cmd.WaitDelay (exec.ErrWaitDelay), so Wait reports failure over an answer that
+// is already in the buffer. OpenClaw does this on every invocation: it forks an
+// `openclaw-config` helper that inherits stdout. #6084 measured that shape,
+// tried a WaitDelay backstop, and reverted it on review precisely because the
+// call then fails; MUL-5467 is the follow-up.
+//
+// Deliberately narrow, because "we have output" must never be confused with "we
+// have the answer":
+//
+// - answered is the caller's own *recognition* of the answer, not a length
+// check and not a parse that falls back to accepting anything. A version is
+// salvaged only if extractVersionLine matched a version-shaped line — its
+// trimmed-raw fallback does not qualify, since a wrapper's banner satisfies
+// it — and a catalog only if it parsed.
+// - Only ErrWaitDelay qualifies. A non-zero exit still fails: a CLI that
+// printed something and then exited 1 is reporting a problem, and its stderr
+// is the diagnosis. Cancellation and deadlines still fail too — reaching the
+// deadline means the CLI never finished, and this is not the layer that
+// decides a timeout was acceptable.
+func salvageProbeAnswer(runtimeCmd Command, probe string, answered bool, err error) bool {
+ if !answered || !errors.Is(err, exec.ErrWaitDelay) {
+ return false
+ }
+ if runtimeCmd.logger != nil {
+ runtimeCmd.logger.Warn("agent: CLI answered but left its output pipes open; "+
+ "using the answer and reaping the tree",
+ "command", runtimeCmd.String(), "probe", probe, "err", err)
+ }
+ return true
}
// extractVersionLine pulls the version line out of a `<cli> --version` capture,
@@ -1135,17 +1210,24 @@ func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {
// or "codex-cli 0.118.0" survive unchanged because the whole matching line is
// returned. If no line carries a semver token, fall back to the trimmed raw
// output so unusual version formats aren't silently dropped to empty.
-func extractVersionLine(raw string) string {
+//
+// The second return reports whether that scan actually matched, i.e. whether the
+// first return is a recognised version or only the fallback. It exists because
+// the fallback accepts *any* non-empty text, which is fine when the CLI exited
+// cleanly (it said what it says) and unusable as evidence when a caller has to
+// decide whether an incomplete read already holds the answer — see
+// salvageProbeAnswer.
+func extractVersionLine(raw string) (string, bool) {
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
if versionRe.MatchString(line) {
- return line
+ return line, true
}
}
- return strings.TrimSpace(raw)
+ return strings.TrimSpace(raw), false
}
// logWriter adapts a *slog.Logger to an io.Writer for capturing stderr.
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index d5526f9544..c72c53b834 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -2073,7 +2073,7 @@ func detectCodexVersionForDiagnostics(ctx context.Context, runtimeCmd Command, e
}
return "unknown"
}
- version := extractVersionLine(string(data))
+ version, _ := extractVersionLine(string(data))
if strings.TrimSpace(version) == "" {
return "unknown"
}
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 578c801235..16abea8946 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -2578,6 +2578,17 @@ func discoverOpenclawAgents(ctx context.Context, runtimeCmd Command) ([]Model, e
// Try JSON modes first. Different openclaw builds expose the
// flag under different names; trying a couple is cheap.
+ //
+ // outputOwned, and this loop already has the salvage built in: a lingering
+ // `openclaw-config` helper makes Wait report exec.ErrWaitDelay with the
+ // catalog in the buffer, and `err != nil && len(out) == 0` lets a populated
+ // buffer through to the parse. The parse is the real gate — a truncated list
+ // does not unmarshal, so a short catalog cannot be mistaken for the real one.
+ //
+ // Not the collector in run_collect_quiet.go: it returns on the direct child's
+ // exit, and a wrapper that exits before the real CLI has printed would have
+ // its catalog killed mid-write. Pipe EOF is the signal that no more output is
+ // coming. See detectCLIVersion.
for _, jsonArgs := range [][]string{
{"agents", "list", "--json"},
{"agents", "list", "--output", "json"},
diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.go
index 5075c2cbda..7f6ad8d8e7 100644
--- a/server/pkg/agent/openclaw.go
+++ b/server/pkg/agent/openclaw.go
@@ -288,15 +288,46 @@ func customArgsContains(args []string, flag string) bool {
// comment, so the message intentionally names the detected version
// and the upgrade command.
func checkOpenclawVersion(ctx context.Context, runtimeCmd Command) error {
+ // This runs synchronously before Execute creates the provider session, so a
+ // pipe-holding descendant here would otherwise leave a task marked running
+ // with no backend and no inactivity watchdog to stop it. ctx is the task's
+ // and can be hours long, so the probe carries the same bound every other
+ // provider's version probe gets.
+ ctx, cancel := context.WithTimeout(ctx, detectVersionTimeout)
+ defer cancel()
+
+ // combinedOutputOwned, for the reason recorded on detectCLIVersion: pipe EOF
+ // is the signal that no more output is coming, and the direct child's exit is
+ // not. openclaw is npm-installed, so on Windows the direct child is a shim and
+ // the real CLI is already a descendant.
+ //
+ // Both streams are parsed, and extractVersionLine is deliberately bypassed.
+ // CombinedOutput rather than separate buffers because a build that prints its
+ // banner on stderr must still pass the gate, and one shared writer is what
+ // makes os/exec give the two streams a single pipe and therefore one
+ // interleaving. parseOpenclawVersion already scans the whole text with
+ // openclaw's own version pattern, whereas picking "the first line containing a
+ // semver" first would let unrelated stderr noise answer for it — a node
+ // deprecation warning carries one.
cmd := runtimeCmd.exec(ctx, "--version")
hideAgentWindow(cmd)
- out, err := combinedOutputOwned(cmd, runtimeCmd.logger)
+ raw, err := combinedOutputOwned(cmd, runtimeCmd.logger)
+ out := string(raw)
+ detected, parsed := parseOpenclawVersion(out)
if err != nil {
- return fmt.Errorf("openclaw --version failed: %w", err)
+ // The gate may proceed on a version that arrived before a lingering
+ // `openclaw-config` helper held the pipes past WaitDelay — failing here
+ // would fail the task over an answer we have. Anything else (non-zero
+ // exit, deadline) still fails; see salvageProbeAnswer.
+ if !salvageProbeAnswer(runtimeCmd, "--version", parsed, err) {
+ // ExplainExecError by hand: detectCLIVersion applies it on the daemon's
+ // probe path, and this is the other gate that has to name an ENOEXEC
+ // shim rather than report an opaque exec failure (MUL-6164).
+ return fmt.Errorf("openclaw --version failed: %w", ExplainExecError(err))
+ }
}
- detected, ok := parseOpenclawVersion(string(out))
- if !ok {
- return fmt.Errorf("could not parse openclaw version from output: %q", strings.TrimSpace(string(out)))
+ if !parsed {
+ return fmt.Errorf("could not parse openclaw version from output: %q", strings.TrimSpace(out))
}
if compareOpenclawVersion(detected, minOpenclawVersion) < 0 {
return fmt.Errorf("openclaw %s is below the minimum supported version %s. Run `openclaw update` to upgrade and try again.", detected, minOpenclawVersion)
diff --git a/server/pkg/agent/run_collect.go b/server/pkg/agent/run_collect.go
new file mode 100644
index 0000000000..f2519c7ee0
--- /dev/null
+++ b/server/pkg/agent/run_collect.go
@@ -0,0 +1,501 @@
+package agent
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// collectReapWindow bounds how long finish() keeps re-signalling the process
+// tree, and collectReapStep is the interval between passes.
+//
+// One pass is not enough. A descendant whose fork completes between the kill's
+// enumeration of the group and the signal's delivery never receives it, and only
+// a later pass reaches it — measured 3 misses in 10 runs of the forking stub in
+// run_collect_test.go, each leaving a `sleep 300` reparented to init. The window
+// only has to cover that fork, so it is deliberately short: retrying for longer
+// would widen the pid-reuse window documented on reapProcessTree, since the group
+// id is the pid Wait has already reaped.
+const (
+ collectReapWindow = 100 * time.Millisecond
+ collectReapStep = 10 * time.Millisecond
+)
+
+// collectSettleGrace bounds the one cleanup wait on the answer path: after the
+// tree has been signalled, how long finish() waits for the reader goroutines to
+// see EOF before handing the caller what arrived.
+//
+// Short on purpose, and by the time it runs the caller has already decided that
+// reading is over — either the answer satisfied its completeness rule, or
+// collectDrainGrace expired waiting for one. What this cap cuts short is a
+// descendant that inherited the pipe and holds it open, whose trailing output is
+// not the answer. EOF short-circuits the wait, so the normal case pays nothing.
+const collectSettleGrace = 400 * time.Millisecond
+
+// collectDrainGrace bounds the wait for pipe EOF *after* the direct child has
+// exited, before the tree is reaped.
+//
+// This exists because leader exit is not the end of output, and treating it as
+// one is a data-loss bug rather than a slow path. A wrapper can exit
+// successfully while the real CLI — its descendant, which inherited stdout — has
+// not printed yet; npm and PowerShell shims make that the normal shape on
+// Windows. Review measured the consequence on an earlier revision of this
+// branch: the wrapper exits 0, its child prints the version 500ms later, and
+// reaping on leader exit returned an empty answer with a nil error, where
+// os/exec's own EOF wait returns the version.
+//
+// So EOF is the signal, and this is its bound. 2s matches probeWaitDelay, which
+// is the equivalent bound os/exec applies for the same reason on the
+// launch.go helpers — a descendant that never closes the pipe must not hold the
+// call forever.
+//
+// A caller's completeness rule short-circuits it: once the answer is in the
+// buffer there is nothing left to wait for, so the normal case — a CLI that
+// prints its answer and exits, with or without a lingering helper — pays
+// nothing.
+const collectDrainGrace = 2 * time.Second
+
+// collectStdoutLimit caps the answer this package will accumulate, and
+// collectStderrTail caps the diagnostic sample kept from stderr.
+//
+// Both streams were unbounded in an earlier revision, and review measured the
+// cost: a CLI writing continuously for the probe window retained 13,107,400
+// bytes of stderr where launch.go's outputOwned keeps the last
+// probeStderrSampleBytes (32 KiB). A broken local CLI in a log loop could
+// exhaust daemon memory before any deadline helped.
+//
+// The two limits are deliberately different in kind, because the streams are:
+//
+// - stderr is a diagnostic sample, so the *tail* is what matters — a CLI's
+// actual failure line is at the end. Keeping the last 32 KiB matches
+// outputOwned exactly, so moving a call site between the two mechanisms
+// cannot change what a failed probe reports.
+// - stdout is the answer, and silently dropping part of an answer is how a
+// truncated catalog becomes a "successful" empty one. So it is capped and
+// the overflow is reported as an error instead: a one-shot response that
+// exceeds this is a malfunction, not a large answer. Where that cap falls is
+// derived from the largest answer these call sites ask for; see
+// collectStdoutLimit below.
+const collectStderrTail = probeStderrSampleBytes
+
+// A var, not a const, so a test can shrink it rather than generating megabytes to
+// reach it — the same reason detectVersionTimeout is one. Production never
+// reassigns it.
+//
+// 8 MiB is derived rather than picked, because where this falls is a product
+// compatibility boundary and not only a memory bound: a legal config past the cap
+// stops a task from starting. The derivation, in the order it constrains the
+// value:
+//
+// - What is actually asked for. Measured on OpenClaw 2026.7.1-2:
+// `config validate --json` answers in 715 bytes and `config file` in 2663.
+// The largest answer any call site asks for is the fully resolved config from
+// `config get --json`, whose size scales with the user's agents and MCP
+// servers.
+// - There is no upstream ceiling on either, so the worst case is constructed:
+// 1000 agents and 250 MCP servers, with the fields OpenClaw's resolved config
+// carries, serialises to 547,291 bytes. Real deployments carry single-digit
+// agent counts, so that is already orders of magnitude past the field. This
+// bound leaves 15x on top of *it*, which is what
+// TestCollectStdoutLimitHasHeadroomOverTheLargestAnswer asserts — the
+// construction lives in the test so the derivation cannot drift from the
+// value silently.
+// - It matches what the daemon already holds for a comparable per-task payload
+// it reads whole into memory (internal/daemon's maxLocalSkillBundleSize is the
+// same 8 MiB), so the two limits do not have to be reasoned about separately.
+// Named rather than imported: pkg/agent is the lower layer.
+//
+// A cap of some size is unavoidable rather than a design choice: every caller
+// parses the answer as one document, so an answer that cannot be held in memory
+// cannot be used either. What the derivation buys is that the boundary sits far
+// outside any answer a real host produces, and TestCollectedStdoutBoundaryIsExact
+// pins exactly where it is — at the limit the answer is returned whole, one byte
+// past it fails closed with errCollectStdoutTooLarge instead of being silently
+// shortened.
+var collectStdoutLimit = 8 << 20
+
+// outputBuffer accumulates one stream and records when the last write landed.
+//
+// buf and lastWrite are updated inside the same critical section on purpose. If
+// the timestamp were published after releasing the lock, a reader could observe
+// new bytes together with a stale timestamp and conclude the stream had gone
+// quiet at the very moment it was producing — which for RunCollectQuiet means
+// truncating an answer mid-write.
+//
+// max bounds retention. keepTail selects which end survives: a tail buffer drops
+// from the front and keeps reading (stderr, a sample), while a head-capped
+// buffer stops accumulating and records the overflow so the caller can fail
+// rather than return a silently shortened answer (stdout).
+type outputBuffer struct {
+ mu sync.Mutex
+ buf []byte
+ lastWrite time.Time
+ max int
+ keepTail bool
+ overflow bool
+}
+
+// absorb drains r into the buffer until EOF or the file is closed. Read errors
+// other than those are reported; a truncated stream is surfaced to the caller
+// as whatever arrived, matching the previous cmd.Output() behaviour.
+//
+// Reading continues past max in both modes. Stopping would leave the child
+// blocked in write() with a full pipe, which for a head-capped stream converts
+// "answer too large" into a hang.
+func (o *outputBuffer) absorb(r io.Reader) error {
+ chunk := make([]byte, 32*1024)
+ for {
+ n, err := r.Read(chunk)
+ if n > 0 {
+ now := time.Now()
+ o.mu.Lock()
+ o.append(chunk[:n], now)
+ o.mu.Unlock()
+ }
+ if err != nil {
+ if errors.Is(err, io.EOF) || errors.Is(err, os.ErrClosed) {
+ return nil
+ }
+ return err
+ }
+ }
+}
+
+func (o *outputBuffer) snapshot() []byte {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return append([]byte(nil), o.buf...)
+}
+
+// append records p under the caller's lock, honouring max. The timestamp is set
+// even when bytes are dropped: the stream was active, and an idle check that
+// concluded otherwise would be wrong.
+func (o *outputBuffer) append(p []byte, now time.Time) {
+ o.lastWrite = now
+ if o.max <= 0 {
+ o.buf = append(o.buf, p...)
+ return
+ }
+ if o.keepTail {
+ o.buf = append(o.buf, p...)
+ if len(o.buf) > o.max {
+ o.buf = append([]byte(nil), o.buf[len(o.buf)-o.max:]...)
+ o.overflow = true
+ }
+ return
+ }
+ room := o.max - len(o.buf)
+ if room <= 0 {
+ o.overflow = true
+ return
+ }
+ if len(p) > room {
+ p = p[:room]
+ o.overflow = true
+ }
+ o.buf = append(o.buf, p...)
+}
+
+// overflowed reports whether max caused anything to be dropped.
+func (o *outputBuffer) overflowed() bool {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return o.overflow
+}
+
+// idleFor reports how long since the last write and whether anything has been
+// written at all.
+func (o *outputBuffer) idleFor() (time.Duration, bool) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.lastWrite.IsZero() {
+ return 0, false
+ }
+ return time.Since(o.lastWrite), true
+}
+
+// collector runs a command with pipes this package owns, rather than handing
+// os/exec an io.Writer and letting it do the draining.
+//
+// That distinction is the whole point, and it is the one thing launch.go's
+// runOwned / outputOwned / combinedOutputOwned cannot do. When os/exec owns the
+// draining, Wait blocks until the output pipes reach EOF, and EOF requires every
+// write end to be closed — so a CLI that forks a helper inheriting stdout
+// (OpenClaw spawns `openclaw-config`) keeps Wait open for the helper's lifetime.
+// Cancelling the context does not help: it kills the direct child without
+// unblocking os/exec's io.Copy. Handing os/exec an *os.File instead means it
+// starts no copy goroutine at all, so Wait returns the instant the direct child
+// exits and this package decides when reading is over.
+//
+// The owned helpers bound that wait with probeWaitDelay instead, which is the
+// right trade for the probes they serve — but the bound expires into
+// exec.ErrWaitDelay, so a CLI whose answer arrived and whose helper lingered is
+// reported as a failed call. On the OpenClaw paths that is not tolerable: a
+// failed `--version` skips runtime registration, and a failed `config file`
+// fails task preparation. See RunCollectQuiet for the guarantees this buys and
+// the one it cannot make.
+//
+// The corollary, learned the hard way: because this package decides when reading
+// is over, it must decide correctly. The direct child's exit is evidence about the
+// direct child only — a wrapper that exits while its descendant still owes the
+// answer is the normal shape on Windows — so awaitOutputAfterExit waits for pipe
+// EOF, bounded, unless the caller's rule says the answer is already in.
+type collector struct {
+ cmd *exec.Cmd
+ outR, errR *os.File
+ stdout outputBuffer
+ stderr outputBuffer
+
+ readers chan struct{} // closed once both absorb loops have returned
+ waitDone chan struct{} // closed once cmd.Wait has returned
+ waitErr error // valid after waitDone is closed
+
+ finishOnce sync.Once
+}
+
+// startCollector takes a *exec.Cmd the caller has already built rather than an
+// executable path, so a launch that carries an argv prefix (Command.exec, which
+// applies a custom runtime's fixed_args) keeps it. Building the command here
+// would silently drop that prefix.
+//
+// The caller must not have started it, and must leave Stdout/Stderr unset: this
+// package installs its own *os.File pipes, which is the whole reason Wait cannot
+// be held hostage by a descendant.
+//
+// No ctx parameter: the collector's lifetime is bounded by the callers below,
+// which select on ctx themselves. Taking one here would suggest this function
+// enforces it.
+func startCollector(cmd *exec.Cmd, env []string) (*collector, error) {
+ if env != nil {
+ cmd.Env = env
+ }
+ hideAgentWindow(cmd)
+ configureProcessGroup(cmd)
+
+ outR, outW, err := os.Pipe()
+ if err != nil {
+ return nil, fmt.Errorf("collect stdout pipe: %w", err)
+ }
+ errR, errW, err := os.Pipe()
+ if err != nil {
+ outR.Close()
+ outW.Close()
+ return nil, fmt.Errorf("collect stderr pipe: %w", err)
+ }
+
+ cmd.Stdout = outW
+ cmd.Stderr = errW
+
+ // startOwnedProcessTree rather than cmd.Start: on Windows it creates the
+ // child suspended and assigns it to a Job Object before it runs a single
+ // instruction, so a .cmd shim cannot spawn the real CLI outside the
+ // ownership boundary. On Unix configureProcessGroup above already did the
+ // equivalent and this is a plain Start. Either way the tree — not just the
+ // direct child — is what finish() gets to reap.
+ if startErr := startOwnedProcessTree(cmd, slog.Default()); startErr != nil {
+ releaseProcessGroup(cmd)
+ outR.Close()
+ outW.Close()
+ errR.Close()
+ errW.Close()
+ return nil, startErr
+ }
+
+ // Drop the parent's write ends immediately: otherwise EOF can never arrive
+ // no matter how thoroughly the child tree is reaped.
+ outW.Close()
+ errW.Close()
+
+ c := &collector{
+ cmd: cmd,
+ outR: outR,
+ errR: errR,
+ readers: make(chan struct{}),
+ waitDone: make(chan struct{}),
+ }
+ // The answer is capped and reports overflow; the diagnostic keeps its tail.
+ // See collectStdoutLimit.
+ c.stdout.max = collectStdoutLimit
+ c.stderr.max = collectStderrTail
+ c.stderr.keepTail = true
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() { defer wg.Done(); _ = c.stdout.absorb(outR) }()
+ go func() { defer wg.Done(); _ = c.stderr.absorb(errR) }()
+ go func() { wg.Wait(); close(c.readers) }()
+ go func() { c.waitErr = cmd.Wait(); close(c.waitDone) }()
+
+ return c, nil
+}
+
+// finish reaps the process tree and leaves the buffers in the most complete
+// state it can reach within collectSettleGrace, so a caller may snapshot them
+// straight afterwards.
+//
+// It deliberately reports nothing. Cleanup that does not converge means the OS
+// refused to kill something; that is worth a log line, but it must not decide
+// whether the caller gets the answer. A version probe whose output arrived and
+// whose helper the kernel would not kill is exactly the case #6084's cmd.WaitDelay
+// got wrong — it failed a probe that had succeeded, and a failed version probe
+// skips runtime registration entirely.
+//
+// Safe to call more than once and from any of the caller's exit paths.
+func (c *collector) finish() {
+ c.finishOnce.Do(func() {
+ // Reap whatever the CLI forked and left in the leader's group, on the
+ // success path too: a successful `openclaw --version` still leaves its
+ // helper behind, which is how orphans accumulate on a host that probes
+ // on a timer. A helper that called setsid is out of reach here — see
+ // guarantee 2 on RunCollectQuiet — but this is also what releases the last
+ // write end so the readers below can see EOF, which does not depend on
+ // the kill landing.
+ //
+ // Retried across collectReapWindow because a single pass loses a
+ // descendant that was mid-fork when the signal went out; see there.
+ reapKill(c.cmd)
+ treeGone := waitProcessGroupGone(c.cmd, collectReapStep)
+ for reapDeadline := time.Now().Add(collectReapWindow); !treeGone && time.Now().Before(reapDeadline); {
+ reapKill(c.cmd)
+ treeGone = waitProcessGroupGone(c.cmd, collectReapStep)
+ }
+
+ // Because this package owns the pipes, Wait is not being held open by a
+ // descendant: it returns as soon as the direct child is gone, which the
+ // kill above has just ensured.
+ settleDeadline := time.Now().Add(collectSettleGrace)
+ waitReturned := waitUntil(c.waitDone, settleDeadline)
+ drained := waitUntil(c.readers, settleDeadline)
+
+ // Stop reading either way. Nothing is waited on here: on Windows an
+ // anonymous pipe is not pollable, so closing the read end does not evict
+ // a blocked Read and waiting for the absorb loop would park this call for
+ // as long as the surviving descendant felt like living. The loops are
+ // harmless — snapshot takes the buffer's mutex, so one still appending
+ // cannot race a caller reading it — and they end when the descendant
+ // finally does.
+ c.outR.Close()
+ c.errR.Close()
+ // Only now: on Windows closing the job handle is what kills anything
+ // still inside it, so it must not run while the tree could still be
+ // serving output.
+ releaseProcessGroup(c.cmd)
+
+ if !treeGone || !drained || !waitReturned {
+ slog.Default().Warn("agent: collect cleanup did not converge",
+ "command", c.cmd.Path,
+ "tree_gone", treeGone,
+ "output_drained", drained,
+ "wait_returned", waitReturned,
+ "window", collectReapWindow,
+ "settle_grace", collectSettleGrace)
+ }
+ })
+}
+
+// reapKill is the process-tree kill, indirected so a test can make one pass miss
+// and prove the retry in finish() is what recovers. Production never reassigns it.
+var reapKill = reapProcessTree
+
+func waitUntil(done <-chan struct{}, deadline time.Time) bool {
+ select {
+ case <-done:
+ return true
+ default:
+ }
+ remaining := time.Until(deadline)
+ if remaining <= 0 {
+ return false
+ }
+ timer := time.NewTimer(remaining)
+ defer timer.Stop()
+ select {
+ case <-done:
+ return true
+ case <-timer.C:
+ return false
+ }
+}
+
+// exitErr reports the command's exit error without blocking, and whether the
+// command has been reaped at all yet.
+func (c *collector) exitErr() (error, bool) {
+ select {
+ case <-c.waitDone:
+ return c.waitErr, true
+ default:
+ return nil, false
+ }
+}
+
+// awaitOutputAfterExit waits, after the direct child has exited, for the output
+// this call is still owed.
+//
+// The distinction it enforces is the one an earlier revision of this branch got
+// wrong: the leader exiting means *the leader* is done, not that output is done.
+// A wrapper can exit 0 while the real CLI, which inherited its stdout, has not
+// printed yet. Only pipe EOF means every write end is closed and no more output
+// is coming, so that is what this waits for — bounded by collectDrainGrace, since
+// a descendant that never closes the pipe must not hold the call forever.
+//
+// complete short-circuits the wait: once the answer is in the buffer there is
+// nothing left to owe, so a CLI that prints and exits pays nothing here even when
+// it leaves a helper on the pipe. With a nil rule there is no way to recognise the
+// answer, so EOF or the bound are the only stopping conditions.
+//
+// Note it does *not* additionally require the buffer to have gone idle. Idleness
+// is a proxy for "the writer stopped", and the leader's exit is direct evidence
+// of that; demanding both would charge every well-behaved call an idle grace it
+// has already earned.
+func (c *collector) awaitOutputAfterExit(ctx context.Context, complete OutputComplete) {
+ if complete != nil && complete(c.stdout.snapshot()) {
+ return
+ }
+ deadline := time.Now().Add(collectDrainGrace)
+ ticker := time.NewTicker(quietPoll)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-c.readers:
+ return
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if complete != nil && complete(c.stdout.snapshot()) {
+ return
+ }
+ if time.Now().After(deadline) {
+ return
+ }
+ }
+ }
+}
+
+// reapProcessTree SIGKILLs the process group led by cmd's child, so helpers the
+// child forked die with it. Safe to call after the child has already exited:
+// configureProcessGroup makes the child the group leader, so its pid doubles as
+// the group id and the group outlives the leader for as long as any member runs.
+// An empty group yields ESRCH, which signalProcessGroup absorbs.
+//
+// The group kill is issued just after Wait has reaped the leader, so in
+// principle the leader's pid is already free for reuse. Sequential pid
+// allocation makes reuse inside that window (microseconds, and only after
+// wrapping the whole pid space) not a practical concern, and it is the same
+// window the other backends' cancellation paths already live with.
+//
+// On Windows signalProcessGroup terminates the Job Object that
+// startOwnedProcessTree assigned the child to, which reaches the same
+// descendants; see proc_windows.go.
+func reapProcessTree(cmd *exec.Cmd) {
+ if cmd == nil || cmd.Process == nil {
+ return
+ }
+ signalProcessGroup(cmd, syscall.SIGKILL)
+}
diff --git a/server/pkg/agent/run_collect_lifecycle_test.go b/server/pkg/agent/run_collect_lifecycle_test.go
new file mode 100644
index 0000000000..f6ceadb1ad
--- /dev/null
+++ b/server/pkg/agent/run_collect_lifecycle_test.go
@@ -0,0 +1,428 @@
+//go:build !windows
+
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Regressions for the second review round on #6275. All three are cases where an
+// earlier revision of this branch was *worse* than the launch.go helpers it
+// replaced, which is the bar any replacement has to clear.
+
+// writeWrapperExitingBeforeChild writes a CLI whose direct child exits 0
+// immediately while a backgrounded descendant, holding the inherited stdout,
+// prints the answer `delay` later.
+//
+// This is not a contrived shape. An npm-installed CLI on Windows is reached
+// through a shim, a PowerShell launcher spawns a native child, and either can
+// return before the process that owes us the answer has written it.
+func writeWrapperExitingBeforeChild(t *testing.T, delay, answer string) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "fake-cli")
+ body := "#!/bin/sh\n" +
+ "( sleep " + delay + "; printf '%s\\n' '" + answer + "' ) &\n" +
+ "exit 0\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+ return bin
+}
+
+// TestDetectCLIVersionWaitsForAWrapperDescendant pins the baseline comparison the
+// review asked for: whatever mechanism detectCLIVersion uses must not do worse
+// than launch.go's outputOwned on the same stub.
+//
+// The failure it guards against was measured on an earlier revision: treating the
+// direct child's exit as "the answer is in" returned an empty version with a *nil
+// error* in 0.41s, while outputOwned returned the version in 0.68s. Empty-and-nil
+// is the worst possible shape here — DetectVersion routes all 23 providers through
+// this function, and a caller cannot tell that answer from a CLI that legitimately
+// prints nothing.
+func TestDetectCLIVersionWaitsForAWrapperDescendant(t *testing.T) {
+ bin := writeWrapperExitingBeforeChild(t, "0.5", "fake-cli 1.2.3")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ got, err := detectCLIVersion(ctx, Command{Path: bin, logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("detectCLIVersion: %v", err)
+ }
+ if !strings.Contains(got, "1.2.3") {
+ t.Fatalf("version = %q, want the descendant's output — leader exit is not "+
+ "the end of output, only pipe EOF is", got)
+ }
+
+ // The baseline, on the identical stub, so this test fails if the mechanism
+ // ever regresses below it rather than merely changing.
+ cmd := Command{Path: bin}.exec(ctx)
+ hideAgentWindow(cmd)
+ out, oerr := outputOwned(cmd, slog.Default())
+ if oerr != nil {
+ t.Fatalf("outputOwned baseline: %v", oerr)
+ }
+ baseline, _ := extractVersionLine(string(out))
+ if !strings.Contains(baseline, "1.2.3") {
+ t.Fatalf("baseline outputOwned = %q, want the version — the stub is wrong, "+
+ "not the code under test", out)
+ }
+}
+
+// TestDetectCLIVersionDoesNotSalvageABannerAsTheVersion pins the third-round
+// review finding: the ErrWaitDelay salvage was gated on `version != ""`, and
+// extractVersionLine's trimmed-raw fallback makes any non-empty text satisfy
+// that — including a line the wrapper printed before the real version existed.
+//
+// Measured on the reviewed head with this stub: detectCLIVersion returned
+// version="initializing plugins" with a nil error in 2.31s, and logged "CLI
+// answered but left its output pipes open" — the opposite of what happened. The
+// banner would then be persisted as the runtime's version for every one of the 23
+// providers, since DetectVersion routes them all through here.
+//
+// The contract: when the bound expires and no *recognised* version arrived, the
+// original error stands. There is no answer to salvage.
+func TestDetectCLIVersionDoesNotSalvageABannerAsTheVersion(t *testing.T) {
+ // Banner on stdout, leader exits 0, and the real version arrives from a
+ // descendant holding the pipe well past the 2s WaitDelay this probe sets.
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "fake-cli")
+ body := "#!/bin/sh\n" +
+ "printf 'initializing plugins\\n'\n" +
+ "( sleep 5; printf 'fake-cli 1.2.3\\n' ) &\n" +
+ "exit 0\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ got, err := detectCLIVersion(ctx, Command{Path: bin, logger: slog.Default()})
+ if err == nil {
+ t.Fatalf("detectCLIVersion = %q with a nil error; a banner is not the "+
+ "answer, so the ErrWaitDelay failure must stand", got)
+ }
+ if got != "" {
+ t.Errorf("version = %q, want empty — a failed probe must not report a "+
+ "version the CLI never gave", got)
+ }
+ if !errors.Is(err, exec.ErrWaitDelay) {
+ t.Errorf("err = %v, want it to wrap exec.ErrWaitDelay (the bound that "+
+ "actually expired)", err)
+ }
+}
+
+// TestRunCollectQuietWaitsForAWrapperDescendant is the same contract on the
+// collector, which is the one mechanism in this package that can return before
+// pipe EOF.
+//
+// It may do so only when the caller's completeness rule says the answer is in.
+// With a rule that is not yet satisfied at leader exit, it has to keep waiting —
+// bounded by collectDrainGrace — or it kills the process that owes the answer.
+func TestRunCollectQuietWaitsForAWrapperDescendant(t *testing.T) {
+ bin := writeWrapperExitingBeforeChild(t, "0.5", `{"ok":true}`)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, bin)
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if strings.TrimSpace(string(out)) != `{"ok":true}` {
+ t.Fatalf("stdout = %q, want the descendant's document", out)
+ }
+}
+
+// TestRunCollectQuietDoesNotWaitWhenTheAnswerIsIn is the other half: the drain
+// wait must not become a tax on every call.
+//
+// A CLI that prints a complete answer and exits, leaving a helper on the pipe —
+// which is what OpenClaw does on every invocation — has nothing left to wait for,
+// so the rule short-circuits the drain and the call returns promptly rather than
+// paying collectDrainGrace.
+func TestRunCollectQuietDoesNotWaitWhenTheAnswerIsIn(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "fake-cli")
+ body := "#!/bin/sh\n" +
+ "printf '{\"ok\":true}\\n'\n" +
+ "sleep 300 &\n" + // inherits stdout, so EOF never arrives
+ "exit 0\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ start := time.Now()
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, bin)
+ elapsed := time.Since(start)
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if strings.TrimSpace(string(out)) != `{"ok":true}` {
+ t.Fatalf("stdout = %q", out)
+ }
+ if elapsed >= collectDrainGrace {
+ t.Errorf("took %v, i.e. at least the full drain grace (%v) — a satisfied "+
+ "completeness rule must short-circuit the wait for EOF", elapsed, collectDrainGrace)
+ }
+}
+
+// TestCollectedStderrKeepsOnlyItsTail pins the memory bound the review found
+// missing. An earlier revision retained 13,107,400 bytes of stderr from a CLI
+// writing continuously, where launch.go's outputOwned keeps the last
+// probeStderrSampleBytes; a broken local CLI in a log loop could exhaust daemon
+// memory inside the probe window.
+//
+// The tail rather than the head, matching outputOwned, because a CLI's actual
+// failure line is at the end.
+func TestCollectedStderrKeepsOnlyItsTail(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "fake-cli")
+ // ~64 KiB per line, 200 lines: ~12.8 MB, i.e. 400x the bound.
+ body := "#!/bin/sh\n" +
+ "line=$(printf 'x%.0s' $(seq 1 65536))\n" +
+ "i=0\n" +
+ "while [ $i -lt 200 ]; do printf '%s\\n' \"$line\" >&2; i=$((i+1)); done\n" +
+ "printf 'LAST-STDERR-LINE\\n' >&2\n" +
+ "printf '{\"ok\":true}\\n'\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ _, stderr, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, bin)
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if len(stderr) > collectStderrTail {
+ t.Errorf("retained %d bytes of stderr, want at most %d — the bound "+
+ "outputOwned already applied", len(stderr), collectStderrTail)
+ }
+ if !strings.Contains(stderr, "LAST-STDERR-LINE") {
+ t.Error("the tail was dropped instead of the head; a failed probe's " +
+ "diagnosis is its last line")
+ }
+}
+
+// TestCollectedStdoutOverflowIsReportedNotTruncated is the stdout half of the
+// same bound, and it is deliberately not symmetric with stderr.
+//
+// stderr is a sample, so dropping its front costs nothing. stdout is the answer,
+// and handing a caller a head-truncated answer is how a partial catalog becomes a
+// confident empty one — so overflow is an error instead.
+func TestCollectedStdoutOverflowIsReportedNotTruncated(t *testing.T) {
+ prev := collectStdoutLimit
+ collectStdoutLimit = 64 << 10
+ t.Cleanup(func() { collectStdoutLimit = prev })
+
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "fake-cli")
+ body := "#!/bin/sh\n" +
+ "line=$(printf 'y%.0s' $(seq 1 65536))\n" +
+ "i=0\n" +
+ "while [ $i -lt 8 ]; do printf '%s\\n' \"$line\"; i=$((i+1)); done\n"
+ if err := os.WriteFile(bin, []byte(body), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, nil, bin)
+ if err == nil {
+ t.Fatalf("an over-limit answer must be reported, not silently shortened "+
+ "(got %d bytes and a nil error)", len(out))
+ }
+ if !errors.Is(err, errCollectStdoutTooLarge) {
+ t.Errorf("err = %v, want errCollectStdoutTooLarge", err)
+ }
+}
+
+// TestCollectedStdoutBoundaryIsExact pins where that cap falls, because it is a
+// compatibility boundary and not only a memory bound: a legal answer one byte
+// too large stops a task from starting. Off-by-one here would move the boundary
+// without anyone noticing.
+//
+// The limit is shrunk rather than fed 8 MiB, for the same reason
+// detectVersionTimeout is a var: the property under test is the comparison, not
+// the constant.
+func TestCollectedStdoutBoundaryIsExact(t *testing.T) {
+ prev := collectStdoutLimit
+ collectStdoutLimit = 8 << 10
+ t.Cleanup(func() { collectStdoutLimit = prev })
+
+ catBin, lookErr := exec.LookPath("cat")
+ if lookErr != nil {
+ t.Skipf("no cat binary to emit an exact byte count: %v", lookErr)
+ }
+
+ cases := []struct {
+ name string
+ size int
+ wantErrIs error
+ wantOutLen int
+ }{
+ {name: "exactly at the limit", size: collectStdoutLimit, wantOutLen: collectStdoutLimit},
+ {name: "one byte past the limit", size: collectStdoutLimit + 1, wantErrIs: errCollectStdoutTooLarge},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ // A file rather than a shell loop, so the byte count is exact — no
+ // trailing newline a printf would add.
+ payload := filepath.Join(dir, "payload")
+ if err := os.WriteFile(payload, bytes.Repeat([]byte("z"), tc.size), 0o600); err != nil {
+ t.Fatalf("write payload: %v", err)
+ }
+ bin := filepath.Join(dir, "fake-cli")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\n"+catBin+" "+payload+"\n"), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, nil, bin)
+ if tc.wantErrIs != nil {
+ if !errors.Is(err, tc.wantErrIs) {
+ t.Fatalf("%d bytes against a %d-byte limit: err = %v, want %v",
+ tc.size, collectStdoutLimit, err, tc.wantErrIs)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("%d bytes against a %d-byte limit must be accepted: %v",
+ tc.size, collectStdoutLimit, err)
+ }
+ if len(out) != tc.wantOutLen {
+ t.Errorf("kept %d of %d bytes, want all of them", len(out), tc.wantOutLen)
+ }
+ })
+ }
+}
+
+// TestCollectStdoutLimitHasHeadroomOverTheLargestAnswer is the derivation behind
+// collectStdoutLimit, made executable — the review found the value asserted with
+// no upstream limit, measured high-water mark, or capacity argument behind it.
+//
+// The largest answer any call site asks this collector for is the fully resolved
+// OpenClaw config (`config get --json`), whose size scales with the user's agents
+// and MCP servers. Upstream publishes no ceiling on either, so the derivation is
+// a constructed high-water mark: a host far past anything a real deployment has,
+// with the fields OpenClaw actually carries, and a stated multiple on top.
+//
+// It runs the payload through the collector rather than only comparing lengths,
+// so the assertion covers the whole path a large answer takes — chunked reads,
+// the head-capped buffer, and the completeness rule.
+func TestCollectStdoutLimitHasHeadroomOverTheLargestAnswer(t *testing.T) {
+ // The multiple on top of the constructed worst case. 8x, so a host an order
+ // of magnitude past the construction is still inside the bound.
+ const wantHeadroom = 8
+
+ payload := openclawResolvedConfigHighWaterMark(t)
+ t.Logf("constructed high-water mark: %d bytes (%d agents, %d mcp servers); "+
+ "collectStdoutLimit = %d (%.0fx)",
+ len(payload), highWaterMarkAgents, highWaterMarkMcpServers,
+ collectStdoutLimit, float64(collectStdoutLimit)/float64(len(payload)))
+
+ if collectStdoutLimit < wantHeadroom*len(payload) {
+ t.Errorf("collectStdoutLimit = %d leaves less than %dx over the largest "+
+ "answer we ask for (%d bytes); a legal config past the cap cannot start "+
+ "a task at all, so this bound has to be derived rather than picked",
+ collectStdoutLimit, wantHeadroom, len(payload))
+ }
+
+ catBin, lookErr := exec.LookPath("cat")
+ if lookErr != nil {
+ t.Skipf("no cat binary to emit the payload verbatim: %v", lookErr)
+ }
+ dir := t.TempDir()
+ payloadPath := filepath.Join(dir, "resolved-config.json")
+ if err := os.WriteFile(payloadPath, payload, 0o600); err != nil {
+ t.Fatalf("write payload: %v", err)
+ }
+ bin := filepath.Join(dir, "fake-cli")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\n"+catBin+" "+payloadPath+"\n"), 0o755); err != nil {
+ t.Fatalf("write stub: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, bin)
+ if err != nil {
+ t.Fatalf("the largest answer we ask for must come back cleanly: %v", err)
+ }
+ if !bytes.Equal(out, payload) {
+ t.Errorf("answer came back changed: %d bytes of %d", len(out), len(payload))
+ }
+}
+
+const (
+ // Deliberately past any real deployment: the largest OpenClaw configs seen in
+ // the field carry single-digit agent counts.
+ highWaterMarkAgents = 1000
+ highWaterMarkMcpServers = 250
+)
+
+// openclawResolvedConfigHighWaterMark builds a `config get --json` payload for a
+// host at the scale above, with the fields OpenClaw's resolved config actually
+// carries, so its size is a defensible worst case rather than a round number.
+func openclawResolvedConfigHighWaterMark(t *testing.T) []byte {
+ t.Helper()
+
+ agents := make([]map[string]any, 0, highWaterMarkAgents)
+ for i := range highWaterMarkAgents {
+ agents = append(agents, map[string]any{
+ "id": fmt.Sprintf("agent-with-a-descriptive-name-%04d", i),
+ "workspace": fmt.Sprintf("/Users/somebody/work/very/deeply/nested/checkout-%04d/service", i),
+ "model": map[string]any{
+ "primary": "anthropic/claude-sonnet-4-6",
+ "fallback": "openai/gpt-5.5-codex-preview",
+ },
+ "instructions": "Follow the repository guidelines, prefer small changes, and " +
+ "always run the package's tests before handing work back for review.",
+ "skills": []string{"code-review", "release-notes", "incident-triage", "migrations"},
+ "permissions": map[string]any{"edit": true, "shell": true, "network": false},
+ })
+ }
+
+ servers := make(map[string]any, highWaterMarkMcpServers)
+ for i := range highWaterMarkMcpServers {
+ servers[fmt.Sprintf("mcp-server-%04d", i)] = map[string]any{
+ "command": "/opt/homebrew/bin/node",
+ "args": []string{fmt.Sprintf("/Users/somebody/.openclaw/servers/server-%04d/dist/index.js", i), "--stdio"},
+ "env": map[string]string{
+ "SERVER_TOKEN": "__OPENCLAW_REDACTED__",
+ "SERVER_HOME": fmt.Sprintf("/Users/somebody/.openclaw/servers/server-%04d", i),
+ },
+ }
+ }
+
+ payload, err := json.Marshal(map[string]any{
+ "agents": map[string]any{"list": agents},
+ "mcp": map[string]any{"servers": servers},
+ })
+ if err != nil {
+ t.Fatalf("build high-water-mark payload: %v", err)
+ }
+ return payload
+}
diff --git a/server/pkg/agent/run_collect_quiet.go b/server/pkg/agent/run_collect_quiet.go
new file mode 100644
index 0000000000..7dd8243606
--- /dev/null
+++ b/server/pkg/agent/run_collect_quiet.go
@@ -0,0 +1,238 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os/exec"
+ "time"
+)
+
+// DefaultQuietIdleGrace is how long stdout must stay silent, on top of already
+// carrying a complete answer, before RunCollectQuiet stops waiting for a CLI to
+// exit.
+//
+// Sized for "the CLI already flushed its answer": these commands print a path or
+// a short JSON document, and the writes of one logical response land
+// back-to-back — measured at 0.012–0.033ms apart on a real host. 400ms is orders
+// of magnitude longer than that, and short enough that the calls task setup
+// makes cost about a second in the misbehaving case instead of a full
+// openclawCLITimeout each.
+//
+// What that sizing does *not* cover, and what the caller's `complete` rule has
+// to: a gap between output that is not the answer and the answer itself. On the
+// same host, a config that produces Doctor and plugin warnings put a single
+// 3285ms silence between the end of the warning block and the config path. Any
+// rule that accepts something printed before the answer therefore has 3.2s in
+// which to fire on it, and no value here can fix that — review demonstrated it
+// against a 5s grace with a warning line that was itself a path.
+//
+// So the requirement lands on the rules rather than on this constant: a rule must
+// be unsatisfiable by anything the CLI prints before its answer. The only rule in
+// this package that qualifies is JSONOutputComplete, because a document has to
+// parse as a whole and because upstream keeps incidental output off a `--json`
+// stdout entirely. Judging human-readable output by shape does not qualify, and
+// the `config file` rule that tried was removed rather than retuned — see
+// openclawOutputComplete in internal/daemon/execenv.
+//
+// It is also the window in which a *late* failure can still be observed: a CLI
+// that prints a complete answer and then exits non-zero is reported as the
+// failure it is, as long as it does so within the grace. Beyond that it is
+// indistinguishable from one that prints an answer and hangs forever, which is
+// the case this whole helper exists to survive.
+const DefaultQuietIdleGrace = 400 * time.Millisecond
+
+// quietPoll is how often RunCollectQuiet re-evaluates its exit conditions.
+const quietPoll = 50 * time.Millisecond
+
+// OutputComplete reports whether the bytes captured so far are a *finished*
+// answer for the command that produced them.
+//
+// This is the caller's judgement, not something the runner can infer: only the
+// caller knows whether `{"agents":[{"id":"a"},` is a truncated document or a
+// legitimate one. Without it, "we have some output" gets mistaken for "we have
+// the output" and a response interrupted mid-flight is reported as success.
+type OutputComplete func(stdout []byte) bool
+
+// JSONOutputComplete is the rule for commands whose entire answer is one JSON
+// document. Empty output is never complete; a lone `null` is, since that is how
+// the CLI reports an unset key.
+//
+// Note this requires the whole buffer to parse, so a CLI that prints banner text
+// before its JSON never satisfies it. That matches how the callers parse the
+// result anyway (a whole-buffer json.Unmarshal), so such output was never usable
+// — it now fails on the deadline instead of on the parse.
+func JSONOutputComplete(stdout []byte) bool {
+ trimmed := bytes.TrimSpace(stdout)
+ return len(trimmed) > 0 && json.Valid(trimmed)
+}
+
+// RunCollectQuiet runs a one-shot CLI command and returns when the process
+// exits, or — for a CLI that will not exit — as soon as it has produced output
+// that `complete` accepts and that has then stayed idle for idleGrace.
+//
+// # Why "output is enough" beats "wait for exit"
+//
+// Measured on a host running openclaw 2026.5.27:
+//
+// openclaw --version 258ms exits cleanly
+// openclaw config file 60s correct path printed, then never exits
+// openclaw agents list 60s correct list printed, then never exits
+//
+// Waiting for exit turns two working commands into a task-fatal error, and they
+// sit on the task's critical path (Prepare -> prepareOpenclawConfig). The
+// contract of those commands is "print a value"; once the value has arrived,
+// whether the process tidies itself up is not the caller's business.
+//
+// Nor is that a quirk of the build those timings came from. Upstream has an
+// explicit opt-in for "print a one-shot answer and then exit" —
+// `requestExitAfterOneShotOutput`, flushed at the end of `runCli` after both
+// streams drain (`src/cli/one-shot-exit.ts`, checked at `v2026.7.1`). In the
+// shipped 2026.7.1 build only `models list`, `models status` and the hooks CLI
+// take it. `config file`, `config get` and `agents list` do not: their success
+// paths only print, so termination is whatever the Node event loop happens to
+// do, and `runtime.exit` appears on their failure paths alone. So a version
+// where they exit promptly is not making a promise a later one has to keep.
+//
+// # Why `complete` is required rather than "any output"
+//
+// An earlier revision returned success from the deadline branch whenever stdout
+// was non-empty. That salvaged partial answers: a CLI still streaming when the
+// deadline arrived had its truncated output reported as success (measured 9 runs
+// in 10 against a 250ms deadline). Two conditions now gate the early return, and
+// neither is sufficient alone:
+//
+// - `complete` accepts the buffer. Idle alone is not enough, because the CLI
+// may be pausing between a banner and the real answer — `openclaw config
+// file` prints Doctor warning UI first (see MUL-3136), and cutting off there
+// yields the banner instead of the path. The rule carries the whole weight of
+// that distinction: review broke a rule that judged the path by *shape* with a
+// warning line that was itself a path, so a rule has to be one the CLI's
+// pre-answer output cannot satisfy at all.
+// - The buffer has then been idle for idleGrace. Complete alone is not enough,
+// because more output may still follow and change the answer.
+//
+// Reaching the context deadline is never success. Whatever was captured is
+// returned alongside the error so a caller with a different rule can inspect it,
+// but this helper does not decide on the caller's behalf.
+//
+// A nil `complete` disables the early return entirely: the call then waits for
+// exit, bounded only by ctx. That is the right default for a command whose
+// output shape has no completeness rule.
+//
+// quiet reports that the return did not come from a clean exit, so callers can
+// log the CLI's misbehaviour without failing on it.
+//
+// Guarantees callers depend on:
+//
+// 1. Returns within roughly the caller's context deadline plus collectDrainGrace,
+// collectReapWindow and collectSettleGrace, whatever the CLI leaves behind.
+// 2. Descendants that are still in the leader's process group are signalled
+// before returning, and the signal is repeated across collectReapWindow so one
+// that was mid-fork does not escape. A descendant that left the group is out
+// of reach on Unix — OpenClaw's helper was measured with its own PGID and SID —
+// which is why guarantee 1 does not depend on the kill landing. Windows is
+// different: the Job Object owns the tree irrespective of groups.
+// 3. Output is not abandoned while something may still be writing it: after the
+// direct child exits, the call waits for pipe EOF unless `complete` says the
+// answer is in. Leader exit alone is not treated as completion.
+// 4. Retention is bounded — collectStdoutLimit for the answer (reported, not
+// silently truncated) and collectStderrTail for the diagnostic sample.
+// 5. The command's real exit status is reported, which openclawShimDiagnostic
+// depends on (it type-switches on *exec.ExitError).
+//
+// Use this only for commands whose entire output is a short one-shot response.
+// Anything that streams incrementally (agent execution) must keep its own
+// lifecycle handling, where a pause in output carries meaning.
+func RunCollectQuiet(ctx context.Context, env []string, idleGrace time.Duration, complete OutputComplete, execPath string, args ...string) (stdout []byte, stderr string, quiet bool, err error) {
+ // Command.exec, not exec.CommandContext: launch.go owns process construction so
+ // a custom runtime's fixed_args prefix cannot be dropped (GH #7046). A zero
+ // Command has no prefix, which is what a bare path argument means here.
+ return RunCollectQuietCmd(ctx, Command{Path: execPath}.exec(ctx, args...), env, idleGrace, complete)
+}
+
+// RunCollectQuietCmd is RunCollectQuiet for a caller that already holds a
+// *exec.Cmd, which is what Command.exec returns.
+func RunCollectQuietCmd(ctx context.Context, cmd *exec.Cmd, env []string, idleGrace time.Duration, complete OutputComplete) (stdout []byte, stderr string, quiet bool, err error) {
+ if idleGrace <= 0 {
+ idleGrace = DefaultQuietIdleGrace
+ }
+
+ c, startErr := startCollector(cmd, env)
+ if startErr != nil {
+ return nil, "", false, startErr
+ }
+
+ ticker := time.NewTicker(quietPoll)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-c.waitDone:
+ // The direct child is gone, which is not the same as "no more output
+ // is coming" — a wrapper may have exited while the real CLI still
+ // owes us the answer. Wait for pipe EOF, bounded, unless the answer
+ // is already in; see awaitOutputAfterExit.
+ c.awaitOutputAfterExit(ctx, complete)
+ c.finish()
+ out := c.stdout.snapshot()
+ if c.stdout.overflowed() {
+ return out, string(c.stderr.snapshot()), false, collectStdoutOverflowErr()
+ }
+ return out, string(c.stderr.snapshot()), false, c.waitErr
+
+ case <-ctx.Done():
+ c.finish()
+ out := c.stdout.snapshot()
+ // Deliberately no salvage. Reaching the deadline means we never saw
+ // output that `complete` accepted, so by the caller's own rule the
+ // buffer is unfinished. Prefer the process error when we have one:
+ // callers attribute ctx themselves and a "signal: killed" detail is
+ // worth keeping in the message.
+ if werr, reaped := c.exitErr(); reaped && werr != nil {
+ return out, string(c.stderr.snapshot()), true, werr
+ }
+ return out, string(c.stderr.snapshot()), true, ctx.Err()
+
+ case <-ticker.C:
+ if complete == nil {
+ continue
+ }
+ idle, produced := c.stdout.idleFor()
+ if !produced || idle < idleGrace {
+ continue
+ }
+ out := c.stdout.snapshot()
+ if !complete(out) {
+ continue
+ }
+ // A finished answer that has gone quiet: take it and reap the tree.
+ // `out` is the buffer `complete` accepted, deliberately not a fresh
+ // snapshot — bytes a lingering descendant appends after that verdict
+ // were never part of the answer and could only break the parse.
+ c.finish()
+ if c.stdout.overflowed() {
+ return out, string(c.stderr.snapshot()), true, collectStdoutOverflowErr()
+ }
+ return out, string(c.stderr.snapshot()), true, nil
+ }
+ }
+}
+
+// errCollectStdoutTooLarge reports that the answer exceeded collectStdoutLimit.
+//
+// Reported rather than returned quietly: these helpers run one-shot commands
+// whose response is a path or a short document, so overflow means the CLI is
+// malfunctioning, and a caller that parsed a head-truncated answer would be
+// parsing something the CLI never said. stderr is capped by keeping its tail
+// instead, because it is a diagnostic sample and not an answer — dropping its
+// front loses nothing a caller relies on.
+var errCollectStdoutTooLarge = errors.New("collected stdout exceeded its limit")
+
+// collectStdoutOverflowErr names the limit in the message while keeping
+// errCollectStdoutTooLarge as the sentinel callers match on.
+func collectStdoutOverflowErr() error {
+ return fmt.Errorf("%w (%d bytes)", errCollectStdoutTooLarge, collectStdoutLimit)
+}
diff --git a/server/pkg/agent/run_collect_quiet_test.go b/server/pkg/agent/run_collect_quiet_test.go
new file mode 100644
index 0000000000..b438ed1403
--- /dev/null
+++ b/server/pkg/agent/run_collect_quiet_test.go
@@ -0,0 +1,336 @@
+//go:build !windows
+
+package agent
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Reproduces the second OpenClaw failure mode behind MUL-5467: the CLI prints
+// the correct answer and then never exits. Measured on a host running openclaw
+// 2026.5.27:
+//
+// openclaw --version 258ms exits cleanly
+// openclaw config file 60s correct path printed, then killed by the caller
+// openclaw agents list 60s correct list printed, then killed by the caller
+//
+// Waiting for exit turned working commands into task-fatal errors, so a host
+// with that CLI build could not prepare a single task's execution environment.
+
+const quietTestJSON = `{"agents":[{"id":"main"}]}`
+
+// writePrintThenHangCLI creates a CLI that prints payload and then hangs
+// forever, optionally forking a helper that also holds the pipes.
+func writePrintThenHangCLI(t *testing.T, payload, helperPidFile string) string {
+ t.Helper()
+ dir := t.TempDir()
+ script := filepath.Join(dir, "fake-cli")
+ fork := ""
+ if helperPidFile != "" {
+ // $!, not $$ from inside a subshell: see writeForkingCLIOutput. Naming
+ // the direct child here would make the reaping assertion vacuous.
+ fork = `sleep 300 &
+echo $! > "` + helperPidFile + `"
+`
+ }
+ body := "#!/bin/sh\n" + fork + `printf '%s\n' '` + payload + `'
+# The defining behaviour: answer delivered, process refuses to exit.
+sleep 300
+`
+ if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake cli: %v", err)
+ }
+ return script
+}
+
+func writeCLI(t *testing.T, body string) string {
+ t.Helper()
+ script := filepath.Join(t.TempDir(), "fake-cli")
+ if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake cli: %v", err)
+ }
+ return script
+}
+
+// TestRunCollectQuietReturnsOnceOutputGoesIdle is the core contract: a complete
+// answer plus silence is enough, and returning must not depend on the deadline.
+func TestRunCollectQuietReturnsOnceOutputGoesIdle(t *testing.T) {
+ cli := writePrintThenHangCLI(t, quietTestJSON, "")
+
+ // A long ctx on purpose.
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ start := time.Now()
+ out, _, quiet, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, cli)
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("RunCollectQuiet returned an error: %v", err)
+ }
+ if got := strings.TrimSpace(string(out)); got != quietTestJSON {
+ t.Errorf("stdout = %q, want the printed answer", got)
+ }
+ if !quiet {
+ t.Error("quiet = false, want true — callers should be able to log the " +
+ "CLI's failure to exit without failing on it")
+ }
+ // A loose bound on purpose: it only has to sit far below the 60s ctx and the
+ // stub's 300s sleep, either of which a broken mechanism would take. Tying it
+ // to the 400ms grace would make it a CI flake, since spawning the stub costs
+ // the same order of magnitude.
+ if elapsed > 10*time.Second {
+ t.Errorf("took %v — it waited for an exit that never comes instead of "+
+ "accepting the flushed output", elapsed)
+ }
+}
+
+// TestRunCollectQuietDoesNotSalvagePartialOutputAtDeadline is the regression for
+// the review finding on #6275. An earlier revision returned success from the
+// deadline branch whenever stdout was non-empty, so a CLI still streaming when
+// the deadline arrived had its truncated output reported as success — measured
+// 9 runs in 10. The deadline is never success.
+func TestRunCollectQuietDoesNotSalvagePartialOutputAtDeadline(t *testing.T) {
+ // Emits a JSON document forever: always non-empty, never complete.
+ // 120ms between writes, not 30ms: the stub forks a `sleep` per iteration and
+ // this package also holds timing-tight tests, so a tighter loop steals CPU
+ // from them. Still far below the 250ms deadline, so the document is always
+ // caught mid-write.
+ cli := writeCLI(t, "#!/bin/sh\nprintf '{\"agents\":['\n"+
+ "while :; do printf '{\"id\":\"a\"},'; sleep 0.12; done\n")
+
+ // Four runs is decisive: the reverted implementation salvaged 9 of 10.
+ for i := 0; i < 4; i++ {
+ ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, cli)
+ cancel()
+
+ if err == nil {
+ t.Fatalf("run %d: partial output reported as success (%d bytes: %q) — "+
+ "an interrupted response must never be handed to a caller as a "+
+ "finished one", i, len(out), truncateForLog(out))
+ }
+ // The bytes are still returned so a caller with its own rule can look,
+ // but they arrive with the error attached.
+ if JSONOutputComplete(out) {
+ t.Fatalf("run %d: the stub is not supposed to be able to emit a "+
+ "complete document; test is not exercising the intended path", i)
+ }
+ }
+}
+
+// TestRunCollectQuietWaitsForTheAnswerAfterAPrompt is the second regression the
+// review asked for. Output arriving and then going quiet is NOT sufficient: the
+// CLI may be pausing between a banner and the real answer. `openclaw config file`
+// does exactly this — it prints Doctor warning UI first (MUL-3136) — and cutting
+// off there would return the banner as the answer.
+func TestRunCollectQuietWaitsForTheAnswerAfterAPrompt(t *testing.T) {
+ // Banner, a pause well past the idle grace, then the real answer, then hang.
+ cli := writeCLI(t, "#!/bin/sh\n"+
+ "echo 'warning: run openclaw doctor to inspect config'\n"+
+ "sleep 1\n"+
+ "printf '%s\\n' '"+quietTestJSON+"'\n"+
+ "sleep 300\n")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ // The rule mirrors what execenv uses for `config file`: the answer is the
+ // last non-empty line, and it has to look like an answer.
+ lastLineIsAnswer := func(out []byte) bool {
+ lines := strings.Split(strings.TrimSpace(string(out)), "\n")
+ return strings.TrimSpace(lines[len(lines)-1]) == quietTestJSON
+ }
+
+ out, _, quiet, err := RunCollectQuiet(ctx, nil, 0, lastLineIsAnswer, cli)
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if !quiet {
+ t.Error("quiet = false, want true — the stub never exits")
+ }
+ if !strings.Contains(string(out), quietTestJSON) {
+ t.Errorf("stdout = %q — returned before the real answer arrived, so the "+
+ "banner would have been mistaken for it", out)
+ }
+}
+
+// TestRunCollectQuietReportsLateNonZeroExit is the third regression the review
+// asked for. A CLI that prints a complete answer and then fails must be reported
+// as the failure it is, as long as it fails within the idle grace — which is
+// exactly what the grace is for. The stub exits at 150ms against a 400ms grace.
+func TestRunCollectQuietReportsLateNonZeroExit(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\nprintf '%s\\n' '"+quietTestJSON+"'\n"+
+ "echo 'openclaw doctor found a problem' >&2\nsleep 0.15\nexit 5\n")
+
+ out, stderr, quiet, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli)
+ if err == nil {
+ t.Fatalf("a complete answer followed by exit 5 was reported as success "+
+ "(out=%q) — the answer does not excuse the failure", truncateForLog(out))
+ }
+ if quiet {
+ t.Error("quiet = true, want false — this returned through the exit path")
+ }
+ if !strings.Contains(stderr, "openclaw doctor") {
+ t.Errorf("stderr = %q, lost the CLI's diagnostics", stderr)
+ }
+}
+
+// TestRunCollectQuietWithoutCompletenessRuleWaitsForExit pins the conservative
+// default: with no rule there is nothing to judge the output by, so the early
+// return is disabled entirely rather than guessed at.
+//
+// Synchronized on a marker the CLI writes after its answer rather than on a
+// deadline. The two assertions want opposite budgets — "returned an error" wants
+// a short one, "the captured bytes survived" wants the spawn to have finished —
+// and any single number that serves both is a flake waiting for a loaded host.
+// Waiting for the marker also makes the check stronger than a timeout could: it
+// proves the runner was still blocked at a moment when the answer was fully
+// available to it.
+func TestRunCollectQuietWithoutCompletenessRuleWaitsForExit(t *testing.T) {
+ marker := filepath.Join(t.TempDir(), "answer-delivered")
+ cli := writeCLI(t, "#!/bin/sh\n"+
+ `printf '%s\n' '`+quietTestJSON+"'\n"+
+ "touch '"+marker+"'\n"+
+ "# The defining behaviour: answer delivered, process refuses to exit.\n"+
+ "sleep 300\n")
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ type collected struct {
+ out []byte
+ err error
+ }
+ done := make(chan collected, 1)
+ go func() {
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, nil, cli)
+ done <- collected{out: out, err: err}
+ }()
+
+ waitForFile(t, marker, 30*time.Second)
+
+ // Well past the point where a rule-driven early return would have fired.
+ select {
+ case got := <-done:
+ t.Fatalf("returned while the process was still running (err=%v, out=%q) — "+
+ "without a rule the runner must not decide the answer is finished",
+ got.err, truncateForLog(got.out))
+ case <-time.After(3 * DefaultQuietIdleGrace):
+ }
+
+ cancel()
+ got := <-done
+ // Not a context sentinel: cancelling reaps the tree, and both entry points
+ // deliberately prefer the process error once they have one, because
+ // "signal: killed" is the more specific account of what happened. The
+ // invariant under test is only that success was never reported.
+ if got.err == nil {
+ t.Errorf("nil completeness rule still returned success (out=%q)", truncateForLog(got.out))
+ }
+ // The output is still handed back for a caller that wants to inspect it.
+ if !strings.Contains(string(got.out), quietTestJSON) {
+ t.Errorf("stdout = %q, want the captured bytes to survive the error", got.out)
+ }
+}
+
+// TestRunCollectQuietPrefersCleanExit pins that a well-behaved CLI is not
+// mislabelled as misbehaving: quiet must be false, which is also what proves it
+// returned through the exit path rather than the idle shortcut.
+func TestRunCollectQuietPrefersCleanExit(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\nprintf '%s\\n' '"+quietTestJSON+"'\nexit 0\n")
+
+ out, _, quiet, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli)
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if strings.TrimSpace(string(out)) != quietTestJSON {
+ t.Errorf("stdout = %q, want the printed answer", out)
+ }
+ if quiet {
+ t.Error("quiet = true for a CLI that exited cleanly — the flag must " +
+ "distinguish real misbehaviour from normal operation, and a clean " +
+ "exit must not be reported through the idle path")
+ }
+}
+
+// TestRunCollectQuietPropagatesExitFailure pins that "output is enough" never
+// becomes "everything is fine": a genuinely broken CLI must still fail, with its
+// stderr intact for openclawShimDiagnostic and the daemon log.
+func TestRunCollectQuietPropagatesExitFailure(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\necho 'run openclaw doctor' >&2\nexit 4\n")
+
+ _, stderr, _, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli)
+ if err == nil {
+ t.Fatal("expected an error for exit status 4 — a genuinely broken CLI " +
+ "must not be silently treated as success")
+ }
+ if !strings.Contains(stderr, "openclaw doctor") {
+ t.Errorf("stderr = %q, lost the CLI's diagnostics", stderr)
+ }
+}
+
+// TestRunCollectQuietReapsHelperOnIdleReturn pins that the idle shortcut still
+// cleans up: this path runs per task, so a helper left behind each time is how a
+// host accumulates orphan `openclaw-config` processes.
+func TestRunCollectQuietReapsHelperOnIdleReturn(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writePrintThenHangCLI(t, quietTestJSON, pidFile)
+
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli); err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+
+ data, readErr := os.ReadFile(pidFile)
+ if readErr != nil {
+ t.Fatalf("helper pid file unreadable: %v", readErr)
+ }
+ pid, convErr := strconv.Atoi(strings.TrimSpace(string(data)))
+ if convErr != nil {
+ t.Fatalf("bad pid %q: %v", data, convErr)
+ }
+
+ if !waitForProcessGone(pid, 5*time.Second) {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("helper pid %d survived the idle-path return — the orphan "+
+ "leak is back on this code path", pid)
+ }
+}
+
+// TestRunCollectQuietWithNoOutputHonorsContext pins that the idle shortcut cannot
+// mask a CLI that produces nothing: with no output there is nothing to judge, so
+// the deadline must still govern and the call must still fail.
+func TestRunCollectQuietWithNoOutputHonorsContext(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\nsleep 300\n")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 700*time.Millisecond)
+ defer cancel()
+
+ start := time.Now()
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, cli)
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Error("expected an error when the CLI produced no output at all")
+ }
+ if len(strings.TrimSpace(string(out))) != 0 {
+ t.Errorf("stdout = %q, want empty", out)
+ }
+ if elapsed > 5*time.Second {
+ t.Errorf("took %v — the context deadline was not honored", elapsed)
+ }
+}
+
+func truncateForLog(b []byte) string {
+ if len(b) > 80 {
+ return string(b[:80]) + "..."
+ }
+ return string(b)
+}
diff --git a/server/pkg/agent/run_collect_test.go b/server/pkg/agent/run_collect_test.go
new file mode 100644
index 0000000000..96e69b6379
--- /dev/null
+++ b/server/pkg/agent/run_collect_test.go
@@ -0,0 +1,471 @@
+//go:build !windows
+
+package agent
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// These tests reproduce the shape behind MUL-5467: invoking a CLI that forks a
+// long-lived helper which inherits stdout/stderr.
+//
+// Observed on an OpenClaw host — `openclaw --version` returns promptly but
+// leaves an `openclaw-config` helper holding the pipe's write end. With a bare
+// cmd.Output() the call never returns (os/exec waits for pipe EOF, and killing
+// the direct child on ctx cancellation does not unblock that), and the helper
+// is reparented to init. A daemon probing on a timer therefore accumulated one
+// parked goroutine and one orphan per cycle.
+
+// writeForkingCLI creates a shell script with that behaviour: print a version
+// line, fork a helper that holds the inherited stdout/stderr for far longer
+// than any test would wait, then exit 0. The helper records its own pid so the
+// test can assert it was reaped.
+func writeForkingCLI(t *testing.T, pidFile string) string {
+ return writeForkingCLIOutput(t, pidFile, "fake-cli 1.2.3")
+}
+
+func writeForkingCLIOutput(t *testing.T, pidFile, output string) string {
+ t.Helper()
+ dir := t.TempDir()
+ script := filepath.Join(dir, "fake-cli")
+ body := `#!/bin/sh
+# The helper keeps the inherited stdout/stderr open — the exact shape that
+# makes cmd.Output() wait for a process it never spawned.
+sleep 300 &
+# $!, not $$ from inside a subshell: POSIX keeps $$ at the invoking shell's pid
+# even inside ( ), so recording it would name the direct child — which cmd.Wait
+# reaps regardless of whether the tree kill works, making every assertion built
+# on this file vacuous.
+echo $! > "` + pidFile + `"
+echo "` + output + `"
+exit 0
+`
+ if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
+ t.Fatalf("write fake cli: %v", err)
+ }
+ return script
+}
+
+// TestCheckOpenclawVersionReapsPipeHoldingGrandchild covers the task-start
+// version gate, which is separate from the daemon registration probe. It must
+// use RunCollect too: Execute calls this synchronously before it returns a
+// Session, so a pipe-holding descendant here would bypass both the provider
+// timeout and the daemon's inactivity watchdog.
+func TestCheckOpenclawVersionReapsPipeHoldingGrandchild(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLIOutput(t, pidFile, "OpenClaw 2026.7.1")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := checkOpenclawVersion(ctx, Command{Path: cli}); err != nil {
+ t.Fatalf("checkOpenclawVersion: %v", err)
+ }
+
+ pid := waitForPidFile(t, pidFile)
+ if !waitForProcessGone(pid, 2*time.Second) {
+ t.Errorf("openclaw version helper pid %d still alive after version check", pid)
+ }
+}
+
+// TestCheckOpenclawVersionAcceptsStderrOnlyVersion — the gate replaced
+// combinedOutputOwned, so stderr has to stay in the parse. A build that prints
+// its banner there would otherwise fail the minimum-version check with an empty
+// output, which skips the runtime entirely.
+func TestCheckOpenclawVersionAcceptsStderrOnlyVersion(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\necho 'OpenClaw 2026.7.1' >&2\n")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := checkOpenclawVersion(ctx, Command{Path: cli}); err != nil {
+ t.Fatalf("checkOpenclawVersion with the version on stderr: %v", err)
+ }
+}
+
+// waitForPidFile waits for the forked helper to record its pid.
+func waitForPidFile(t *testing.T, pidFile string) int {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if data, err := os.ReadFile(pidFile); err == nil {
+ if pid, convErr := strconv.Atoi(strings.TrimSpace(string(data))); convErr == nil && pid > 0 {
+ return pid
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Fatalf("helper never wrote its pid to %s", pidFile)
+ return 0
+}
+
+// processAlive reports whether pid still exists. Signal 0 only performs the
+// permission/existence check.
+func processAlive(pid int) bool { return syscall.Kill(pid, 0) == nil }
+
+// waitForFile polls until path exists, so a test can synchronize on something
+// the fake CLI did rather than on how long it took to get there.
+func waitForFile(t *testing.T, path string, within time.Duration) {
+ t.Helper()
+ deadline := time.Now().Add(within)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(path); err == nil {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("fake CLI never created %s within %v", path, within)
+}
+
+// waitForProcessGone polls until pid is gone, since SIGKILL delivery and
+// reaping are asynchronous.
+func waitForProcessGone(pid int, within time.Duration) bool {
+ deadline := time.Now().Add(within)
+ for time.Now().Before(deadline) {
+ if !processAlive(pid) {
+ return true
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ return false
+}
+
+// TestRunCollectReturnsDespitePipeHoldingGrandchild pins guarantee #1: the call
+// completes even though a helper still holds stdout. With any buffer-based form —
+// cmd.Output(), or launch.go's outputOwned — this blocks until the helper's
+// `sleep 300` finishes, or until probeWaitDelay converts it into
+// exec.ErrWaitDelay.
+func TestRunCollectReturnsDespitePipeHoldingGrandchild(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLI(t, pidFile)
+
+ start := time.Now()
+ out, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli)
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("RunCollect returned an error: %v", err)
+ }
+ if !strings.Contains(string(out), "fake-cli 1.2.3") {
+ t.Errorf("stdout did not survive: %q", out)
+ }
+ // Generous bound: the point is "does not wait for the 300s helper".
+ if elapsed > 15*time.Second {
+ t.Errorf("RunCollect took %v — it waited on the helper instead of "+
+ "returning once the direct child exited", elapsed)
+ }
+}
+
+// TestRunCollectReapsForkedHelper pins guarantee #2: the helper is killed
+// before RunCollect returns, so invoking a CLI on a timer cannot accumulate
+// orphans. This is the assertion that would have caught the production leak.
+func TestRunCollectReapsForkedHelper(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLI(t, pidFile)
+
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli); err != nil {
+ t.Fatalf("RunCollect returned an error: %v", err)
+ }
+
+ pid := waitForPidFile(t, pidFile)
+ if !waitForProcessGone(pid, 5*time.Second) {
+ // Don't leave a stray `sleep 300` behind if the assertion fails.
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("forked helper (pid %d) survived RunCollect — the process "+
+ "group was not reaped and the orphan leak is back", pid)
+ }
+}
+
+// TestRunCollectSurfacesStderrAndExitStatus guards the diagnostic behaviour:
+// owning the pipes must not cost us the CLI's stderr or its exit status.
+func TestRunCollectSurfacesStderrAndExitStatus(t *testing.T) {
+ dir := t.TempDir()
+ cli := filepath.Join(dir, "failing-cli")
+ body := "#!/bin/sh\necho 'boom' >&2\nexit 7\n"
+ if err := os.WriteFile(cli, []byte(body), 0o755); err != nil {
+ t.Fatalf("write cli: %v", err)
+ }
+
+ _, stderr, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli)
+ if err == nil {
+ t.Fatal("expected an error for exit status 7")
+ }
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) {
+ t.Fatalf("err = %T (%v), want *exec.ExitError — callers such as "+
+ "openclawShimDiagnostic type-switch on it", err, err)
+ }
+ if exitErr.ExitCode() != 7 {
+ t.Errorf("exit code = %d, want 7", exitErr.ExitCode())
+ }
+ if !strings.Contains(stderr, "boom") {
+ t.Errorf("stderr = %q, lost the CLI's diagnostics", stderr)
+ }
+}
+
+// TestRunCollectRetriesTheTreeKill pins the retry, which is not decoration: a
+// single pass loses a descendant whose fork completes between the kill's
+// enumeration of the process group and the signal's delivery. Measured 3 misses
+// in 10 runs of the forking stub, each leaving a `sleep 300` reparented to init
+// and the call stalled until the settle grace expired.
+//
+// The race cannot be forced from a stub — it lives inside one syscall — so the
+// missed pass is injected here instead. Same var-for-tests pattern as
+// detectVersionTimeout and openclawExec.
+func TestRunCollectRetriesTheTreeKill(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLI(t, pidFile)
+
+ original := reapKill
+ var passes int32
+ reapKill = func(cmd *exec.Cmd) {
+ // The first pass misses exactly the way the enumeration race does: the
+ // signal is issued and reaches nothing.
+ if atomic.AddInt32(&passes, 1) > 1 {
+ original(cmd)
+ }
+ }
+ t.Cleanup(func() { reapKill = original })
+
+ out, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli)
+ if err != nil {
+ t.Fatalf("RunCollect returned an error: %v", err)
+ }
+ if !strings.Contains(string(out), "fake-cli 1.2.3") {
+ t.Errorf("stdout did not survive: %q", out)
+ }
+
+ pid := waitForPidFile(t, pidFile)
+ if !waitForProcessGone(pid, 5*time.Second) {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("helper (pid %d) survived a missed first kill — one pass is "+
+ "all the tree gets, so a descendant that was mid-fork stays an orphan", pid)
+ }
+ if got := atomic.LoadInt32(&passes); got < 2 {
+ t.Errorf("kill passes = %d, want at least 2 — the retry never ran, so "+
+ "this test passed for the wrong reason", got)
+ }
+}
+
+// TestRunCollectRespectsProcessGroupPrecondition pins the invariant the group
+// kill depends on: the child must lead its own group. If configureProcessGroup
+// ever stopped setting Setpgid, reapProcessTree would silently degrade to
+// signalling only the direct child and the orphan leak would return.
+func TestRunCollectRespectsProcessGroupPrecondition(t *testing.T) {
+ cmd := exec.Command("/bin/sh", "-c", "true")
+ configureProcessGroup(cmd)
+
+ if cmd.SysProcAttr == nil || !cmd.SysProcAttr.Setpgid {
+ t.Fatal("configureProcessGroup did not set Setpgid — reapProcessTree " +
+ "can no longer reach descendants")
+ }
+}
+
+// TestRunCollectCmdHonorsContextWithoutACommandContext — RunCollectCmd takes a
+// command the caller built, so "the ctx is enforced" must not quietly depend on
+// that caller having used exec.CommandContext. A plain exec.Command with a
+// hanging CLI is the shape that would otherwise block for as long as the CLI
+// felt like running, with the ctx argument doing nothing at all.
+func TestRunCollectCmdHonorsContextWithoutACommandContext(t *testing.T) {
+ cli := writeCLI(t, "#!/bin/sh\nsleep 300\n")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
+ defer cancel()
+
+ start := time.Now()
+ _, _, _, err := RunCollectQuietCmd(ctx, exec.Command(cli), nil, 0, nil)
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Error("expected an error once the context expired")
+ }
+ if elapsed > 10*time.Second {
+ t.Errorf("took %v — the context did not bound a command built without one", elapsed)
+ }
+}
+
+// TestDetectCLIVersionReapsForkedHelper covers the real caller: version
+// detection runs inside the daemon's blocking preflight for every registered
+// provider, and it was one of the paths leaking `openclaw-config`.
+func TestDetectCLIVersionReapsForkedHelper(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLI(t, pidFile)
+
+ version, err := detectCLIVersion(context.Background(), Command{Path: cli})
+ if err != nil {
+ t.Fatalf("detectCLIVersion: %v", err)
+ }
+ if !strings.Contains(version, "1.2.3") {
+ t.Errorf("version = %q, want it to contain 1.2.3", version)
+ }
+
+ pid := waitForPidFile(t, pidFile)
+ if !waitForProcessGone(pid, 5*time.Second) {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("detectCLIVersion left helper pid %d running", pid)
+ }
+}
+
+// assertNoGoroutineGrowth pins the contract that finish() joins everything
+// startCollector spawned. Polls because goroutine teardown is observed
+// asynchronously, but a correct implementation satisfies it on the first look.
+func assertNoGoroutineGrowth(t *testing.T, before int) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ got := runtime.NumGoroutine()
+ if got <= before {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Errorf("goroutines: %d before, %d after — the collector must join "+
+ "its reader and wait goroutines before returning, on every exit "+
+ "path", before, got)
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// TestRunCollectLeavesNoGoroutines pins review item 3: the call must not park a
+// goroutine on a CLI whose descendant holds the pipe. Previously the wait
+// goroutine could sit in cmd.Wait indefinitely when no owned process-tree
+// boundary released the inherited pipe.
+//
+// Scope: this proves convergence for a tree the kill reaches, which is the case
+// the fix is about. It does not — and cannot — prove anything about a process
+// the OS refuses to terminate; finish() logs that case and still returns the
+// answer, rather than reporting it as a failed call.
+func TestRunCollectLeavesNoGoroutines(t *testing.T) {
+ pidFile := filepath.Join(t.TempDir(), "helper.pid")
+ cli := writeForkingCLI(t, pidFile)
+
+ // Warm up so lazily-created runtime goroutines exist before the baseline.
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli); err != nil {
+ t.Fatalf("warmup: %v", err)
+ }
+ before := runtime.NumGoroutine()
+
+ for i := 0; i < 2; i++ {
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, cli); err != nil {
+ t.Fatalf("run %d: %v", i, err)
+ }
+ }
+ assertNoGoroutineGrowth(t, before)
+}
+
+// TestRunCollectQuietLeavesNoGoroutines pins the same contract on the path that
+// returns while the CLI is still alive — the one that has to kill the child
+// itself rather than waiting for it. Same scope caveat as above: a successful
+// reap is what is being verified.
+func TestRunCollectQuietLeavesNoGoroutines(t *testing.T) {
+ cli := writePrintThenHangCLI(t, quietTestJSON, "")
+
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli); err != nil {
+ t.Fatalf("warmup: %v", err)
+ }
+ before := runtime.NumGoroutine()
+
+ for i := 0; i < 2; i++ {
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, JSONOutputComplete, cli); err != nil {
+ t.Fatalf("run %d: %v", i, err)
+ }
+ }
+ assertNoGoroutineGrowth(t, before)
+}
+
+// TestOutputBufferAbsorbStopsWhenReadEndClosed pins the mechanism finish() relies
+// on when a descendant will not release the pipe: closing the read end has to
+// terminate the in-flight Read, otherwise the join would hang and the previous
+// revision's alternative — returning while io.Copy was still appending — is a
+// data race on the buffer the caller is about to read.
+func TestOutputBufferAbsorbStopsWhenReadEndClosed(t *testing.T) {
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("pipe: %v", err)
+ }
+ defer w.Close()
+
+ var buf outputBuffer
+ done := make(chan struct{})
+ go func() { defer close(done); _ = buf.absorb(r) }()
+
+ if _, err := w.WriteString("partial"); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+ // Let the reader pick it up, then pull the rug out while it is blocked in
+ // Read with the write end still open (i.e. no EOF is coming).
+ time.Sleep(50 * time.Millisecond)
+ r.Close()
+
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("absorb did not return after the read end was closed — finish() " +
+ "would block forever waiting to join it")
+ }
+ if got := string(buf.snapshot()); got != "partial" {
+ t.Errorf("snapshot = %q, want the bytes that arrived before the close", got)
+ }
+}
+
+// TestOutputBufferPublishesBytesAndTimestampTogether pins review item 2. The
+// buffer and the last-write timestamp are updated in one critical section, so a
+// reader can never see new bytes carrying a stale timestamp and conclude the
+// stream has gone quiet while it is in fact producing.
+//
+// Run under -race this also covers the concurrent access itself.
+func TestOutputBufferPublishesBytesAndTimestampTogether(t *testing.T) {
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("pipe: %v", err)
+ }
+
+ var buf outputBuffer
+ absorbed := make(chan struct{})
+ go func() { defer close(absorbed); _ = buf.absorb(r) }()
+
+ writing := make(chan struct{})
+ go func() {
+ defer close(writing)
+ for i := 0; i < 60; i++ {
+ _, _ = w.WriteString("x")
+ time.Sleep(3 * time.Millisecond)
+ }
+ w.Close()
+ }()
+
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case <-writing:
+ // Writer finished; idleness is legitimate from here on.
+ <-absorbed
+ return
+ default:
+ }
+ n := len(buf.snapshot())
+ idle, produced := buf.idleFor()
+ // While the writer is active at 1ms intervals, any observed byte must
+ // come with a recent timestamp. A generous bound keeps this from being a
+ // scheduling flake while still failing if the timestamp lagged the bytes
+ // by a whole grace period.
+ if produced && n > 0 && idle > 300*time.Millisecond {
+ t.Fatalf("saw %d bytes with idle=%v while the writer was still "+
+ "producing — a stale timestamp lets RunCollectQuiet truncate an "+
+ "answer mid-write", n, idle)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ <-writing
+ <-absorbed
+}
diff --git a/server/pkg/agent/run_collect_windows_test.go b/server/pkg/agent/run_collect_windows_test.go
new file mode 100644
index 0000000000..ab7fa9f2d3
--- /dev/null
+++ b/server/pkg/agent/run_collect_windows_test.go
@@ -0,0 +1,247 @@
+//go:build windows
+
+package agent
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+// Windows contract coverage for the collector, requested in review of #6275.
+//
+// Windows has no Unix process groups, so the collector uses a Job Object. These
+// tests pin both process-tree ownership and the platform-independent contract:
+//
+// - the call returns rather than parking on a CLI that will not exit;
+// - the output captured before that is complete and correct;
+// - no goroutine started by startCollector outlives the call whenever the Job
+// Object kill takes, so a daemon invoking these helpers on a timer cannot
+// accumulate parked goroutines. A process the OS refuses to terminate is out
+// of scope here, as it is on Unix: finish() logs that and still returns the
+// answer.
+//
+// execenv/isolation_windows_test.go separately pins the outer Job Object around
+// the complete task-preparation helper.
+
+const windowsCollectJSON = `{"agents":[{"id":"main"}]}`
+
+// writeWindowsPrintThenHangShim creates a batch shim that prints payload and then
+// stays alive, mirroring `openclaw config file` on the affected build. `ping` is
+// used as the sleep because it is present on every Windows image and its own
+// output is redirected away so it cannot pollute the captured stdout.
+func writeWindowsPrintThenHangShim(t *testing.T, payload string) string {
+ t.Helper()
+ shim := filepath.Join(t.TempDir(), "fake-cli.cmd")
+ body := "@ECHO off\r\n" +
+ "ECHO " + payload + "\r\n" +
+ "ping -n 20 127.0.0.1 >NUL\r\n"
+ if err := os.WriteFile(shim, []byte(body), 0o644); err != nil {
+ t.Fatalf("write shim: %v", err)
+ }
+ return shim
+}
+
+func windowsAssertNoGoroutineGrowth(t *testing.T, before int) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ got := runtime.NumGoroutine()
+ if got <= before {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Errorf("goroutines: %d before, %d after — the collector must join "+
+ "its reader and wait goroutines before returning, including on "+
+ "Windows where cleanup uses a Job Object", before, got)
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// TestWindowsRunCollectQuietCutsShortAndLeavesNoGoroutines is the main Windows
+// contract: a CLI that prints a complete answer and then refuses to exit must
+// still yield that answer promptly, and must not leave anything behind.
+func TestWindowsRunCollectQuietCutsShortAndLeavesNoGoroutines(t *testing.T) {
+ shim := writeWindowsPrintThenHangShim(t, windowsCollectJSON)
+
+ // A long ctx on purpose: returning must come from the completeness rule
+ // plus the idle grace, not from the deadline.
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+
+ if _, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, shim); err != nil {
+ t.Fatalf("warmup: %v", err)
+ }
+ before := runtime.NumGoroutine()
+
+ start := time.Now()
+ out, _, quiet, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, shim)
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("RunCollectQuiet: %v", err)
+ }
+ if got := strings.TrimSpace(string(out)); got != windowsCollectJSON {
+ t.Errorf("stdout = %q, want the printed answer", got)
+ }
+ if !quiet {
+ t.Error("quiet = false, want true — the shim never exits")
+ }
+ // Loose bound: only has to sit far below the 90s ctx and the shim's own 60s
+ // ping, either of which a broken mechanism would take.
+ if elapsed > 30*time.Second {
+ t.Errorf("took %v — waited for an exit that never comes", elapsed)
+ }
+ windowsAssertNoGoroutineGrowth(t, before)
+}
+
+// TestWindowsRunCollectQuietDoesNotSalvagePartialOutput pins that the deadline is
+// not success on Windows either: a shim still streaming when the deadline lands
+// must not have its truncated output reported as a finished answer.
+func TestWindowsRunCollectQuietDoesNotSalvagePartialOutput(t *testing.T) {
+ shim := filepath.Join(t.TempDir(), "streaming.cmd")
+ // Plain ECHO rather than `<NUL SET /P` for the no-newline trick: the quoting
+ // rules around SET /P are subtle and this file cannot be executed outside a
+ // real Windows runner, so a fragile shim would fail in CI for reasons that
+ // have nothing to do with the code under test. Newlines between the fragments
+ // are irrelevant here — the buffer is never valid JSON either way, which is
+ // the whole point.
+ body := "@ECHO off\r\n" +
+ "ECHO {\"agents\":[\r\n" +
+ ":loop\r\n" +
+ "ECHO {\"id\":\"a\"},\r\n" +
+ "ping -n 2 127.0.0.1 >NUL\r\n" +
+ "GOTO loop\r\n"
+ if err := os.WriteFile(shim, []byte(body), 0o644); err != nil {
+ t.Fatalf("write shim: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ out, _, _, err := RunCollectQuiet(ctx, nil, 0, JSONOutputComplete, shim)
+ if err == nil {
+ t.Fatalf("partial output reported as success (%d bytes) — an interrupted "+
+ "response must never be handed to a caller as a finished one", len(out))
+ }
+}
+
+// TestWindowsRunCollectReturnsAndLeavesNoGoroutines pins the wait-for-exit helper
+// on Windows: a normal command is captured correctly and joins everything.
+func TestWindowsRunCollectReturnsAndLeavesNoGoroutines(t *testing.T) {
+ shim := filepath.Join(t.TempDir(), "quick.cmd")
+ body := "@ECHO off\r\nECHO fake-cli 1.2.3\r\nEXIT /B 0\r\n"
+ if err := os.WriteFile(shim, []byte(body), 0o644); err != nil {
+ t.Fatalf("write shim: %v", err)
+ }
+
+ if _, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, shim); err != nil {
+ t.Fatalf("warmup: %v", err)
+ }
+ before := runtime.NumGoroutine()
+
+ out, _, _, err := RunCollectQuiet(context.Background(), nil, 0, nil, shim)
+ if err != nil {
+ t.Fatalf("RunCollect: %v", err)
+ }
+ if !strings.Contains(string(out), "fake-cli 1.2.3") {
+ t.Errorf("stdout = %q, lost the output", out)
+ }
+ windowsAssertNoGoroutineGrowth(t, before)
+}
+
+func TestWindowsRunCollectKillsDescendant(t *testing.T) {
+ tempDir := t.TempDir()
+ sourcePath := filepath.Join(tempDir, "fake_cli.go")
+ exePath := filepath.Join(tempDir, "fake_cli.exe")
+ pidPath := filepath.Join(tempDir, "descendant.pid")
+ const source = `package main
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "time"
+)
+func main() {
+ if len(os.Args) > 1 && os.Args[1] == "descendant" {
+ time.Sleep(time.Minute)
+ return
+ }
+ child := exec.Command(os.Args[0], "descendant")
+ child.Stdout = os.Stdout
+ child.Stderr = os.Stderr
+ if err := child.Start(); err != nil { panic(err) }
+ if err := os.WriteFile(os.Getenv("DESCENDANT_PID_FILE"), []byte(fmt.Sprint(child.Process.Pid)), 0600); err != nil { panic(err) }
+ fmt.Println("fake-cli 1.2.3")
+}`
+ if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ build := exec.Command("go", "build", "-o", exePath, sourcePath)
+ if output, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build Windows fake CLI: %v: %s", err, output)
+ }
+
+ env := append(os.Environ(), "DESCENDANT_PID_FILE="+pidPath)
+ out, _, _, err := RunCollectQuiet(context.Background(), env, 0, nil, exePath)
+ if err != nil {
+ t.Fatalf("RunCollect: %v", err)
+ }
+ if !strings.Contains(string(out), "fake-cli 1.2.3") {
+ t.Fatalf("stdout = %q, lost the direct child's output", out)
+ }
+ rawPID, err := os.ReadFile(pidPath)
+ if err != nil {
+ t.Fatalf("read descendant pid: %v", err)
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(rawPID)))
+ if err != nil {
+ t.Fatalf("parse descendant pid: %v", err)
+ }
+ descendantAlive := true
+ t.Cleanup(func() {
+ if descendantAlive {
+ process, findErr := os.FindProcess(pid)
+ if findErr != nil {
+ return
+ }
+ _ = process.Kill()
+ }
+ })
+
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ process, openErr := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))
+ if errors.Is(openErr, windows.ERROR_INVALID_PARAMETER) {
+ descendantAlive = false
+ return
+ }
+ if openErr != nil {
+ t.Fatalf("open descendant pid %d: %v", pid, openErr)
+ }
+ state, waitErr := windows.WaitForSingleObject(process, 0)
+ windows.CloseHandle(process)
+ if waitErr != nil {
+ t.Fatalf("query descendant pid %d: %v", pid, waitErr)
+ }
+ if waitErr == nil && state == windows.WAIT_OBJECT_0 {
+ descendantAlive = false
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("descendant pid %d survived RunCollect", pid)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
diff --git a/server/pkg/agent/version_test.go b/server/pkg/agent/version_test.go
index d2f8628d09..6d54eb5cf7 100644
--- a/server/pkg/agent/version_test.go
+++ b/server/pkg/agent/version_test.go
@@ -96,56 +96,82 @@ func TestExtractVersionLine(t *testing.T) {
name string
raw string
want string
+ // wantRecognised is whether the semver scan matched, as opposed to the
+ // trimmed-raw fallback answering. Pinned per case because
+ // salvageProbeAnswer treats the two differently: only a recognised
+ // version is evidence that an incomplete read already holds the answer.
+ wantRecognised bool
}{
{
- name: "bare semver",
- raw: "0.42.0\n",
- want: "0.42.0",
+ name: "bare semver",
+ raw: "0.42.0\n",
+ want: "0.42.0",
+ wantRecognised: true,
},
{
- name: "claude full string preserved",
- raw: "2.1.5 (Claude Code)\n",
- want: "2.1.5 (Claude Code)",
+ name: "claude full string preserved",
+ raw: "2.1.5 (Claude Code)\n",
+ want: "2.1.5 (Claude Code)",
+ wantRecognised: true,
},
{
- name: "codex prefix preserved",
- raw: "codex-cli 0.118.0\n",
- want: "codex-cli 0.118.0",
+ name: "codex prefix preserved",
+ raw: "codex-cli 0.118.0\n",
+ want: "codex-cli 0.118.0",
+ wantRecognised: true,
},
// Reproduces #2516: gemini's Windows shim emits `chcp` output to stdout
// before the real version. The chcp line has no dotted-number form,
// so the semver scan skips it and picks up "0.42.0" from the next line.
{
- name: "windows chcp prefix before version",
- raw: "Active code page: 65001\n0.42.0\n",
- want: "0.42.0",
+ name: "windows chcp prefix before version",
+ raw: "Active code page: 65001\n0.42.0\n",
+ want: "0.42.0",
+ wantRecognised: true,
},
{
- name: "windows chcp prefix CRLF",
- raw: "Active code page: 65001\r\n0.42.0\r\n",
- want: "0.42.0",
+ name: "windows chcp prefix CRLF",
+ raw: "Active code page: 65001\r\n0.42.0\r\n",
+ want: "0.42.0",
+ wantRecognised: true,
},
{
- name: "leading blank lines",
- raw: "\n\n 0.42.0\n",
- want: "0.42.0",
+ name: "leading blank lines",
+ raw: "\n\n 0.42.0\n",
+ want: "0.42.0",
+ wantRecognised: true,
},
{
- name: "non-semver output falls back to trimmed raw",
- raw: " some-build-id \n",
- want: "some-build-id",
+ name: "non-semver output falls back to trimmed raw",
+ raw: " some-build-id \n",
+ want: "some-build-id",
+ wantRecognised: false,
},
+ // The shape the salvage gate turns on: a wrapper's progress line
+ // satisfies the fallback, so "non-empty" cannot mean "the version
+ // arrived". See TestDetectCLIVersionDoesNotSalvageABannerAsTheVersion.
{
- name: "empty input",
- raw: "",
- want: "",
+ name: "wrapper banner is not a recognised version",
+ raw: "initializing plugins\n",
+ want: "initializing plugins",
+ wantRecognised: false,
+ },
+ {
+ name: "empty input",
+ raw: "",
+ want: "",
+ wantRecognised: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := extractVersionLine(tt.raw); got != tt.want {
+ got, recognised := extractVersionLine(tt.raw)
+ if got != tt.want {
t.Errorf("extractVersionLine(%q) = %q, want %q", tt.raw, got, tt.want)
}
+ if recognised != tt.wantRecognised {
+ t.Errorf("extractVersionLine(%q) recognised = %v, want %v", tt.raw, recognised, tt.wantRecognised)
+ }
})
}
}