Skip to content

fix: sessions_spawn outputSchema is ignored on CLI backends - #146715

Merged
roboclaw-bot merged 4 commits into
openclaw:mainfrom
etzelm:fix/cli-collector-structured-output
Sep 14, 2026
Merged

roboclaw-bot merged 4 commits into
openclaw:mainfrom
etzelm:fix/cli-collector-structured-output

Conversation

@etzelm

@etzelm etzelm commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Related: #141474

Merged as 268dbc6d08b1. Verified on main with Mitchell Etzel as author and VACInc as coauthor. Landed source head: d8c61fdc00cc1dd3fe6255d5d55c634e50ce7fc6. Original contributor ancestry is preserved. The branch incorporates upstream service-fixture repair #147398, landed collector-yield repair #146716, and deterministic Reef fixture repair #147551. No duplicate fixture implementation was added. The feature delta remains unchanged (stable patch ID 77b235aeeebfea9df5338ddc815f5e53057eb1de); a small docs follow-up removes the obsolete CLI collector exception.

Current CI: exact-head run 34791962154 completed successfully, including openclaw/ci-gate job103821518360. A cancelled ClawSweeper Dispatch is separate review automation, not a failed product test. The previous refreshed-head run failed the Reef scan fixture because equal-millisecond writes changed its order; #147551 supplies distinct fixture timestamps and guaranteed clock cleanup while preserving every result and read-count assertion. It is now included via its original upstream commit ddc8743ab6cfed3db44600eda63ccb3a862475a4.

Proof attribution: references to “this head” in the original contributor evidence below mean 9ce1a595aca78bd49e8948768300255668030c83. Those live runs have not been relabeled as executions on the refreshed head. Historical stranded collector recovery remains outside this PR; #141474 stays open.

Worked on by: Mitchell Etzel (@etzelm), Vito Cappello (@VACInc). Coordination session.

What Problem This Solves

Fixes: a Swarm collector child silently ignores outputSchema and its agents_wait returns status: "failed" with schemaError: "structured_output was not called" when that child runs on a CLI backend such as claude-cli, codex-cli, or gemini-cli.

User Impact

sessions_spawn with collect: true and an outputSchema now returns a validated structured result regardless of which runtime the child uses, so Swarm scripts and agents.run() calls no longer have to keep collector children on an embedded model to get structured output. Every collector child on a CLI backend also stops being offered sessions_yield, ask_user, and sessions_send, which they were never able to use productively, whether or not that child requested an outputSchema.

The contract applies only to the admitted collector run: the request has to present that collector's own Gateway run id, which reaches tool resolution exclusively through the run-bound CLI client grant the Gateway mints for that child's turn. Two other kinds of caller share this code path and neither is affected. A session-scoped openclaw attach client, even one bound to the collector's own session key on the same loopback server, carries no run id and therefore gets the plain surface: no structured_output, and sessions_yield and the other requester tools exactly as main serves them today. The operator-facing http tool-invoke surface (surface has exactly two values) is likewise unchanged from main, and operator tool policy stays authoritative there.

Why This Change Was Made

Embedded runs pass the collector's swarmCollector and swarmOutputSchema into tool construction, and that is what builds the synthetic structured_output tool. CLI backends receive their OpenClaw tools from the Gateway's loopback MCP resolver instead, and the loopback grant carries no collector fields, so the tool was never built. The child reported "A tool named structured_output was not present in my tool list" while outputSchema stayed accepted and documented.

The resolver now derives the collector contract from the subagent registry, the same durable owner the Gateway preflight already trusts when deciding whether a session is a collector. Collector identity follows the registry's collect flag alone, so it matches the embedded runner, which takes swarmCollector straight from the spawn request for every collector; the outputSchema gates only the result transport, not the identity. No new state, marker, or store is added. The registry also supplies the collector's run id, so a recorded result lands under the key agents_wait reads back even when the CLI turn's run id differs.

This is a deliberate precedence of the collector run contract over operator tool policy (tools.allow, gateway deny lists) for the admitted collector run's own turn, matching what the embedded runner already does in-process for the same runs. Nothing changes for any other caller.

Two deliberate choices:

  • The run contract outranks tool policy, at both enforcement points. structured_output is restored after the resolver's policy pipeline, so a restrictive tools.allow cannot delete a run contract. That alone is not enough. A per-run grant allowlist is applied after the resolver returns and is enforced exactly on tools/list and tools/call. A collector launched by sessions_spawn or agents.run() carries no toolsAllow, but one launched through a plugin's api.runtime.subagent.run, or restored from a cron continuation, can. The CLI attempt therefore merges the forced tool name into that allowlist before the grant is minted, using the same mergeForcedEmbeddedAttemptToolsAllow helper the embedded runner already uses. The grant filter itself is untouched, so a hard allowlist stays a hard allowlist.

  • The contract is bound to the admitted collector run, not to the transport or the session key. The transport alone is not authority. The loopback MCP server authenticates three kinds of caller, and only one of them is the collector child: a run-bound CLI client grant (minted per run, presented with its capture key), a session-scoped openclaw attach bearer, and the server's own owner/non-owner tokens. resolveMcpRequestContext returns the grant's immutable context for the first and a minimal { sessionKey, agentId } context for the second, so runId is present only for a run-bound CLI grant. The header-derived branch never sets it either, and the single http caller (tools-invoke-shared.ts) never passes one. The resolver therefore requires params.runId to match the registry collector record for that child session, comparing against both entry.runId and the launch id retained as entry.swarmRunId, which is the same pair getSubagentRunByRunId matches after a queued relaunch remaps the row. An attach client bound to the collector's own session resolves to the plain surface, and tools/call resolves names out of that exact list, so naming structured_output returns Tool not available: structured_output and reaches no writer.

    A final authority re-check before persistence. Tool lists are cached per grant for up to 30 seconds, and the before-tool hook is awaited between tool construction and execute, so admission at construction time is not sufficient on its own. The result tool's onStateChange now re-checks, immediately before recordSwarmStructuredOutput, that the grant is still current and that the caller still owns the admitted collector run. The first operand is the same isCurrent liveness check the loopback server already applies as authorizeToolCall after the hook; the second is the same admitted-run test the resolver applied. A failure throws, createStructuredOutputTool rolls its in-memory state back and returns a tool error, and nothing is written to the registry or to the durable row. No new store, marker, or mechanism is introduced, and the callback is not part of the tool cache key because the grant token already is and every grant-row replacement evicts that token's cached tools.

    Reachability of recordSwarmStructuredOutput. It has exactly one production caller: the onStateChange callback of the tool built in createOpenClawSwarmToolGroups. That tool is only built when createOpenClawTools is given both swarmCollector and swarmOutputSchema. Exactly two call sites supply them: agent-tools.ts, the embedded runner reading the spawn request in-process, and tool-resolution.ts, now only for a matched admitted collector run. The third createOpenClawTools caller, skills/runtime/tool-dispatch.ts, passes neither. So a collector result can be submitted only from the collector child's own admitted run: operator-submitted results and submission by an attach client or any other participant cannot occur, because the tool is never present for them, and a revocation that lands during the awaited runBeforeToolCallHook now fails at the write itself as well as at the server's post-hook check.

    Should a missing in-memory collector record refuse every tool request for a persisted schema-backed session? No. The previous revision's fail-closed throw and its persisted-session-store probe are both removed. A collector turn whose registry record is not loaded now resolves to the plain surface, which is exactly what main does, so restart behavior is identical to main, no operator inspection path is affected, and no existing persisted session loses its tool surface. Restart recovery of collector runs is not this resolver's job in the first place: subagent-registry-restart-recovery.ts re-dispatches a recovered run with swarmCollector and swarmOutputSchema rebuilt from the persisted entry, and that file is untouched here.

Side effect worth naming: carrying collector context into this path also applies the existing collector tool filter, so CLI collector children no longer receive sessions_yield. Because identity is schema-independent, that holds for a collector spawned without an outputSchema too, which is the arm the issue's D2 describes: it loses the requester-only tools even though it receives no structured_output. That is the cheap mitigation suggested in the issue for D2, and it is covered by a test here. The rest of D2, the yield stranding itself, is out of scope for this PR.

docs/tools/swarm.md now removes the temporary CLI collector exception added with #146716. Its structured-output contract already required the synthetic result tool; this PR aligns CLI behavior with that contract.

Evidence

Two regression tests, each at the layer that owns its half of the defect, plus a new describe in the existing loopback MCP server suite that drives the same authority chain through the running server.

src/gateway/tool-resolution.swarm-collector.test.ts drives the real entry point resolveGatewayScopedTools with a collector run registered in the subagent registry, executes the resolved tool and asserts the result reaches the registry record, then drives resolveMcpLoopbackScopedTools to cover the grant allowlist enforced above the resolver. The same describe registers a second collector run carrying no outputSchema and pins the schema-independent half of the contract on it: the requester-only tools are withheld, structured_output stays absent, and the flag reaches tool construction (its resolved sessions_spawn rejects a nested non-collector spawn, the same option the yield admission check reads). It also pins the unloaded-registry case: a subagent session the registry has no record of resolves to a plain surface with sessions_yield intact, which is main's behavior.

A second describe pins the admission gate, calling the resolver the way each of its real callers does. A loopback request with no run id, which is exactly the context resolveMcpRequestContext builds for a session-scoped attach grant, must resolve a collector session to the same tool list a plain child gets: no structured_output, sessions_yield intact, and the registry record still carrying no structuredOutput and no collectorCompletion. A loopback request carrying a different run's id must get the same plain surface. A request carrying the launch id a queued relaunch retains as swarmRunId must still be admitted. The same describe keeps the http cases: tools-invoke-shared.ts passes surface: "http", and there a collector session must resolve to a tool list identical to a plain child's, must keep sessions_yield, and must let a restrictive tools.allow win outright.

