Repository navigation
fix: sessions_spawn outputSchema is ignored on CLI backends - #146715
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 8:27 PM ET / September 14, 2026, 00:27 UTC (Revision 12). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherSwarm 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +191, Tests +646, Docs -4. Total +833 across 12 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (11 earlier review cycles; latest 8 shown)
|
42c8e49 to
34e32a8
Compare
34e32a8 to
3fd85d7
Compare
3fd85d7 to
c39df3a
Compare
|
The single red check on this head, It fails in Everything else on this head is green (164 passing). For context on the two earlier This head is rebased onto 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.
c39df3a to
9ce1a59
Compare
|
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
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. |
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]>
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]>
|
Merged via squash.
|
…#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]>
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 ID77b235aeeebfea9df5338ddc815f5e53057eb1de); 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
outputSchemaand itsagents_waitreturnsstatus: "failed"withschemaError: "structured_output was not called"when that child runs on a CLI backend such asclaude-cli,codex-cli, orgemini-cli.User Impact
sessions_spawnwithcollect: trueand anoutputSchemanow returns a validated structured result regardless of which runtime the child uses, so Swarm scripts andagents.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 offeredsessions_yield,ask_user, andsessions_send, which they were never able to use productively, whether or not that child requested anoutputSchema.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 attachclient, 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: nostructured_output, andsessions_yieldand the other requester tools exactly as main serves them today. The operator-facinghttptool-invoke surface (surfacehas 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
swarmCollectorandswarmOutputSchemainto tool construction, and that is what builds the syntheticstructured_outputtool. 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" whileoutputSchemastayed 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
collectflag alone, so it matches the embedded runner, which takesswarmCollectorstraight from the spawn request for every collector; theoutputSchemagates 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 keyagents_waitreads 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_outputis restored after the resolver's policy pipeline, so a restrictivetools.allowcannot delete a run contract. That alone is not enough. A per-run grant allowlist is applied after the resolver returns and is enforced exactly ontools/listandtools/call. A collector launched bysessions_spawnoragents.run()carries notoolsAllow, but one launched through a plugin'sapi.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 samemergeForcedEmbeddedAttemptToolsAllowhelper 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 attachbearer, and the server's own owner/non-owner tokens.resolveMcpRequestContextreturns the grant's immutable context for the first and a minimal{ sessionKey, agentId }context for the second, sorunIdis present only for a run-bound CLI grant. The header-derived branch never sets it either, and the singlehttpcaller (tools-invoke-shared.ts) never passes one. The resolver therefore requiresparams.runIdto match the registry collector record for that child session, comparing against bothentry.runIdand the launch id retained asentry.swarmRunId, which is the same pairgetSubagentRunByRunIdmatches after a queued relaunch remaps the row. An attach client bound to the collector's own session resolves to the plain surface, andtools/callresolves names out of that exact list, so namingstructured_outputreturnsTool not available: structured_outputand 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'sonStateChangenow re-checks, immediately beforerecordSwarmStructuredOutput, that the grant is still current and that the caller still owns the admitted collector run. The first operand is the sameisCurrentliveness check the loopback server already applies asauthorizeToolCallafter the hook; the second is the same admitted-run test the resolver applied. A failure throws,createStructuredOutputToolrolls 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: theonStateChangecallback of the tool built increateOpenClawSwarmToolGroups. That tool is only built whencreateOpenClawToolsis given bothswarmCollectorandswarmOutputSchema. Exactly two call sites supply them:agent-tools.ts, the embedded runner reading the spawn request in-process, andtool-resolution.ts, now only for a matched admitted collector run. The thirdcreateOpenClawToolscaller,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 awaitedrunBeforeToolCallHooknow 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.tsre-dispatches a recovered run withswarmCollectorandswarmOutputSchemarebuilt 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 anoutputSchematoo, which is the arm the issue's D2 describes: it loses the requester-only tools even though it receives nostructured_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.mdnow 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.tsdrives the real entry pointresolveGatewayScopedToolswith a collector run registered in the subagent registry, executes the resolved tool and asserts the result reaches the registry record, then drivesresolveMcpLoopbackScopedToolsto cover the grant allowlist enforced above the resolver. The same describe registers a second collector run carrying nooutputSchemaand pins the schema-independent half of the contract on it: the requester-only tools are withheld,structured_outputstays absent, and the flag reaches tool construction (its resolvedsessions_spawnrejects 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 withsessions_yieldintact, 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
resolveMcpRequestContextbuilds for a session-scoped attach grant, must resolve a collector session to the same tool list a plain child gets: nostructured_output,sessions_yieldintact, and the registry record still carrying nostructuredOutputand nocollectorCompletion. 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 asswarmRunIdmust still be admitted. The same describe keeps thehttpcases:tools-invoke-shared.tspassessurface: "http", and there a collector session must resolve to a tool list identical to a plain child's, must keepsessions_yield, and must let a restrictivetools.allowwin outright.A third describe pins the write-time re-check on the tool's own
executepath. With the grant flipped to revoked after the tool is built,executerejects withcollector run grant is no longer activeand neitherstructuredOutputnorcollectorCompletionis written; with the registry record rebound to a different run after the tool is built, it rejects withcaller no longer owns the admitted collector runand again writes nothing; with the grant still current it records normally. The fourth describe drivesresolveMcpLoopbackScopedTools, the loopback entry point above the resolver, for the grant allowlist and for the run-less context.src/agents/command/attempt-execution.cli.test.tscovers the merge itself: a restricted collector attempt must handrunCliAgentatoolsAllowthat still containsstructured_output, while a schema-less collector attempt and a plain non-collector attempt must both be left untouched.src/gateway/mcp-http.test.tscloses 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, inresolveMcpRequestContext. The new describe registers a schema-backed collector run and then goes over the wire to a realensureMcpLoopbackServer, with the mocked resolver delegating to the realresolveGatewayScopedTools, so every layer between the bearer token and the registry record runs: anopenclaw attachgrant minted for that collector's own child session gets atools/listwithoutstructured_output, atools/call structured_outputansweredTool not available: structured_outputwithisError: true, and a registry record still holding neitherstructuredOutputnorcollectorCompletion. 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 withTool call authorization expired, and rebinding the registry record to a different run there, which leaves grant liveness untouched, is refused withFailed 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:
structured_output, and executing it records{ structured: { answer: "ok" }, invalidAttempts: 0 }on that collector's registry record. Over the server, atools/callon that collector's own run-bound grant does the same.openclaw attachgrant for that session produces the run-less context itself rather than receiving it as a parameter.executefail closed beforerecordSwarmStructuredOutput, leaving the record untouched. Over the server, the revocation is performed inside the awaited before-tool hook, and the caller is refused beforeexecuteruns 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):
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:
node scripts/run-vitest.mjs <15 test files>node scripts/check-changed.mjs --timedok, including typecheck core, typecheck core tests, format changed files, lint, import cycles, dead export scangit diff --checkFull test and check output
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 256on the restored files matched the pre-mutation copy, and the suites were re-rungreen afterward.
1. Admitted-run gate reverted to session-key-only resolution.
resolveSwarmCollectorToolContextdrops the
admittedRunIdrequirement and theownsAdmittedCollectorRuntest, resolving thecollector contract from the child session key alone, which is what the previous revision did.
2. Pre-persistence re-check removed. Only the
assertCollectorWriteAuthority()call insideonStateChangeis deleted; the resolve-time gate stays.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.
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 ontoa2b2391e353, which carries both fixes.3fd85d7746, twice, onsrc/agents/sessions/settings-storage.test.ts > FileSettingsStorage > preserves independent concurrent first writes to global settings(and the project-settings sibling), failingexpect(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 basebc6b662e042, 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:c39df3a1596, once, onsrc/daemon/systemd.test.ts > readSystemdServiceRuntime > passes a kill-backed timeout to systemctl when a read deadline is set, failingAssertionError: expected 1233 to be 1234. The test asserted an exactopts.timeoutfor everyexecFilecall 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 withtoBeGreaterThan(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 fetchesthis exact object and checks it out, so
git rev-parse HEADin the repro worktree prints9ce1a595aca78bd49e8948768300255668030c83, on parenta2b2391e353, 11 files and +865/-28, with aclean tree. The image bakes that sha at
/image-commit, and every receipt below carries it. Thereis no
patch-idstand-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.
basewas built from an unchanged commit and was not re-run; its rows are from thefirst 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
5ce5b0a223was re-checked and still applies cleanly with no conflicts, giving4783ef45f22.Executed against a real
claude-clichild (Claude Code 2.1.270) driving a local model, incontainers built from the base commit and from this branch's head. Arms are driven
over the Gateway
POST /tools/invokeendpoint (sessions_spawn, thenagents_wait), so noparent model judgment is in the control path. Receipt fields come from
agents_wait, thesubagentsrecent/tasksprojections, and the state SQLitesubagent_runs.payload_json.Every collector arm runs a CLI child spawned by
sessions_spawn, so every tool list and everyrecorded 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 collectorsession was persisted and in flight.
Environment.
node:24-bookworm/ Nodev24.21.0; Claude Code2.1.270; child model refclaude-cli/qwen3-coder-next-mlxserved 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-clibackend launching the real Claude Codebinary. Claude Code is pointed at the local endpoint through its user
settings.jsonenvblock,because
CLAUDE_CLI_CLEAR_ENVstripsANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKENfrom thespawned process environment by design.
agents_wait9717a7635a0(base)bfb20d9bfailed,schemaError: "structured_output was not called",result: "gamma"9ce1a595aca(this head)63df6caddone,structured: {"result":"gamma"}29b64e35ed4(predecessor merge, not re-run)411d65dbdone,structured: {"result":"gamma"}9ce1a595aca(this head)8cb6199edone,structured: {"result":"gamma"}9ce1a595aca(this head)1d27f7b8terminal/error; grant then answers401 unauthorized9ce1a595aca(this head)71b565d7done,structured: {"result":"gamma"}, then grant answers401 unauthorized9ce1a595aca(this head)ea70dfce404; the child's own submissiondone,structured: {"result":"delta"}9ce1a595aca(this head)48fe5641done,structured: {"result":"gamma"}9ce1a595aca(this head)a4f41ebffailed,error: "subagent run lost active execution context"9ce1a595aca/ A+B90f8c022/bef8b4f4/7e52aa85done,result: "gamma"on all three29b64e35ed412042001doneBoth 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 negativearm spawns the same call with the task word
delta, so its own recorded result is distinguishablefrom 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 sametool over the operator
httpsurface was refused with404 Tool not available: structured_outputand 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.recentreportsstatus: "done"andsubagents.tasksreportsstatus: "completed"for the same run - the requester is told the run failed, both statussurfaces say it succeeded.
After (this head,
9ce1a595aca), run63df6cad-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/*/*.jsonlinside the container), per child turn rather than aggregated:
mcp__openclaw__structured_outputmcp__openclaw__sessions_yield9717a76outputSchema(d1-before)9ce1a59outputSchema(d1-after)9ce1a59outputSchema(attach client arm)9ce1a59outputSchema(operator HTTP negative arm)9ce1a59outputSchema, one turn each side of a gateway restart9ce1a59outputSchema(revoked grant arm, both runs)29b64e3outputSchema(d1-AB)9717a769ce1a5929b64e329b64e329b64e3On
basea schema-less collector keepssessions_yield; on A and on A+B it does not, whilestructured_outputstays 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 withstructured_outputswapped in.mcp__openclaw__ask_userandmcp__openclaw__sessions_sendcannot be measured in this harness:the reproduction gateway does not offer either tool on any image,
baseincluded (its child toolsurface 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 childandwithholds requester-only tools from a collector child that requested no schemain the resolver test, not by this run.On A the child calls the tool and the result is recorded:
agents_waitreturnsstructured: {"result":"gamma"}withschemaError: null, and the durablesubagent_runsrowcarries the same object under
collectorCompletion.structured. The rawtool_use/tool_resultpairs were captured this time, from the operator HTTP negative arm's own childtranscript, and they also show the validation retry path:
That is the same session key, on the same gateway, in the same wall-clock window in which four
operator
POST /tools/invokerequests namingstructured_outputwere 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()returnedundefinedfor a runwith no
outputSchema, so on the Gateway path a schema-less collector was not treated as acollector at all and kept
sessions_yield; only schema-backed collectors lost it. The resolverkeys collector identity on the registry's
collectflag, matching the embedded runner, so everycollector child on the loopback path loses
sessions_yield,ask_user, andsessions_send, andonly a schema-backed one receives
structured_output. The A and A+B arms confirm the live half ofthat:
control-A,control-AB, andd2-ABare all schema-less collectors and none of them isoffered
sessions_yield, while the schema-backed rows and both D1 arms are unchanged and thenon-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 theattach.grantgateway call at scopeoperator.admin. The returnedmcpConfiggives the loopbackMCP URL directly and carries only an
Authorizationheader, with nox-openclaw-cli-capture-key; that was confirmed on both images. The loopback MCP was then drivenwith that bearer and nothing else. No
x-session-keyor other context header was sent.Before, on the previous head
34e32a8b8aa, collector run006335e3:The child's own answer was
gamma. A client that never ran the task overwrote the recorded resultwith
forged, and that is what the requester received and what the durable row kept.After, on this head
9ce1a595aca, collector run8cb6199e:The grant itself was inspected before it was used: its
mcpConfiglists exactly one header name,Authorization, and carries nox-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_outputand lostsessions_yield. On this head it is resolved as an ordinary session client, so it keepssessions_yieldand is never offered the result tool. That is the gate keying onparams.runId,which an attach grant does not carry, rather than on the session key, which it does. The literal
string
forgedappears in nosubagent_runspayload on this head, checked for the target run andacross 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
executepath, and, as of this head, at thereal MCP boundary, where
src/gateway/mcp-http.test.tsrevokes the collector's grant from insidethe awaited before-tool hook of a live
tools/calland getsTool call authorization expiredwith 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 runspawned 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
claudeprocess was located in the container,its
--mcp-configand itsOPENCLAW_MCP_TOKEN/OPENCLAW_MCP_CLI_CAPTURE_KEYvalues were readfrom
/proc/<pid>, and the resulting headers were replayed against the loopback MCP. Unlike theattach grant, this client config carries both
Authorizationandx-openclaw-cli-capture-key, and while the run is live itstools/listreturns 29 names withstructured_outputpresent andsessions_yieldabsent. It is the collector's real writer.tools/call structured_outputafter1d27f7b8SIGKILLto the collector child, so run teardown revokes the grant{"error":"unauthorized"}Claude Code process exited with signal SIGKILL, nocollectorCompletion71b565d7{"error":"unauthorized"}collectorCompletion.structured: {"result":"gamma"}, unchangedtools/liston the same grant after revocation also returns 401, and the forged value appears inno
subagent_runspayload in either variant. So a revoked collector grant writes nothing, whichis 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 expiredfrom the server's post-hookauthorizeToolCallandFailed to persist structured_output: collector run grant is no longer activefrom the pre-persistence re-check, appears in these receipts. Once the grant row is gonethe 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
executepath.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 surfacewith the task word
delta, and while it was still running, fourPOST /tools/invokerequestsnamed
structured_outputagainst it with the same gateway bearer token that had just beenaccepted for
sessions_spawn. Two field spellings were used, because the endpoint readsparams.input.name ?? params.input.tool, and both the child's session key and the parent's weretried, mid-run and again after the run had gone terminal.
All four attempts returned that identical status and body:
toolnot_found,Tool not available: structured_outputnamenot_found,Tool not available: structured_outputtoolmainnot_found,Tool not available: structured_outputtoolnot_found,Tool not available: structured_outputThe 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":{}}returned200 ok: true. The404 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-a0c6a4d636afreturnedagents_waitdonewithstructured: {"result":"delta"}andschemaError: nullat 89.2 s, and its durable row carriescollectorCompletion: {"status":"done","structured":{"result":"delta"}}withexecution.outcome.status: "ok". So the same tool name is writable by the collector's ownrun-bound grant and refused on the operator surface, in the same run. The
tool_use/tool_resultpair quoted above is from a child transcript on this image.Nothing forged was persisted. The literal string
forgedappears in nosubagent_runspayload in that container's state database, checked both for the target run and across every row.
The same four requests against the
baseimage9717a76also returned 404 with the identicalbody, 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_waitfailed,result: "delta",schemaError: "structured_output was not called".Restart with a persisted schema-backed collector session
Image A at
9ce1a595aca, with/stateon a persistent Docker volume so the state databaseoutlives 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.sessions_spawnschema-backed collector, runf161a1e4,acceptedexecution.status: "running";SIGTERMsent to the gatewayPOST /tools/invokeanswers503while it drains the in-flight runSIGKILLsent, the waydocker stopescalatesclaudeprocess survives as an orphan; durable row stillrunning/state, different pid; it prints[gateway] ready5.1 s after the start callagents_waiton the interrupted run returns after 59.6 sWhat recovery did with the interrupted run. It settled it as an error rather than relaunching
it.
agents_waitreturnedstatus: "failed",error: "subagent run lost active execution context",schemaError: "structured_output was not called"; the durable row moved toexecution.status: "terminal"withoutcome.status: "error"carrying that message, andinterruptionReasonstayednull. The child could not survive the restart: it is a subprocess ofthe 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 withmcp__openclaw__structured_outputpresent andmcp__openclaw__sessions_yieldabsent, 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,grantorswarmaround either spawn.A fresh collector after the restart works. One was spawned, 65.4 s after
[gateway] ready,run
48fe5641. It returnedagents_waitdonewithstructured: {"result":"gamma"}andschemaError: nullat 90.1 s, withcollectorCompletion.structuredmatching andexecution.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
failedwithschemaError: "structured_output was not called"and only the retry succeed. That did notrecur here, and it did not recur on the
patch-idequal predecessor either, where threepost-restart collectors spawned 65.1 s, 163.5 s and 280.4 s after ready all returned
done, whichrules 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:
Not verified here:
ask_userandsessions_sendare not offered by the reproduction gatewayon any image, so their withholding is proven by the resolver tests rather than by a live
transcript.
codex-cliandgemini-clireach the same resolver but were not exercised backend bybackend. 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
executepath. See the revoked-grant subsection above forwhat the live arms do and do not reach. The revoked-grant pair, which earlier revisions could only
measure on a
patch-idequal predecessor, was re-measured on9ce1a595acafor this revision. Twothings 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>. AnyAnthropic-compatible local endpoint works for the child; this run used LM Studio on port 1234.
1. Image. One per commit: base
9717a7635a0ee83167568038e2c123943968e19d, A9ce1a595aca78bd49e8948768300255668030c83, B32c4f145bed14237ab2a64d868f223cf2b46ebf6, A+B mergeof the two. Check each out into
~/repro/wt/<arm>/. B sits on upstream main4f6379cafeb6b53beb5e7ceff7de2d40535318c0, and the A+B merge is produced locally by merging Ainto B, which is clean and needs no conflict resolution and yields
29b64e35ed46b0a4e9aff0583375fd269ea906a5. Applying A and B asgit format-patchfiles reproducesboth shas exactly, as long as
git amis given the original committer identity and date; the authoridentity and date already travel inside the patch.
A is 11 files, +865/-28 against
9717a7635a0.The commit is baked at
/image-commitand 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.)2. Config.
~/repro/incontainer/openclaw.json, copied to/state/openclaw.jsonat boot.sessions_spawnis on the Gateway HTTP deny list by default, whichgateway.tools.allowoverrides.{ "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_ENVstripsANTHROPIC_BASE_URLandANTHROPIC_AUTH_TOKENbefore launch. Use user settings instead, which thebackend loads via
--setting-sources user.3. Run.
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).4a. Operator HTTP negative arm. Spawn the D1 arm again with the task word
deltaand"label":"repro-http-negative", takechildSessionKeyfrom the spawn result, then fire thesewhile the child is still running. Every one must answer
404with{"ok":false,"error":{"type":"not_found","message":"Tool not available: structured_output"}}.Repeat the first request once more after
agents_waithas returned, to cover the terminal case.4b. Restart with a persisted collector session. Start the container with
/stateon a namedvolume (
-v repro-state:/state) so the database outlives the process, then:Expect the interrupted run to settle
failedwitherror: "subagent run lost active execution context", and the fresh collector to returndonewith its structured result. Re-run the toolscan from step 5 afterwards: the post-restart collector turn must still show
mcp__openclaw__structured_outputpresent andmcp__openclaw__sessions_yieldabsent. Apost-restart collector can still come back
structured_output was not calledif the child simplydoes 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_spawnresult or fromsubagents { action: "list" }.Expect
tools/listto omitstructured_outputand to includesessions_yield, andtools/callto return
{"content":[{"type":"text","text":"Tool not available: structured_output"}], "isError":true}. Then let the child finish:agents_waitmust return the child's own result, andforgedmust appear in nosubagent_runspayload. On a build without the admission gate the sametwo requests return the tool and
{"status":"recorded"}, and the durable row ends up holdingforged, 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.
With those headers,
tools/listreturns the collector contract:structured_outputpresent,sessions_yieldabsent. Now revoke the grant by ending the run, either by killing the child sorun teardown revokes it, or simply by letting the run finish, and replay the same
tools/callstructured_outputrequest. Expect the loopback MCP to answer401and the durable row to beunchanged: no
collectorCompletionat all for the killed run, and the child's own result for thecompleted one. Note that
subagents { action: "cancel" }will not do this from the operatorsurface; 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_useblocks.Read out whether
mcp__openclaw__structured_outputandmcp__openclaw__sessions_yieldare presentper file, plus the total
mcp__openclaw__*count.6. Expected results.
9717a769ce1a59agents_waitfailed,schemaError: "structured_output was not called",result: "gamma"done,structured: {"result":"gamma"},schemaError: nullcollectorCompletion.structuredcollectorCompletion.structured: {"result":"gamma"},execution.outcome.status: "ok"structured_outputabsent,sessions_yieldpresentstructured_outputpresent,sessions_yieldabsentdone"gamma";sessions_yieldpresentdone"gamma";sessions_yieldabsentstructured_outputoverPOST /tools/invoke404 not_found404 not_foundtools/listfor the collector's sessionstructured_outputabsent,sessions_yieldpresenttools/call structured_outputTool not available: structured_output,isError: true401from the loopback MCP, durable row unchangedstructured_outputpresent,sessions_yieldabsentThe child is a small local model, so a given turn can decline to call a tool it was offered. If an
arm returns
failedwithstructured_output was not called, check that turn's transcript beforeconcluding anything about the tool surface: on
basethe name is absent from the tool list, whilea turn that simply did not call it shows the name in its list and no
tool_useblock at all.