A third describe pins the write-time re-check on the tool's own execute path. With the grant flipped to revoked after the tool is built, execute rejects with collector run grant is no longer active and neither structuredOutput nor collectorCompletion is written; with the registry record rebound to a different run after the tool is built, it rejects with caller no longer owns the admitted collector run and again writes nothing; with the grant still current it records normally. The fourth describe drives resolveMcpLoopbackScopedTools, the loopback entry point above the resolver, for the grant allowlist and for the run-less context.

src/agents/command/attempt-execution.cli.test.ts covers the merge itself: a restricted collector attempt must hand runCliAgent a toolsAllow that still contains structured_output, while a schema-less collector attempt and a plain non-collector attempt must both be left untouched.

src/gateway/mcp-http.test.ts closes the last gap between the resolver tests and the running server. The resolver tests supply the attach client's missing run id as a parameter; the premise that an attach grant has no run id lives one layer up, in resolveMcpRequestContext. The new describe registers a schema-backed collector run and then goes over the wire to a real ensureMcpLoopbackServer, with the mocked resolver delegating to the real resolveGatewayScopedTools, so every layer between the bearer token and the registry record runs: an openclaw attach grant minted for that collector's own child session gets a tools/list without structured_output, a tools/call structured_output answered Tool not available: structured_output with isError: true, and a registry record still holding neither structuredOutput nor collectorCompletion. The collector's own run-bound client grant, presented with its capture key, gets the tool listed and records { answer: "ok" }. Two rejection cases run the revocation inside the awaited before-tool hook itself: revoking the grant there is refused with Tool call authorization expired, and rebinding the registry record to a different run there, which leaves grant liveness untouched, is refused with Failed to persist structured_output: caller no longer owns the admitted collector run. Both leave the record unchanged.

Authority-chain evidence. Three proofs, each run twice, once at the resolver and once over the loopback MCP server, and each fails if its gate is removed:

  1. Allowed collector. A loopback request presenting the admitted collector run's own id resolves structured_output, and executing it records { structured: { answer: "ok" }, invalidAttempts: 0 } on that collector's registry record. Over the server, a tools/call on that collector's own run-bound grant does the same.
  2. Session-scoped attach client. A loopback request for the same collector session carrying no run id resolves the plain surface, so the writer is neither listed nor callable and nothing is persisted. Over the server, a real openclaw attach grant for that session produces the run-less context itself rather than receiving it as a parameter.
  3. Revoked during the hook. A grant revoked after tool construction makes execute fail closed before recordSwarmStructuredOutput, leaving the record untouched. Over the server, the revocation is performed inside the awaited before-tool hook, and the caller is refused before execute runs at all.

Mutation checks, all re-verified on this head against a pre-mutation copy of the sources, which was restored and re-run green after each. Reverting the admitted-run gate to the previous session-key-only resolution turns 8 of the resolver suite's 22 cases red, including all three attach-client and cross-run cases, and 2 of the 4 new boundary cases. Removing only the pre-persistence re-check turns 2 of those 22 red and 1 of the 4. Removing the server's own post-hook liveness check does not open the write: the revoked-in-hook boundary case then fails one layer lower, on the re-check this PR adds, with Failed to persist structured_output: collector run grant is no longer active. The red summaries are in the details block below.

Live receipts are under Live behavior proof below. Arms 1 and 2 are measured there against a real gateway, arm 2 with a before and an after on the same harness. Arm 3 is measured on the collector's real grant but one layer earlier than the in-hook window: once the grant row is gone the loopback MCP refuses at transport auth with a bare 401 and nothing is written, so the two tool-level refusal texts come from the tests above rather than from that run.

Before (the eight source files reverted to base, all three test files kept):

$ node scripts/run-vitest.mjs src/gateway/tool-resolution.swarm-collector.test.ts
 × resolveGatewayScopedTools swarm collectors > serves structured_output to a collector child resolved through the gateway
   → expected collector output transport to be defined
 × resolveGatewayScopedTools swarm collectors > keeps structured_output through a restrictive gateway tool policy
   → expected [ 'sessions_list' ] to include 'structured_output'
 × resolveGatewayScopedTools swarm collectors > omits interactive and pausing tools for a gateway collector child
   → expected [ 'dashboard', 'nodes', …(20) ] to not include 'sessions_yield'
 ✓ resolveGatewayScopedTools swarm collectors > leaves non-collector sessions without the collector transport
 × resolveGatewayScopedTools swarm collectors > stops serving the collector transport after the result is captured
   → expected [ 'dashboard', 'nodes', …(20) ] to not include 'sessions_yield'
 × resolveGatewayScopedTools swarm collectors > withholds requester-only tools from a collector child that requested no schema
   → expected [ 'dashboard', 'nodes', …(20) ] to not include 'sessions_yield'
 × resolveGatewayScopedTools swarm collectors > passes collector identity into tool construction for a schema-less collector
   → promise resolved "{ content: [ { …(2) } ], …(1) }" instead of rejecting
 ✓ resolveGatewayScopedTools swarm collectors > resolves a plain surface for a subagent session the registry has no record of
 ✓ collector contract is bound to the admitted collector run > serves the plain surface to a session-scoped attach client on the same session
 ✓ collector contract is bound to the admitted collector run > writes nothing for an attach client, because the result tool is never listed
 ✓ collector contract is bound to the admitted collector run > withholds the contract from a run-bound grant for a different run
 × collector contract is bound to the admitted collector run > admits the collector through the launch id a queued relaunch retains
   → expected [ 'dashboard', 'nodes', …(20) ] to include 'structured_output'
 ✓ collector contract is bound to the admitted collector run > leaves the http surface exactly as it is without a collector session
 ✓ collector contract is bound to the admitted collector run > does not withhold requester-only tools from a collector session on the http surface
 ✓ collector contract is bound to the admitted collector run > keeps operator tool policy authoritative for a collector session on the http surface
 × collector contract is bound to the admitted collector run > still applies the full contract on the loopback surface
   → expected [ 'dashboard', 'nodes', …(20) ] to include 'structured_output'
 × collector write authority is re-checked before persistence > rejects the result when the grant is revoked between construction and execute
   → expected collector output transport to be defined
 × collector write authority is re-checked before persistence > rejects the result when the caller stops owning the admitted collector run
   → expected collector output transport to be defined
 × collector write authority is re-checked before persistence > records the result while the grant is still current
   → expected collector output transport to be defined
 × collector tools behind the loopback grant allowlist > serves structured_output when the CLI grant carries the merged collector allowlist
   → expected [ 'read' ] to include 'structured_output'
 ✓ collector tools behind the loopback grant allowlist > hard-filters structured_output out of a grant that never merged it
 ✓ collector tools behind the loopback grant allowlist > withholds structured_output from a run-less context at the loopback entry point
 Test Files  1 failed (1)
      Tests  12 failed | 10 passed (22)

$ node scripts/run-vitest.mjs src/agents/command/attempt-execution.cli.test.ts
 × CLI attempt execution > merges the collector result transport into a restricted CLI toolsAllow
   → expected [ 'read' ] to deeply equal [ 'read', 'structured_output' ]
 Test Files  1 failed (1)
      Tests  1 failed | 154 passed (155)

$ node scripts/run-vitest.mjs src/gateway/mcp-http.test.ts
 ✓ collector result tool across the loopback MCP boundary > gives an attach grant on the collector's session no result tool to list or call
 × collector result tool across the loopback MCP boundary > refuses the collector's own call when its grant is revoked inside the before-tool hook
   → expected [ 'dashboard', 'tts', …(13) ] to include 'structured_output'
 × collector result tool across the loopback MCP boundary > refuses the collector's own call when the record stops owning the admitted run
   → expected [ 'dashboard', 'tts', …(13) ] to include 'structured_output'
 × collector result tool across the loopback MCP boundary > records the result for the collector's own run-bound grant
   → expected true not to be true
 Test Files  1 failed (1)
      Tests  3 failed | 121 passed (124)

The ten passing collector cases are controls that must not change: a non-collector session, a subagent session with no registry record, the three attach-client and cross-run cases, the run-less loopback entry point, the three http-surface cases (all of which pass on base precisely because base serves no collector contract at all on this resolver), and the grant filter still hard-filtering a tool that was never merged into it. The attach case in the boundary suite is a control for the same reason: base serves no result tool on that surface to anyone, so an attach client is refused there on both commits, and only this branch has to keep refusing it while the collector's own grant succeeds.

After: 473 tests pass across 15 files and 4 shards, covering both new regression tests and the new boundary describe, plus the existing Gateway tool-resolution, tool-resolution exclude, loopback MCP server, MCP runtime, MCP schema, MCP question-authority, attach, Swarm, structured-output, collector, and swarm-tools suites.

Validation, all clean:

Command Result
node scripts/run-vitest.mjs <15 test files> 4 shards passed, 473 tests, 39.62s, exit 0
node scripts/check-changed.mjs --timed exit 0, all lanes ok, including typecheck core, typecheck core tests, format changed files, lint, import cycles, dead export scan
git diff --check exit 0, no output
Full test and check output
$ node scripts/run-vitest.mjs src/gateway/tool-resolution.swarm-collector.test.ts \
    src/agents/command/attempt-execution.cli.test.ts src/gateway/tool-resolution.test.ts \
    src/gateway/tool-resolution.exclude.test.ts src/agents/openclaw-tools.swarm.test.ts \
    src/agents/tools/structured-output-tool.test.ts \
    src/agents/agent-tools.collector.integration.test.ts \
    src/agents/tools/swarm-tools.integration.test.ts \
    src/gateway/mcp-http.test.ts src/gateway/mcp-http.runtime.test.ts \
    src/gateway/mcp-http.schema.test.ts src/gateway/mcp-http.handlers.network-error.test.ts \
    src/gateway/mcp-http.oauth-tools.test.ts src/gateway/mcp-http.question-authority.test.ts \
    src/gateway/server-methods/attach.test.ts

[test] starting test/vitest/vitest.gateway.config.ts
 Test Files  10 passed (10)
      Tests  291 passed (291)
[test] starting test/vitest/vitest.agents-core.config.ts
 Test Files  2 passed (2)
      Tests  19 passed (19)
[test] starting test/vitest/vitest.agents-support.config.ts
 Test Files  1 passed (1)
      Tests  155 passed (155)
[test] starting test/vitest/vitest.agents-tools.config.ts
 Test Files  2 passed (2)
      Tests  8 passed (8)
[test] passed 4 Vitest shards in 39.62s
VITEST_EXIT=0

$ node scripts/check-changed.mjs --timed 2>&1 | tail -25
   179ms  ok         guarded extension wildcard re-exports
   162ms  ok         plugin-sdk wildcard re-exports
   248ms  ok         duplicate scan target coverage
   206ms  ok         dependency pin guard
   155ms  ok         format changed files
   1.98s  ok         config docs baseline
   1.32s  ok         plugin boundaries
   3.33s  ok         wrapper shadowing
   356ms  ok         package patch guard
   469ms  ok         test temp creation report (warning-only)
  17.28s  ok         core tsgo graph boundary
   3.75s  ok         typecheck core
   4.63s  ok         typecheck core tests
   4.94s  ok         coercion helper declaration guard
   6.99s  ok         deprecated API usage
  30.89s  ok         dead export scan (skip with OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1)
  18.10s  ok         lint core changed files
    32ms  ok         native state schema version guard
  38.11s  ok         database-first legacy-store guard
   312ms  ok         media download helper guard
   5.57s  ok         runtime sidecar loader guard
   4.53s  ok         runtime import cycles
   462ms  ok         webhook body guard
   5.37s  ok         pairing store guard
   5.07s  ok         pairing account guard
CHECK_EXIT=0

$ git diff --check
(no output)
DIFF_CHECK_EXIT=0
Mutation checks: the three red summaries

Each mutation was applied to a copy of the shipped source, measured, then reverted from that copy;
shasum -a 256 on the restored files matched the pre-mutation copy, and the suites were re-run
green afterward.

1. Admitted-run gate reverted to session-key-only resolution. resolveSwarmCollectorToolContext
drops the admittedRunId requirement and the ownsAdmittedCollectorRun test, resolving the
collector contract from the child session key alone, which is what the previous revision did.

$ node scripts/run-vitest.mjs src/gateway/tool-resolution.swarm-collector.test.ts
 × collector contract is bound to the admitted collector run > serves the plain surface to a session-scoped attach client on the same session
 × collector contract is bound to the admitted collector run > writes nothing for an attach client, because the result tool is never listed
 × collector contract is bound to the admitted collector run > withholds the contract from a run-bound grant for a different run
 × collector contract is bound to the admitted collector run > leaves the http surface exactly as it is without a collector session
 × collector contract is bound to the admitted collector run > does not withhold requester-only tools from a collector session on the http surface
 × collector contract is bound to the admitted collector run > keeps operator tool policy authoritative for a collector session on the http surface
 × collector write authority is re-checked before persistence > rejects the result when the caller stops owning the admitted collector run
 × collector tools behind the loopback grant allowlist > withholds structured_output from a run-less context at the loopback entry point
 Test Files  1 failed (1)
      Tests  8 failed | 14 passed (22)

$ node scripts/run-vitest.mjs src/gateway/mcp-http.test.ts
 × collector result tool across the loopback MCP boundary > gives an attach grant on the collector's session no result tool to list or call
 × collector result tool across the loopback MCP boundary > refuses the collector's own call when the record stops owning the admitted run
 Test Files  1 failed (1)
      Tests  2 failed | 122 passed (124)

2. Pre-persistence re-check removed. Only the assertCollectorWriteAuthority() call inside
onStateChange is deleted; the resolve-time gate stays.

$ node scripts/run-vitest.mjs src/gateway/tool-resolution.swarm-collector.test.ts
 × collector write authority is re-checked before persistence > rejects the result when the grant is revoked between construction and execute
 × collector write authority is re-checked before persistence > rejects the result when the caller stops owning the admitted collector run
 Test Files  1 failed (1)
      Tests  2 failed | 20 passed (22)

$ node scripts/run-vitest.mjs src/gateway/mcp-http.test.ts
 × collector result tool across the loopback MCP boundary > refuses the collector's own call when the record stops owning the admitted run
 Test Files  1 failed (1)
      Tests  1 failed | 123 passed (124)

3. The server's post-hook liveness check removed, to show which layer catches a revocation that
lands inside the hook. The write still does not land; it is refused one layer lower, by the
re-check this PR adds.

$ node scripts/run-vitest.mjs src/gateway/mcp-http.test.ts -t "revoked inside the before-tool hook"
 × collector result tool across the loopback MCP boundary > refuses the collector's own call when its grant is revoked inside the before-tool hook
   Expected: "Tool call authorization expired"
   Received: "Failed to persist structured_output: collector run grant is no longer active"
 Test Files  1 failed (1)
      Tests  1 failed | 123 skipped (124)

CI note. Two earlier heads of this branch failed openclaw/ci-gate, each on a single vitest shard, and in both cases on a test in a file this PR does not touch. Both of those tests have since been fixed upstream, and this head is rebased onto a2b2391e353, which carries both fixes.

  1. Head 3fd85d7746, twice, on src/agents/sessions/settings-storage.test.ts > FileSettingsStorage > preserves independent concurrent first writes to global settings (and the project-settings sibling), failing expect(firstSettled).toBe(false). That assertion was added by test(agents): coordinate settings lock contention #146949 (merged 11:24:50Z) and removed again by fix(test): avoid settings lock writer startup timeouts #147029 (merged 13:28:29Z the same day). Both runs were tested against merge base bc6b662e042, which is test(agents): coordinate settings lock contention #146949 itself, so they landed inside that two hour window. The runner log records the tested merge directly:
HEAD is now at 5b956130 Merge 3fd85d77463... into bc6b662e0421694fcfcb1d71112486a0560b93c9
  1. Head c39df3a1596, once, on src/daemon/systemd.test.ts > readSystemdServiceRuntime > passes a kill-backed timeout to systemctl when a read deadline is set, failing AssertionError: expected 1233 to be 1234. The test asserted an exact opts.timeout for every execFile call while each call draws from a decaying deadline budget, so it failed whenever at least 1 ms elapsed between calls. fix(test): accept remaining systemd timeout budget #147117 (merged 15:24:59Z) replaced that with toBeGreaterThan(0) / toBeLessThanOrEqual(1234). That run was otherwise fully green at 164 passing checks, including CodeQL and every Security High lane.

Neither test is in this PR's diff, which is confined to Gateway tool resolution, the swarm collector tool contract, and the CLI runtime allowlist.

Live behavior proof

What commit these arms ran on. Every A row below was measured on this head itself,
9ce1a595aca. The reproduction host no longer rebuilds the commit from a patch file: it fetches
this exact object and checks it out, so git rev-parse HEAD in the repro worktree prints
9ce1a595aca78bd49e8948768300255668030c83, on parent a2b2391e353, 11 files and +865/-28, with a
clean tree. The image bakes that sha at /image-commit, and every receipt below carries it. There
is no patch-id stand-in and no predecessor caveat left in these rows: the revoked-grant arm,
which earlier revisions had to measure on a patch-identical predecessor, was re-measured here on
this head. base was built from an unchanged commit and was not re-run; its rows are from the
first pass. The A+B rows are the earlier merge of the patch-identical predecessor into the
companion yield branch and were not re-run; the merge of this head with that branch's current head
5ce5b0a223 was re-checked and still applies cleanly with no conflicts, giving 4783ef45f22.

Executed against a real claude-cli child (Claude Code 2.1.270) driving a local model, in
containers built from the base commit and from this branch's head. Arms are driven
over the Gateway POST /tools/invoke endpoint (sessions_spawn, then agents_wait), so no
parent model judgment is in the control path. Receipt fields come from agents_wait, the
subagents recent/tasks projections, and the state SQLite subagent_runs.payload_json.
Every collector arm runs a CLI child spawned by sessions_spawn, so every tool list and every
recorded result in this section came from that child's own run over its run-bound loopback MCP
grant, except where a heading below says otherwise. Four arms have their own headings: a
session-scoped attach client, a collector grant that is revoked before it is used, an operator
http-surface negative arm, and a gateway restart carried out while a schema-backed collector
session was persisted and in flight.

Environment. node:24-bookworm / Node v24.21.0; Claude Code 2.1.270; child model ref
claude-cli/qwen3-coder-next-mlx served by a local LM Studio over its Anthropic-compatible API;
one gateway per container with an isolated OPENCLAW_STATE_DIR, gateway.auth.mode: "token",
no channels. No stub CLI: this is the shipped claude-cli backend launching the real Claude Code
binary. Claude Code is pointed at the local endpoint through its user settings.json env block,
because CLAUDE_CLI_CLEAR_ENV strips ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN from the
spawned process environment by design.

Arm Commit Run id agents_wait elapsed
D1 before 9717a7635a0 (base) bfb20d9b failed, schemaError: "structured_output was not called", result: "gamma" 28.2 s
D1 after 9ce1a595aca (this head) 63df6cad done, structured: {"result":"gamma"} 107.2 s
D1 on A+B merged 29b64e35ed4 (predecessor merge, not re-run) 411d65db done, structured: {"result":"gamma"} 82.4 s
Attach client arm, its own collector child 9ce1a595aca (this head) 8cb6199e done, structured: {"result":"gamma"} 84.5 s
Revoked grant arm, collector killed mid-run 9ce1a595aca (this head) 1d27f7b8 run ends terminal/error; grant then answers 401 unauthorized 102.9 s (pair)
Revoked grant arm, collector that ran to completion 9ce1a595aca (this head) 71b565d7 done, structured: {"result":"gamma"}, then grant answers 401 unauthorized 102.2 s
Operator HTTP negative, its own collector child 9ce1a595aca (this head) ea70dfce forged writes refused 404; the child's own submission done, structured: {"result":"delta"} 89.2 s
Restart recovery, collector spawned after the restart 9ce1a595aca (this head) 48fe5641 done, structured: {"result":"gamma"} 90.1 s
Restart recovery, run interrupted by the restart 9ce1a595aca (this head) a4f41ebf failed, error: "subagent run lost active execution context" 59.7 s wait
Positive control (collector, no schema) base / A 9ce1a595aca / A+B 90f8c022 / bef8b4f4 / 7e52aa85 done, result: "gamma" on all three 27-30 s
Negative control (non-collector child) A+B 29b64e35ed4 12042001 n/a, polled to done 35.2 s

Both D1 arms spawn the same call: sessions_spawn({ task: "Reply with the single word gamma.", collect: true, outputSchema: { type: "object", properties: { result: { type: "string" } }, required: ["result"] }, model: "claude-cli/qwen3-coder-next-mlx" }). The operator HTTP negative
arm spawns the same call with the task word delta, so its own recorded result is distinguishable
from every other arm's and from the value the forged operator request tries to submit.

That arm carries both halves at once. The child's own submission over its run-bound loopback grant
was accepted and recorded as structured: {"result":"delta"}, while every forged write of the same
tool over the operator http surface was refused with 404 Tool not available: structured_output
and no forged value reached any durable row.

Before (base), run bfb20d9b-aa6d-4e18-ae75-3986e47467b5:

{"completed":[{"runId":"bfb20d9b-...","status":"failed","result":"gamma",
"schemaError":"structured_output was not called","label":"repro-d1-before"}],"pending":[]}

while subagents.recent reports status: "done" and subagents.tasks reports
status: "completed" for the same run - the requester is told the run failed, both status
surfaces say it succeeded.

After (this head, 9ce1a595aca), run 63df6cad-fd71-4bd1-8383-9634d2dec095:

{"completed":[{"runId":"63df6cad-...","status":"done","result":"gamma",
"structured":{"result":"gamma"},"schemaError":null}],"pending":[]}

// durable subagent_runs row
"collectorCompletion": {"status":"done","structured":{"result":"gamma"},
                        "usage":{"inputTokens":37733,"outputTokens":0}}
"execution": {"status":"terminal","outcome":{"status":"ok","elapsedMs":107122}}

Child tool list, read from Claude Code's own session transcript (~/.claude/projects/*/*.jsonl
inside the container), per child turn rather than aggregated:

Image Child turn mcp__openclaw__structured_output mcp__openclaw__sessions_yield
base 9717a76 collector with outputSchema (d1-before) absent present
A 9ce1a59 collector with outputSchema (d1-after) present absent
A 9ce1a59 collector with outputSchema (attach client arm) present absent
A 9ce1a59 collector with outputSchema (operator HTTP negative arm) present absent
A 9ce1a59 collector with outputSchema, one turn each side of a gateway restart present absent
A 9ce1a59 collector with outputSchema (revoked grant arm, both runs) present absent
A+B 29b64e3 collector with outputSchema (d1-AB) present absent
base 9717a76 collector, no schema (control/d2) absent present
A 9ce1a59 collector, no schema (control-A) absent absent
A+B 29b64e3 collector, no schema (control-AB) absent absent
A+B 29b64e3 collector, no schema, told to yield (d2-AB) absent absent
A+B 29b64e3 non-collector child (plain-AB) absent present

On base a schema-less collector keeps sessions_yield; on A and on A+B it does not, while
structured_output stays absent for it either way because the transport is still schema-gated.
The non-collector row is the negative control: the withholding is scoped to collector runs, not
applied to every child on the image. Tool counts agree: 29 names for a turn that keeps
sessions_yield, 28 for a schema-less collector on A, 29 again for a schema-backed collector with
structured_output swapped in.

mcp__openclaw__ask_user and mcp__openclaw__sessions_send cannot be measured in this harness:
the reproduction gateway does not offer either tool on any image, base included (its child tool
surface is 29 names and contains neither), so their absence in these rows is not evidence. The
withholding of those two is covered by omits interactive and pausing tools for a gateway collector child and withholds requester-only tools from a collector child that requested no schema in the resolver test, not by this run.

On A the child calls the tool and the result is recorded: agents_wait returns
structured: {"result":"gamma"} with schemaError: null, and the durable subagent_runs row
carries the same object under collectorCompletion.structured. The raw tool_use /
tool_result pairs were captured this time, from the operator HTTP negative arm's own child
transcript, and they also show the validation retry path:

tool_use    mcp__openclaw__structured_output  {"result": "delta"}
tool_result "structured_output validation failed: <root>: must be object. Retry once with a
             corrected final result."
tool_use    mcp__openclaw__structured_output  {"result": {"result": "delta"}}
tool_result [{"type":"text","text":"{\n  \"status\": \"recorded\"\n}"}]

That is the same session key, on the same gateway, in the same wall-clock window in which four
operator POST /tools/invoke requests naming structured_output were refused. See below.

What this run established. The schema-less rows above are what exposed the gap an earlier
revision of this branch closed. resolveSwarmCollectorToolContext() returned undefined for a run
with no outputSchema, so on the Gateway path a schema-less collector was not treated as a
collector at all and kept sessions_yield; only schema-backed collectors lost it. The resolver
keys collector identity on the registry's collect flag, matching the embedded runner, so every
collector child on the loopback path loses sessions_yield, ask_user, and sessions_send, and
only a schema-backed one receives structured_output. The A and A+B arms confirm the live half of
that: control-A, control-AB, and d2-AB are all schema-less collectors and none of them is
offered sessions_yield, while the schema-backed rows and both D1 arms are unchanged and the
non-collector child still has the tool.

Session-scoped attach client cannot obtain or call the result tool

This is the arm the admission gate exists for, and it has a before and an after on the same
harness. A schema-backed collector was spawned and left running, so its registry record was still
an open collector. An attach grant was then minted for that child's session key with
openclaw attach --session <child key> --print-config --ttl 600000, which performs the
attach.grant gateway call at scope operator.admin. The returned mcpConfig gives the loopback
MCP URL directly and carries only an Authorization header, with no
x-openclaw-cli-capture-key; that was confirmed on both images. The loopback MCP was then driven
with that bearer and nothing else. No x-session-key or other context header was sent.

POST http://127.0.0.1:<port>/mcp
Authorization: Bearer <ATTACH_GRANT_TOKEN>
Content-Type: application/json
Accept: application/json, text/event-stream

{"jsonrpc":"2.0","id":2,"method":"tools/call",
 "params":{"name":"structured_output","arguments":{"result":{"result":"forged"}}}}

Before, on the previous head 34e32a8b8aa, collector run 006335e3:

// tools/list -> 27 tools
"structured_output": present      "sessions_yield": absent

// tools/call
{"content":[{"type":"text","text":"{\n  \"status\": \"recorded\"\n}"}]}   // isError: false

// agents_wait for that run, and the durable row
{"status":"done","result":"gamma","structured":{"result":"forged"},"schemaError":null}
"collectorCompletion": {"status":"done","structured":{"result":"forged"}}

The child's own answer was gamma. A client that never ran the task overwrote the recorded result
with forged, and that is what the requester received and what the durable row kept.

After, on this head 9ce1a595aca, collector run 8cb6199e:

// tools/list -> 27 tools
"structured_output": absent       "sessions_yield": present

// tools/call
{"content":[{"type":"text","text":"Tool not available: structured_output"}],"isError":true}

// agents_wait for that run, and the durable row
{"status":"done","result":"Task complete. The subagent has recorded `gamma` as the final result.",
 "structured":{"result":"gamma"},"schemaError":null}
"collectorCompletion": {"status":"done","structured":{"result":"gamma"}}
"execution": {"status":"terminal","outcome":{"status":"ok","elapsedMs":91777}}

The grant itself was inspected before it was used: its mcpConfig lists exactly one header name,
Authorization, and carries no x-openclaw-cli-capture-key.

Both lists have 27 names; what changes is which tool occupies the slot. On the old head the attach
client inherited the collector contract, so it received structured_output and lost
sessions_yield. On this head it is resolved as an ordinary session client, so it keeps
sessions_yield and is never offered the result tool. That is the gate keying on params.runId,
which an attach grant does not carry, rather than on the session key, which it does. The literal
string forged appears in no subagent_runs payload on this head, checked for the target run and
across every row.

Revoking the collector's grant writes nothing, and where the refusal lands

The revoked-during-hook window is covered by tests, not by this live run. It is covered twice:
by the write-authority unit tests on the tool's own execute path, and, as of this head, at the
real MCP boundary, where src/gateway/mcp-http.test.ts revokes the collector's grant from inside
the awaited before-tool hook of a live tools/call and gets Tool call authorization expired
with an unchanged registry record. Delete the server's post-hook check and that same boundary call
is refused one layer lower, by the pre-persistence re-check this PR adds, with
Failed to persist structured_output: collector run grant is no longer active.

Live, the revocation was observed one layer earlier than either of those checks, and nothing
below should be read as reproducing the in-hook window. Two things prevent driving that window
from outside a container: no gateway RPC revokes a collector's client grant, and the one lever
reachable from the operator surface, subagents { action: "cancel" }, is refused for a run
spawned this way with {"status":"forbidden","error":"Task outside session tree."}.

What is reproduced live is the same object under test, the collector's own run-bound client
grant
, captured rather than simulated. The child claude process was located in the container,
its --mcp-config and its OPENCLAW_MCP_TOKEN / OPENCLAW_MCP_CLI_CAPTURE_KEY values were read
from /proc/<pid>, and the resulting headers were replayed against the loopback MCP. Unlike the
attach grant, this client config carries both Authorization and
x-openclaw-cli-capture-key, and while the run is live its tools/list returns 29 names with
structured_output present and sessions_yield absent. It is the collector's real writer.

Variant Run How the grant was revoked tools/call structured_output after Durable row
Mid-run 1d27f7b8 SIGKILL to the collector child, so run teardown revokes the grant HTTP 401, {"error":"unauthorized"} terminal / error, Claude Code process exited with signal SIGKILL, no collectorCompletion
After teardown 71b565d7 ordinary run teardown, after the child's own result was recorded HTTP 401, {"error":"unauthorized"} terminal / ok, collectorCompletion.structured: {"result":"gamma"}, unchanged

tools/list on the same grant after revocation also returns 401, and the forged value appears in
no subagent_runs payload in either variant. So a revoked collector grant writes nothing, which
is the property the arm is for.

The detail worth recording is where the refusal happens. Neither of the two tool-level texts
this branch can produce, Tool call authorization expired from the server's post-hook
authorizeToolCall and Failed to persist structured_output: collector run grant is no longer active from the pre-persistence re-check, appears in these receipts. Once the grant row is gone
the loopback MCP rejects the request at the transport auth layer with a bare 401, one layer before
either check can run, and no write occurs. Both of those texts are produced by tests instead: the
first over the real loopback MCP server, the second over that same server once the first check is
removed, and both also on the tool's own execute path.

Operator HTTP surface cannot submit results

This is the third authority-chain arm. It does not exercise operator submission of a result,
because on this head the writer is not present on the operator transport at all, so there is
nothing to submit through and nothing to reject.

On image A at 9ce1a595aca, one schema-backed collector was spawned over the operator surface
with the task word delta, and while it was still running, four POST /tools/invoke requests
named structured_output against it with the same gateway bearer token that had just been
accepted for sessions_spawn. Two field spellings were used, because the endpoint reads
params.input.name ?? params.input.tool, and both the child's session key and the parent's were
tried, mid-run and again after the run had gone terminal.

POST /tools/invoke
Authorization: Bearer <GATEWAY_TOKEN>
Content-Type: application/json

{"tool":"structured_output","args":{"result":{"result":"forged"}},
 "sessionKey":"agent:main:subagent:<CHILD_UUID>"}
HTTP/1.1 404 Not Found

{"ok":false,"error":{"type":"not_found","message":"Tool not available: structured_output"}}

All four attempts returned that identical status and body:

Attempt Name field Target session Phase Status Error
1 tool collector child mid-run 404 not_found, Tool not available: structured_output
2 name collector child mid-run 404 not_found, Tool not available: structured_output
3 tool parent main mid-run 404 not_found, Tool not available: structured_output
4 tool collector child after terminal 404 not_found, Tool not available: structured_output

The transport itself was working. Two control calls with the same bearer token and the same
child session key succeeded in the same window: {"tool":"subagents","args":{"action":"list"}}
returned 200 ok: true, and {"tool":"sessions_list","args":{}} returned 200 ok: true. The
404 is the tool being absent from that surface's resolved list, not an auth or session-target
failure.

The child's own submission went through at the same time. Run
ea70dfce-c819-4ae6-b8fe-a0c6a4d636af returned agents_wait done with
structured: {"result":"delta"} and schemaError: null at 89.2 s, and its durable row carries
collectorCompletion: {"status":"done","structured":{"result":"delta"}} with
execution.outcome.status: "ok". So the same tool name is writable by the collector's own
run-bound grant and refused on the operator surface, in the same run. The tool_use /
tool_result pair quoted above is from a child transcript on this image.

Nothing forged was persisted. The literal string forged appears in no subagent_runs
payload in that container's state database, checked both for the target run and across every row.

The same four requests against the base image 9717a76 also returned 404 with the identical
body, so this is not something the branch newly closed on the operator surface; it was never open
there. That base child, spawned with the same schema, separately reproduced D1: agents_wait
failed, result: "delta", schemaError: "structured_output was not called".

Restart with a persisted schema-backed collector session

Image A at 9ce1a595aca, with /state on a persistent Docker volume so the state database
outlives any single gateway process. The arm spawns a schema-backed collector, stops the gateway
while that child is still running, starts a new gateway on the same /state, and then observes.

t Event
+0 s sessions_spawn schema-backed collector, run f161a1e4, accepted
+2 s durable row present, execution.status: "running"; SIGTERM sent to the gateway
+2 to +14 s the gateway does not exit. POST /tools/invoke answers 503 while it drains the in-flight run
+14 s SIGKILL sent, the way docker stop escalates
+15 s process gone; probe now fails to connect; the child claude process survives as an orphan; durable row still running
+20 s new gateway started on the same /state, different pid; it prints [gateway] ready 5.1 s after the start call
+84 s agents_wait on the interrupted run returns after 59.6 s

What recovery did with the interrupted run. It settled it as an error rather than relaunching
it. agents_wait returned status: "failed", error: "subagent run lost active execution context", schemaError: "structured_output was not called"; the durable row moved to
execution.status: "terminal" with outcome.status: "error" carrying that message, and
interruptionReason stayed null. The child could not survive the restart: it is a subprocess of
the gateway, and although the orphan kept running for about sixteen more seconds it had no live
run context to report into.

The tool surface is not lost. That is the compatibility question, and the answer is no. Both
child turns in this container, the one before the restart and the one after it, show 29
mcp__openclaw__* names with mcp__openclaw__structured_output present and
mcp__openclaw__sessions_yield absent, which is the same contract the pre-restart turn had.
The restarted gateway's log contains no line matching collector, structured_output,
registry, restore, recover, interrupt, grant or swarm around either spawn.

A fresh collector after the restart works. One was spawned, 65.4 s after [gateway] ready,
run 48fe5641. It returned agents_wait done with structured: {"result":"gamma"} and
schemaError: null at 90.1 s, with collectorCompletion.structured matching and
execution.outcome.status: "ok" (elapsedMs: 89848).

This is worth stating precisely, because an earlier run of this arm on an older head saw its
first post-restart collector come back failed with
schemaError: "structured_output was not called" and only the retry succeed. That did not
recur here, and it did not recur on the patch-id equal predecessor either, where three
post-restart collectors spawned 65.1 s, 163.5 s and 280.4 s after ready all returned done, which
rules out a settling window. The earlier failure was the child declining to call an offered tool,
not the tool going missing across a restart. The transcript on this head shows the shape directly,
including the validation retry that a single-call run would not survive:

tool_use    mcp__openclaw__structured_output  {"result":"gamma"}
tool_result "structured_output validation failed: <root>: must be object. Retry once with a
             corrected final result."     // is_error: true
tool_use    mcp__openclaw__structured_output  {"result":{"result":"gamma"}}
tool_result {"status":"recorded"}

Not verified here: ask_user and sessions_send are not offered by the reproduction gateway
on any image, so their withholding is proven by the resolver tests rather than by a live
transcript. codex-cli and gemini-cli reach the same resolver but were not exercised backend by
backend. The cross-run grant arm was not run: no second concurrent collector was spawned to borrow
the first one's grant. A revocation landing inside the awaited before-tool hook, and with it both
of the tool-level refusal texts, is covered by tests rather than by this run: at the real loopback
MCP server as well as on the tool's own execute path. See the revoked-grant subsection above for
what the live arms do and do not reach. The revoked-grant pair, which earlier revisions could only
measure on a patch-id equal predecessor, was re-measured on 9ce1a595aca for this revision. Two
things in this section are still not on this head and say so where they appear: the attach-client
"before" half, which by construction has to run on the old head 34e32a8b8aa, and the A+B rows,
which are the earlier predecessor merge and were not re-run. The LM Studio build version is not
exposed on the API surface used and is not recorded.

Reproducing this proof

Everything below is what ran, with two substitutions: <GATEWAY_TOKEN>, <LM_STUDIO_TOKEN>. Any
Anthropic-compatible local endpoint works for the child; this run used LM Studio on port 1234.

1. Image. One per commit: base 9717a7635a0ee83167568038e2c123943968e19d, A
9ce1a595aca78bd49e8948768300255668030c83, B 32c4f145bed14237ab2a64d868f223cf2b46ebf6, A+B merge
of the two. Check each out into ~/repro/wt/<arm>/. B sits on upstream main
4f6379cafeb6b53beb5e7ceff7de2d40535318c0, and the A+B merge is produced locally by merging A
into B, which is clean and needs no conflict resolution and yields
29b64e35ed46b0a4e9aff0583375fd269ea906a5. Applying A and B as git format-patch files reproduces
both shas exactly, as long as git am is given the original committer identity and date; the author
identity and date already travel inside the patch.

GIT_COMMITTER_NAME='<original committer name>' \
GIT_COMMITTER_EMAIL='<original committer email>' \
GIT_COMMITTER_DATE='<original committer date, RFC 2822>' \
  git am --keep-cr ~/repro/patches/A.patch
git rev-parse HEAD   # 9ce1a595aca78bd49e8948768300255668030c83

A is 11 files, +865/-28 against 9717a7635a0.

FROM node:24-bookworm
ARG REPRO_COMMIT=unknown
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0
ENV PNPM_HOME=/pnpm
ENV PATH=/pnpm:$PATH
RUN apt-get update && apt-get install -y --no-install-recommends \
      git jq sqlite3 curl ca-certificates python3 make g++ && rm -rf /var/lib/apt/lists/*
RUN corepack enable && node -v
WORKDIR /app
COPY . /app
RUN pnpm config set store-dir /pnpm/store --global && pnpm install --frozen-lockfile
RUN pnpm build
RUN npm i -g @anthropic-ai/[email protected] && claude --version
RUN printf '%s\n' "$REPRO_COMMIT" > /image-commit && node -v > /image-node
ENV OPENCLAW_STATE_DIR=/state
LABEL repro.commit="$REPRO_COMMIT"

The commit is baked at /image-commit and Node at /image-node, so every receipt carries both.
(The original build left Claude Code unpinned and resolved 2.1.270; the pin reproduces that.)

SHA=$(git -C ~/repro/wt/A rev-parse HEAD)
docker build -f ~/repro/wt/A/Dockerfile.repro -t openclaw-repro:A \
  --build-arg "REPRO_COMMIT=$SHA" ~/repro/wt/A

2. Config. ~/repro/incontainer/openclaw.json, copied to /state/openclaw.json at boot.
sessions_spawn is on the Gateway HTTP deny list by default, which gateway.tools.allow overrides.

{ "logging": { "level": "debug", "consoleLevel": "info" },
  "gateway": { "port": 18789, "mode": "local",
    "auth": { "mode": "token", "token": "<GATEWAY_TOKEN>" },
    "tools": { "allow": ["sessions_spawn"] } },
  "models": { "providers": { "lmstudio": {
    "baseUrl": "http://host.docker.internal:1234/v1", "apiKey": "<LM_STUDIO_TOKEN>",
    "api": "openai-completions",
    "models": [{ "id": "qwen3-coder-next-mlx", "name": "Qwen3 Coder Next",
      "input": ["text"], "contextWindow": 262144, "maxTokens": 16384,
      "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } }] } } },
  "agents": { "defaults": { "model": "lmstudio/qwen3-coder-next-mlx", "timeoutSeconds": 900,
    "modelPolicy": { "allow": ["lmstudio/qwen3-coder-next-mlx", "claude-cli/qwen3-coder-next-mlx"] },
    "models": { "claude-cli/qwen3-coder-next-mlx": {} } } },
  "tools": { "swarm": { "enabled": true, "waitTimeoutSecondsMax": 600 } } }

Claude Code cannot be aimed at that endpoint through process env: CLAUDE_CLI_CLEAR_ENV strips
ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN before launch. Use user settings instead, which the
backend loads via --setting-sources user.

// /root/.claude/settings.json, mode 0600. Also write /root/.claude.json as
// {"hasCompletedOnboarding":true,"bypassPermissionsModeAccepted":true} so the CLI does not prompt.
{ "env": {
  "ANTHROPIC_BASE_URL": "http://host.docker.internal:1234",
  "ANTHROPIC_AUTH_TOKEN": "<LM_STUDIO_TOKEN>",
  "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_TELEMETRY": "1",
  "DISABLE_AUTOUPDATER": "1", "DISABLE_ERROR_REPORTING": "1", "DISABLE_BUG_COMMAND": "1"
} }

3. Run.

printf '%s\n' 'OPENCLAW_GATEWAY_TOKEN=<GATEWAY_TOKEN>' 'LM_TOKEN=<LM_STUDIO_TOKEN>' \
  'LM_ANTHROPIC_BASE_URL=http://host.docker.internal:1234' 'OPENCLAW_STATE_DIR=/state' \
  > ~/repro/.env.A && chmod 600 ~/repro/.env.A
# The port is not published; arms run inside via docker exec. Add -p 18789:18789 to drive from
# the host, and on Linux --add-host=host.docker.internal:host-gateway.
docker run -d --name repro-A --env-file ~/repro/.env.A \
  -v ~/repro/incontainer:/repro:ro -v ~/repro/out/A:/out \
  openclaw-repro:A bash /repro/boot.sh
# boot.sh writes the two files above, then starts the gateway and polls sessions_list until 200:
cd /app && node /app/openclaw.mjs gateway run --port 18789 </dev/null >/out/gateway.log 2>&1 &

4. Drive. Fixed JSON over the tool-invoke API, so no parent model is in the control path. Run
these inside the container (docker exec -it repro-A bash).

inv() { curl -s -X POST http://127.0.0.1:18789/tools/invoke \
  -H "Authorization: Bearer <GATEWAY_TOKEN>" -H 'Content-Type: application/json' --data-binary @-; }

# D1 arm. A collector spawned from this path must pass an explicit groupId, or the call fails with
# "sessions_spawn collect=true requires a requesting run id when groupId is omitted".
inv <<'JSON'
{"tool":"sessions_spawn","sessionKey":"main","args":{
  "task":"Reply with the single word gamma.",
  "collect":true,
  "outputSchema":{"type":"object","properties":{"result":{"type":"string"}},"required":["result"]},
  "label":"repro-d1","model":"claude-cli/qwen3-coder-next-mlx",
  "runtime":"subagent","groupId":"g-d1"}}
JSON

# Positive control: same call with no outputSchema.
inv <<'JSON'
{"tool":"sessions_spawn","sessionKey":"main","args":{
  "task":"Reply with the single word gamma.",
  "collect":true,"label":"repro-control","model":"claude-cli/qwen3-coder-next-mlx",
  "runtime":"subagent","groupId":"g-control"}}
JSON

# Take runId from each spawn result, then wait and read the projections.
inv <<'JSON'
{"tool":"agents_wait","sessionKey":"main","args":{"ids":["<RUN_ID>"],"timeoutSeconds":120}}
JSON
inv <<'JSON'
{"tool":"subagents","sessionKey":"main","args":{"action":"list"}}
JSON

4a. Operator HTTP negative arm. Spawn the D1 arm again with the task word delta and
"label":"repro-http-negative", take childSessionKey from the spawn result, then fire these
while the child is still running. Every one must answer 404 with
{"ok":false,"error":{"type":"not_found","message":"Tool not available: structured_output"}}.

# both field spellings, because the endpoint reads params.input.name ?? params.input.tool
inv <<'JSON'
{"tool":"structured_output","sessionKey":"<CHILD_SESSION_KEY>",
 "args":{"result":{"result":"forged"}}}
JSON
inv <<'JSON'
{"name":"structured_output","sessionKey":"<CHILD_SESSION_KEY>",
 "args":{"result":{"result":"forged"}}}
JSON
# and aimed at the parent session key instead of the child's
inv <<'JSON'
{"tool":"structured_output","sessionKey":"main","args":{"result":{"result":"forged"}}}
JSON

# transport control: same token, same child session key, a tool that IS on this surface.
# Both must answer 200 with "ok": true.
inv <<'JSON'
{"tool":"subagents","sessionKey":"<CHILD_SESSION_KEY>","args":{"action":"list"}}
JSON
inv <<'JSON'
{"tool":"sessions_list","sessionKey":"<CHILD_SESSION_KEY>","args":{}}
JSON

# then let the child finish, and confirm nothing forged was written
sqlite3 /state/state/openclaw.sqlite "SELECT payload_json FROM subagent_runs;" | grep -c forged

Repeat the first request once more after agents_wait has returned, to cover the terminal case.

4b. Restart with a persisted collector session. Start the container with /state on a named
volume (-v repro-state:/state) so the database outlives the process, then:

# 1. spawn the D1 arm, and about two seconds later stop the gateway from inside the container
PID=$(grep -l openclaw-gateway /proc/*/cmdline | cut -d/ -f3)   # the process renames its title
kill -TERM "$PID"
# SIGTERM drains the in-flight run: /tools/invoke answers 503 and the process stays up.
# Escalate the way docker stop does.
sleep 12 && kill -KILL "$PID"

# 2. start a new gateway on the same /state, and wait for the first 200
cd /app && setsid node /app/openclaw.mjs gateway run --port 18789 \
  </dev/null >>/out/gateway2.log 2>&1 &

# 3. read the interrupted run back, then spawn a fresh schema-backed collector and wait
inv <<'JSON'
{"tool":"agents_wait","sessionKey":"main","args":{"ids":["<PRE_RESTART_RUN_ID>"],"timeoutSeconds":90}}
JSON

Expect the interrupted run to settle failed with error: "subagent run lost active execution context", and the fresh collector to return done with its structured result. Re-run the tool
scan from step 5 afterwards: the post-restart collector turn must still show
mcp__openclaw__structured_output present and mcp__openclaw__sessions_yield absent. A
post-restart collector can still come back structured_output was not called if the child simply
does not call the tool; check that turn's tool list before reading it as a resolution failure.

4c. Session-scoped attach client. Spawn the D1 arm and leave it running, then mint an attach
grant for the child's session key and drive the loopback MCP with it. Read the child session key
from the sessions_spawn result or from subagents { action: "list" }.

# 1. mint the grant; this performs attach.grant at scope operator.admin and prints the token,
#    the written MCP config path, and the launch line, without revoking afterwards
node /app/openclaw.mjs attach --session "agent:main:subagent:<CHILD_UUID>" \
  --print-config --ttl 600000

# the printed configPath holds mcpServers.openclaw.url, which is the loopback MCP endpoint:
#   http://127.0.0.1:<port>/mcp
# and mcpServers.openclaw.headers, which carries Authorization only, with no capture-key header

# 2. list, then call by name. Send no x-session-key or other context header.
MCP=http://127.0.0.1:<PORT>/mcp
curl -s -X POST "$MCP" \
  -H "Authorization: Bearer <ATTACH_GRANT_TOKEN>" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

curl -s -X POST "$MCP" \
  -H "Authorization: Bearer <ATTACH_GRANT_TOKEN>" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"structured_output",
       "arguments":{"result":{"result":"forged"}}}}'

Expect tools/list to omit structured_output and to include sessions_yield, and tools/call
to return {"content":[{"type":"text","text":"Tool not available: structured_output"}], "isError":true}. Then let the child finish: agents_wait must return the child's own result, and
forged must appear in no subagent_runs payload. On a build without the admission gate the same
two requests return the tool and {"status":"recorded"}, and the durable row ends up holding
forged, which is the before half of the pair.

4d. Revoked collector grant. This one uses the collector's own run-bound client grant, not an
attach grant. Spawn the D1 arm, then read the live grant off the child process inside the
container.

# find the child claude process and read its loopback MCP credentials
for p in /proc/[0-9]*; do
  tr '\0' ' ' < "$p/cmdline" | grep -q claude || continue
  tr '\0' '\n' < "$p/environ" | grep -q '^OPENCLAW_MCP_TOKEN=' || continue
  echo "pid=${p#/proc/}"
  tr '\0' '\n' < "$p/cmdline" | grep -A1 -x -- --mcp-config   # path to the MCP config
done
# the config's headers carry BOTH Authorization and x-openclaw-cli-capture-key, with
# ${OPENCLAW_MCP_TOKEN} and ${OPENCLAW_MCP_CLI_CAPTURE_KEY} substituted from that process env

With those headers, tools/list returns the collector contract: structured_output present,
sessions_yield absent. Now revoke the grant by ending the run, either by killing the child so
run teardown revokes it, or simply by letting the run finish, and replay the same tools/call
structured_output request. Expect the loopback MCP to answer 401 and the durable row to be
unchanged: no collectorCompletion at all for the killed run, and the child's own result for the
completed one. Note that subagents { action: "cancel" } will not do this from the operator
surface; it answers {"status":"forbidden","error":"Task outside session tree."}.

5. Observe. The durable row carries the verdict independently of the wait. The child's tool list
comes from Claude Code's own transcripts, one file per child turn, so rows are per turn rather than
aggregated; the scan catches both the offered tool list and actual tool_use blocks.

sqlite3 -json /state/state/openclaw.sqlite \
  "SELECT run_id, payload_json FROM subagent_runs WHERE run_id='<RUN_ID>';" \
  | jq '.[0].payload_json | fromjson | {status: .execution.status,
        outcome: .execution.outcome, pauseReason, collectorCompletion}'

for f in /root/.claude/projects/*/*.jsonl; do echo "== $f"
  grep -o 'mcp__openclaw__[A-Za-z0-9_]*' "$f" | sort -u | tr '\n' ' '; echo; done

Read out whether mcp__openclaw__structured_output and mcp__openclaw__sessions_yield are present
per file, plus the total mcp__openclaw__* count.

6. Expected results.

Observation base 9717a76 A 9ce1a59
D1 agents_wait failed, schemaError: "structured_output was not called", result: "gamma" done, structured: {"result":"gamma"}, schemaError: null
D1 durable row no collectorCompletion.structured collectorCompletion.structured: {"result":"gamma"}, execution.outcome.status: "ok"
D1 child tool list structured_output absent, sessions_yield present structured_output present, sessions_yield absent
Control (no schema) done "gamma"; sessions_yield present done "gamma"; sessions_yield absent
Operator structured_output over POST /tools/invoke 404 not_found 404 not_found
Attach-grant tools/list for the collector's session not run structured_output absent, sessions_yield present
Attach-grant tools/call structured_output not run Tool not available: structured_output, isError: true
Same call on the collector's own grant after the run ends not run 401 from the loopback MCP, durable row unchanged
Collector turn after a gateway restart not run structured_output present, sessions_yield absent

The child is a small local model, so a given turn can decline to call a tool it was offered. If an
arm returns failed with structured_output was not called, check that turn's transcript before
concluding anything about the tool surface: on base the name is absent from the tool list, while
a turn that simply did not call it shows the name in its list and no tool_use block at all.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L labels Sep 13, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 8:27 PM ET / September 14, 2026, 00:27 UTC (Revision 12).

ClawSweeper review

What this changes

The PR gives CLI-backed collector tasks their structured-result tool, preserves it through restricted tool lists, and checks current run authority before recording results.

Merge readiness

✅ Ready for maintainer review

This remains a useful, distinct fix: current main still lacks CLI collector structured-output propagation. The recorded runtime evidence supports the repair, and this review found no blocking correctness or security defect.

Priority: P1
Reviewed head: d8c61fdc00cc1dd3fe6255d5d55c634e50ce7fc6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong runtime evidence, meaningful authority regressions, and no blocking finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded claude-cli runs exercise spawn, MCP tool discovery and submission, agents_wait, and SQLite results after the fix; attach/operator and revoked-grant cases reject forged writes. Hook-time revocation and reassignment have supplemental real-server regression coverage. Proof remains attributed to 9ce1a59, whose central collector implementation is unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Recorded claude-cli runs exercise spawn, MCP tool discovery and submission, agents_wait, and SQLite results after the fix; attach/operator and revoked-grant cases reject forged writes. Hook-time revocation and reassignment have supplemental real-server regression coverage. Proof remains attributed to 9ce1a59, whose central collector implementation is unchanged.
Evidence reviewed 9 items Current main and release still lack propagation: At fetched main, the Gateway calls createOpenClawTools without collector context. The v2026.9.4 resolver likewise contains no swarmCollector propagation; its source was retrieved through GitHub after the local release blob was unavailable.
Authority reaches the final writer: Collector admission requires the registry’s matching run identity. The result callback rechecks grant liveness and ownership synchronously before recordSwarmStructuredOutput; the existing writer rejects unavailable or completed collectors and rolls back failed persistence.
Complete captured proof inspected: Retrieved and inspected the full PR body, confirming its 71,404 UTF-16 units and SHA-256 6b4f6c73265e85a811b3d26d631d3e91ca421cc973e77b23b1950511b977ac80 match the supplied snapshot. At 9ce1a59, real Claude Code in isolated containers changed the same schema-backed spawn from missing-output failure to agents_wait done with matching structured data in SQLite. Attach and operator attempts could not submit forged results; revoked collector grants returned 401 without modifying results.
Findings None None.
Security None None.

How this fits together

Swarm collectors are child-agent tasks whose results are collected by the parent. CLI-backed children obtain tools through the Gateway’s loopback MCP server, which must connect their admitted run to the collector registry and validated result writer.

flowchart TD
  A[Collector spawn with schema] --> B[Admitted CLI run]
  B --> C[Gateway tool resolver]
  D[Collector registry] --> C
  C --> E[Structured result tool]
  E --> F[Check live grant and run ownership]
  F --> G[Persist validated result]
  G --> H[Parent collects result]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +191, Tests +646, Docs -4. Total +833 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 8 217 26 +191
Tests 3 648 2 +646
Docs 1 5 9 -4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 870 37 +833

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #141474
Summary: This PR addresses the CLI structured-output portion of the canonical report; the merged companion addresses collector yield settlement.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one collector contract across embedded and CLI tool assembly, with result writes bound to the live admitted run and historical recovery handled separately.

Do we have a high-confidence way to reproduce the issue?

Yes: spawn a claude-cli collector with an output schema and collect its result; current-main source omits the required tool context, and the contributor recorded the corresponding failure. This review did not execute current main.

Is this the best way to solve the issue?

Yes: the patch extends the existing collector owner and preserves exact grant enforcement, avoiding new persisted state or a competing result mechanism.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1a48d3401a43.

Labels

Label justifications:

  • P1: A documented collector workflow currently returns failed structured results on CLI-backed runs, with a concrete user report and recorded before/after reproduction.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Recorded claude-cli runs exercise spawn, MCP tool discovery and submission, agents_wait, and SQLite results after the fix; attach/operator and revoked-grant cases reject forged writes. Hook-time revocation and reassignment have supplemental real-server regression coverage. Proof remains attributed to 9ce1a59, whose central collector implementation is unchanged.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded claude-cli runs exercise spawn, MCP tool discovery and submission, agents_wait, and SQLite results after the fix; attach/operator and revoked-grant cases reject forged writes. Hook-time revocation and reassignment have supplemental real-server regression coverage. Proof remains attributed to 9ce1a59, whose central collector implementation is unchanged.

Evidence

What I checked:

  • Current main and release still lack propagation: At fetched main, the Gateway calls createOpenClawTools without collector context. The v2026.9.4 resolver likewise contains no swarmCollector propagation; its source was retrieved through GitHub after the local release blob was unavailable. (src/gateway/tool-resolution.ts:269, 1a48d3401a43)
  • Authority reaches the final writer: Collector admission requires the registry’s matching run identity. The result callback rechecks grant liveness and ownership synchronously before recordSwarmStructuredOutput; the existing writer rejects unavailable or completed collectors and rolls back failed persistence. (src/agents/openclaw-tools.swarm.ts:153, d8c61fdc00cc)
  • Complete captured proof inspected: Retrieved and inspected the full PR body, confirming its 71,404 UTF-16 units and SHA-256 6b4f6c73265e85a811b3d26d631d3e91ca421cc973e77b23b1950511b977ac80 match the supplied snapshot. At 9ce1a59, real Claude Code in isolated containers changed the same schema-backed spawn from missing-output failure to agents_wait done with matching structured data in SQLite. Attach and operator attempts could not submit forged results; revoked collector grants returned 401 without modifying results. (9ce1a595aca7)
  • Proof continuity across refresh: The collector owner, Gateway resolver, MCP runtime, and CLI attempt files are identical to the recorded live-proof revision. The separately inspected MCP server difference adopts the upstream request-abort helper without changing collector grant checks. Historical executions remain attributed to their original SHA. (src/agents/openclaw-tools.swarm.ts:53, d8c61fdc00cc)
  • Focused authority regressions: The added MCP boundary cases use the real server and resolver to reject same-session attach callers, grant revocation during the awaited hook, and run reassignment before persistence. The body records failing-before and mutation results plus 473 passing supplemental tests; this read-only review did not execute tests. (src/gateway/mcp-http.test.ts:4095, d8c61fdc00cc)
  • Companion repair is complementary: The supplied GitHub metadata verifies fix(subagents): swarm collector that calls sessions_yield strands agents_wait forever #146716 merged. Its body explicitly distinguishes terminal yield settlement from this PR’s CLI tool propagation. Historical stranded-row recovery and ordinary-leaf continuation questions remain tracked at [Bug]: Collector child calling sessions_yield strands agents_wait forever while status surfaces report done; outputSchema silently inert on claude-cli backends #141474. (610f6dcfef32)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-13T10:56:47.972Z sha 3fd85d77463b351499a08dab9192baafe070446e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T11:32:02.738Z sha 3fd85d77463b351499a08dab9192baafe070446e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T13:08:10.072Z sha 3fd85d77463b351499a08dab9192baafe070446e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T14:10:03.396Z sha 3fd85d77463b351499a08dab9192baafe070446e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T15:03:39.750Z sha c39df3a15961f1c78e7dc050bd7b67d59edcb184 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T20:33:27.991Z sha 9ce1a59 :: blocked before merge. :: none
  • reviewed 2026-09-13T23:57:45.507Z sha ad214d8 :: blocked before merge. :: none
  • reviewed 2026-09-14T00:08:00.224Z sha ad214d8 :: blocked before merge. :: none

@etzelm
etzelm force-pushed the fix/cli-collector-structured-output branch from 42c8e49 to 34e32a8 Compare September 13, 2026 05:19
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 13, 2026
@etzelm
etzelm force-pushed the fix/cli-collector-structured-output branch from 34e32a8 to 3fd85d7 Compare September 13, 2026 09:18
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 13, 2026
@etzelm etzelm closed this Sep 13, 2026
@etzelm etzelm reopened this Sep 13, 2026
@etzelm etzelm closed this Sep 13, 2026
@etzelm etzelm reopened this Sep 13, 2026
@etzelm etzelm closed this Sep 13, 2026
@etzelm etzelm reopened this Sep 13, 2026
@etzelm
etzelm force-pushed the fix/cli-collector-structured-output branch from 3fd85d7 to c39df3a Compare September 13, 2026 14:56
@etzelm

etzelm commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

The single red check on this head, checks-node-compact-large-16, is unrelated to this PR and is already fixed by #147117.

It fails in src/daemon/systemd.test.ts > readSystemdServiceRuntime > passes a kill-backed timeout to systemctl when a read deadline is set with AssertionError: expected 1233 to be 1234 (job). The test asserts an exact opts.timeout for every execFile call, while each call's timeout is drawn from a decaying deadline budget, so it fails whenever at least 1 ms elapses between calls on a loaded runner. #147117 replaces that with toBeGreaterThan(0) / toBeLessThanOrEqual(1234), which accepts the 1233 observed here. The same shard passes on other open PRs, and this PR touches no daemon, updater, or process-spawn code.

Everything else on this head is green (164 passing).

For context on the two earlier openclaw/ci-gate failures on the previous head 3fd85d7746, described in the PR body: those were a different flake, and they were not reproducing because of anything on the branch. Both runs were tested against merge base bc6b662e042, which is #146949, the change that introduced the expect(firstSettled).toBe(false) assertion in settings-storage.test.ts; #147029 removed it about two hours later. The runner log shows the tested merge directly:

HEAD is now at 5b956130 Merge 3fd85d77463... into bc6b662e0421694fcfcb1d71112486a0560b93c9

This head is rebased onto 0347bd5ab4a, which contains #147029, and that shard now passes.

Once #147117 lands, this branch needs a fresh run to pick it up. Re-running the failed job would be enough. I can't trigger that as an outside contributor, and pushing a no-op commit would invalidate the exact-head live proof receipts recorded in the body, so I'd rather not change the sha just to re-roll CI.

- Gateway tool resolution reads collector identity from the subagent
  registry, so CLI-backed collector children receive structured_output
  like embedded ones.
- The contract is gated on the admitted collector run's own grant, not
  on the transport: the request must carry the run id that reaches the
  resolver only from a Gateway-minted run-bound CLI client grant, and
  that id must match the registry record's runId or swarmRunId for the
  child session.
- A session-scoped openclaw attach client, even on the same loopback
  server and the same collector session, carries no run id and resolves
  the plain surface exactly as on main; the http tool-invoke surface is
  unchanged too.
- The result tool re-checks authority immediately before it persists:
  grant liveness plus the same admitted-run ownership test, so a grant
  revoked while the awaited before-tool hook runs fails closed with a
  tool error and writes nothing.
- recordSwarmStructuredOutput therefore stays reachable only from the
  embedded runner and from the admitted collector run's own CLI turn.
- Collector identity is keyed on the registry collect flag alone, so it
  no longer depends on outputSchema and matches the embedded runner,
  which takes swarmCollector from the spawn request; the schema gates
  only the result transport, not the identity.
- structured_output survives restrictive gateway tool policy, and the
  CLI attempt merges it into a narrowed runtime allowlist so the exact
  loopback grant cannot re-hide it for a plugin-launched or
  cron-continued collector.
- A collector turn whose registry record is not loaded resolves to the
  plain surface as on main; restart recovery of collector runs stays
  owned by subagent-registry-restart-recovery.ts.
- Every admitted collector child, schema-backed or not, no longer
  receives sessions_yield, ask_user, or sessions_send, matching the
  embedded runner.
- Collector run contract now has one owner shared by both tool paths.
- Both refusals and the allowed write are also proven over the real
  loopback MCP server: an attach grant minted for the collector's own
  child session gets no result tool to list or call, and that
  collector's run-bound grant is refused when it is revoked or when the
  registry record is rebound inside the awaited before-tool hook.
@etzelm
etzelm force-pushed the fix/cli-collector-structured-output branch from c39df3a to 9ce1a59 Compare September 13, 2026 20:23
@roboclaw-bot

roboclaw-bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Completed: #146715 is merged as 268dbc6d08b129273af94b82b18935a948af57e4, from exact source head d8c61fd.

Independently verified GitHub MERGED state, main containment, Mitchell Etzel (@etzelm) as the landed commit’s author, and the exact trailer Co-authored-by: VACInc <[email protected]>. Main61b87fa8bd55 contains this commit and companion #146716/610f6dcfef32.

The source fork branch remains intact because GitHub denied the native cleanup deletion. No permission changes, alternative credentials, or alternate deletion route were attempted. The native PR worktree was removed, and the merge receipt was retained. This does not affect the confirmed merge.

Historical live proof remains attributed to9ce1a595aca; separate live codex-cli/gemini-cli runs were not claimed. #141474 remains open for historical stranded-row and ordinary-leaf concerns; no operator Gateway restart, live-data repair, or schema change was performed.

Coordination for these two named landings is complete. No further branch rewrite or landing job is needed for #146715 or #146716.

roboclaw-bot and others added 2 commits September 13, 2026 23:44
Bring in the upstream Linux service ownership fixtures and the landed collector yield repair without duplicating the fixture patch or replacing contributor ancestry.

Co-authored-by: VACInc <[email protected]>
Remove the temporary CLI exception after bringing the collector tool contract and terminal settlement fixes together.

Co-authored-by: VACInc <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Sep 13, 2026
Bring in openclaw#147551, which fixes the exact same-millisecond ordering failure observed in the refreshed collector PR CI. Preserve all contributor ancestry and avoid a duplicate local test repair.

Co-authored-by: VACInc <[email protected]>
@roboclaw-bot
roboclaw-bot merged commit 268dbc6 into openclaw:main Sep 14, 2026
224 of 226 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via squash.

@etzelm
etzelm deleted the fix/cli-collector-structured-output branch September 14, 2026 00:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…#146715)

Restore the collector result contract on CLI-backed child runs.

Resolve it from the admitted registry-owned run, preserve exact grant allowlists, and revalidate live authority before recording structured output. Align embedded and CLI requester-tool filtering without changing ordinary subagents or operator/attach callers.

Related: openclaw#141474

Co-authored-by: Mitchell Etzel <[email protected]>
Co-authored-by: VACInc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants