Skip to content

fix(exec): plugin tools can tell which run started a background exec completion wake - #179816

Merged
VACInc merged 1 commit into
openclaw:mainfrom
VACInc:wake-exec-provenance
Oct 22, 2026
Merged

VACInc merged 1 commit into
openclaw:mainfrom
VACInc:wake-exec-provenance

Conversation

@VACInc

@VACInc VACInc commented Oct 21, 2026

Copy link
Copy Markdown
Member

Summary

High Level TLDR

When an agent starts a background exec and ends its turn, OpenClaw wakes the conversation again when the command finishes. That wake is correctly not an owner turn, but it also carried no link to the run that started the command: plugins only saw { kind: "internal_system", sourceTool: "exec" }, and plugin tool factories got neither the run id nor the turn's input provenance. A plugin that gates its own tool (for example an owner-only SSH broker) therefore could not tell "the completion of a command my owner started a minute ago in this session" from any other internal turn, and had to refuse it.

This change names the starting run on the completion wake (InputProvenance.runId) and exposes runId and inputProvenance on the plugin tool context, on both the embedded runtime and the claude-cli MCP loopback. It only adds facts: wakes stay non-owner turns, and no plugin gains authority it did not already have. The Gateway agent method now accepts exec completion provenance only from backend callers, so a client cannot forge it.

What Problem This Solves

Fixes: a plugin tool cannot recognize the completion wake of a background command that its owner started, so owner-gated plugin tools refuse follow-up work on that wake.

User Impact

Plugin authors can correlate a completion wake with the run that started the command (toolContext.inputProvenance.runId against the toolContext.runId seen on that earlier turn) and decide their own policy. Nothing changes for users without such a plugin. Wakes still run with senderIsOwner not true.

Root Cause

  • Before: the wake context is built in src/auto-reply/reply/session-event-context.ts as InputProvenance: { kind: "internal_system", sourceTool: options.source }. The exec process identity travels only as a private exec:<instance id> source-turn id (source-turn-id.ts), and nothing records which run's exec call started the process (ProcessSession has no run field).
  • Plugin tool factories receive OpenClawPluginToolContext (src/plugins/tool-types.ts), which has sessionKey, sessionId, and senderIsOwner, but no runId or inputProvenance, even though agent hooks already receive inputProvenance (PluginHookAgentContext).
  • On claude-cli agents, tools run through the MCP loopback, which deliberately does not inherit the turn's async context (mcp-http.ts, runInDetachedAsyncContext). The run-bound grant (buildCliMcpGrantContext) copied inputProvenance only for verified subagent handoffs, so even an internal wake's provenance never reached loopback tools.
  • Observed: on a live Gateway, an owner turn on a claude-cli agent started a background command; the completion wake then called an owner-only plugin tool, which had to refuse with its owner-authority error because the context offered no verifiable link back to the owner's run. The red tests and the "before" proofs below reproduce the missing facts on current main.

Why This Change Was Made

  • exec records the starting run on the process (ProcessSession.originRunId, from the exec tool's run) and the completion wake stamps it as InputProvenance.runId, using the existing field, so the persisted transcript provenance shape and the Gateway protocol schema are unchanged.
  • resolveOpenClawPluginToolInputs forwards runId and inputProvenance (embedded path). resolveGatewayScopedTools forwards the grant's inputProvenance to plugin tools (loopback path), and the CLI grant now carries internal_system provenance. Loopback requester policy reads provenance only for external_user and verified handoffs (requester-tool-policy.ts), so this does not change any tool surface. External-user and inter-session provenance stay off the grant as before.
  • prepareAgentRequestPreflight rejects client-supplied internal_system/exec provenance unless the caller is a backend client, mirroring the existing progress-refresh reservation directly above it.
Behavior matrix
Case Wake inputProvenance Plugin tool context
Background exec started by run R, embedded runtime { internal_system, exec, runId: R } runId = wake run, inputProvenance.runId = R
Same, claude-cli runtime (MCP loopback) same same (proved below)
Exec tool built without a run id { internal_system, exec } (unchanged) inputProvenance without runId
Foreground exec, or exit before backgrounding no wake (unchanged) n/a
"Exec lost" notice after a Gateway restart { internal_system, exec } (persisted fact has no run) no runId, plugins fail closed
Subagent-session exec (system event + heartbeat path) unchanged unchanged
Node-host exec completion (node event path) unchanged unchanged
agent RPC with internal_system/exec provenance, non-backend client rejected n/a
Same, backend client admitted (unchanged) n/a
CLI grant with external_user or inter_session provenance, no handoff not carried (unchanged) absent
Owner bit on the wake senderIsOwner not true (unchanged) unchanged

Session-event turns are admitted exclusively (turnAdoptionLifecycle.admission: "exclusive"), one exec occurrence per turn, so the stamped run is the run of that turn's command.

Real behavior proof

Both runtimes were proved through a real isolated Gateway process (createOpenClawTestInstance, built dist), with a local plugin that registers a version 2 tool factory wake_probe and records the factory context. A scripted model (embedded: mock OpenAI Responses provider; claude-cli: a fake claude binary on PATH that speaks the stream-json protocol and calls the real MCP loopback from the generated --mcp-config) does: owner turn via chat.send calls exec {"command":"sleep 2; echo WAKE_EXEC_DONE","background":true} and ends; the real completion wake calls wake_probe. The harness files are scratch and not part of this PR.

After (this branch), embedded runtime, plugin trace:

{"source":"factory","runId":"owner-start-turn","sessionKey":"agent:main:wake-provenance","sessionId":"2ea1268c-...","senderIsOwner":true}
{"source":"factory","runId":"b42c0634-...","sessionKey":"agent:main:wake-provenance","sessionId":"2ea1268c-...","senderIsOwner":false,"inputProvenance":{"kind":"internal_system","sourceTool":"exec","runId":"owner-start-turn"}}
{"source":"execute","toolCallId":"call_3|fc_3","runId":"b42c0634-...","senderIsOwner":false,"inputProvenance":{"kind":"internal_system","sourceTool":"exec","runId":"owner-start-turn"}}

After, claude-cli runtime (tool call arrived over the MCP loopback, toolCallId mcp-...):

{"source":"factory","runId":"owner-start-turn","sessionKey":"agent:main:wake-provenance","senderIsOwner":true}
{"source":"factory","runId":"3f44f0ff-...","senderIsOwner":false,"inputProvenance":{"kind":"internal_system","sourceTool":"exec","runId":"owner-start-turn"}}
{"source":"execute","toolCallId":"mcp-9d912671-...","runId":"3f44f0ff-...","senderIsOwner":false,"inputProvenance":{"kind":"internal_system","sourceTool":"exec","runId":"owner-start-turn"}}

Before (same harness on base e8977af441a): the wake's tool context has no runId and no inputProvenance, on both runtimes:

embedded: {"source":"execute","toolCallId":"call_3|fc_3","sessionKey":"...","sessionId":"...","senderIsOwner":false}
claude-cli: {"source":"execute","toolCallId":"mcp-f8e96ab5-...","sessionKey":"agent:main:wake-provenance","sessionId":"...","senderIsOwner":false}
claude-cli assertion: expected undefined to deeply equal { kind: 'internal_system', sourceTool: 'exec', runId: ... }

In both runtimes the wake's own run id differs from the owner run, the session key and id match, and senderIsOwner is false.

Performance

Microbenchmark of the three touched per-turn paths, base vs head, same host and Node 24.19.0, 20k warmup, 9 samples x 50k iterations, two runs per side (median ns/op):

Path base run 1 / 2 head run 1 / 2
session-event context (exec wake) 173.8 / 178.2 203.6 / 191.0
plugin tool inputs 1855.7 / 1829.3 1851.9 / 1855.9
CLI MCP grant context 1837.9 / 1871.9 1908.1 / 1865.0

The wake context gains one conditional property spread (about 15 to 30 ns once per wake); the other two paths are within noise. No per-token or per-tool-call work was added.

What was not tested

  • A real Claude CLI binary and a real model provider: the claude-cli proof uses a protocol-faithful fake claude that drives the real CLI runner, grant, and MCP loopback.
  • A real channel transport (Telegram etc.): the proofs use chat.send on an internal session; the wake path and plugin context are channel-independent.
  • Node-host exec completions and subagent-session exec completions: unchanged paths, no runId added (listed in the matrix).
  • Exec completions recovered after a Gateway restart: intentionally carry no runId; not exercised end to end here.

Verification

  • New regression tests, red on base and green on this branch:
    • src/agents/bash-tools.exec-background-followup.test.ts: real background exec, real session-event handoff and dispatch; the completion turn's inputProvenance is exactly { kind, sourceTool, runId } with a starting run, and has no runId without one; wake stays non-owner.
    • src/agents/openclaw-tools.plugin-context.test.ts: embedded plugin tool inputs forward runId and inputProvenance.
    • src/agents/cli-runner/mcp-grant-context.test.ts: grant carries internal_system provenance, still omits external_user and inter_session without a handoff.
    • src/gateway/tool-resolution.memory-audience.test.ts: loopback plugin tools receive the run id and the grant's provenance.
    • src/gateway/agent-turn/agent-request-preflight.test.ts: non-backend exec provenance rejected, backend admitted.
  • Consumer suites of every touched owner: 41 files (session-event handoff/readmission/permissions, exec notify/runtime/lifecycle, heartbeat exec session events, MCP exec completion and completion lineage, tool resolution, CLI attempt execution and admission, tools invoke HTTP, cron session runs, restart dispatch, plugin reload handoff) passed; plus plugin tool factory/inspection/optional suites and agent-tools.prefix-stability.
  • pnpm check:changed: format, lint, typecheck core and core tests, line-cap ratchet, and all guards pass. Three checks fail identically on base e8977af441a and are not caused by this PR: max-lines suppression ratchet (ui/src/pages/config/config-page-state.ts, ui/src/pages/sessions/sessions-page-state.ts), core test shard root budget (agents-root 722, gateway-root 730, infra 749 on both), and the production unused-export scan (19 unrelated exports; none in touched files).
  • pnpm plugin-sdk:api:diff --base e8977af441a --head HEAD: additive optional fields only (runId, inputProvenance on the tool context; sourceRunId on session event options; originRunId on ProcessSession).
  • $autoreview (branch mode, P1, Claude engine): scoped-clean. Its open questions were checked in source: requester policy reads only external_user provenance and verified handoffs; no non-backend caller sends exec provenance; session-event turns are admitted exclusively, so one wake carries one command's run.
  • Secret scan of the diff (trufflehog, pattern grep): no findings.

…tools

A background exec completion wake reached plugins as
{ kind: "internal_system", sourceTool: "exec" } with no link to the run
that started the command, and plugin tool factories received neither the
turn's run id nor its input provenance. On claude-cli agents the MCP
loopback grant also dropped internal provenance. A plugin therefore could
not tell the completion of a command its owner started from any other
internal turn.

- exec records the starting run on the process and the completion wake
  stamps it as InputProvenance.runId.
- plugin tool contexts expose runId and inputProvenance on both the
  embedded runtime and the claude-cli MCP loopback; the CLI grant carries
  internal-system provenance, which requester policy does not read.
- the agent RPC reserves exec completion provenance for backend callers,
  so a client cannot forge it.

Wakes stay non-owner turns; the new fields are facts, not authority.
@VACInc VACInc self-assigned this Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 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 docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: S labels Oct 21, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR exposes the starting run of background exec completions to plugin tools through embedded and CLI MCP contexts.

Example: Run owner-start-turn starts sleep 2; echo WAKE_EXEC_DONE and ends before the command finishes.

  • Before: The completion's plugin tool context has neither its own runId nor inputProvenance linking it to owner-start-turn.
  • After: The context contains the wake's runId and inputProvenance.runId=owner-start-turn, while senderIsOwner remains false.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, narrowly scoped, and supported by production Gateway traces and green exact-head checks; two forwarding-only tests add limited value.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; supplied logs nevertheless show chat.send launching real background exec and the subsequent plugin execution receiving distinct wake and origin run IDs through built Gateway embedded and MCP paths, with scripted model and CLI fixtures.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Plugin tools cannot correlate a background command's completion turn with the earlier run that launched it.
Reason: The maintainer-authored proposal supplies a narrow missing SDK capability, documents its limitations, and preserves plugin-owned policy and host authorization.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR supplies useful completion correlation that current main lacks, with no concrete production defect found.

Priority: P2
Reviewed head: 04c2f9412cfd829d7c34c484180b2bad434e5a5b

Before merge

None.

Findings

None.

Tests

  • Low-value test src/agents/openclaw-tools.plugin-context.test.ts: Remove the added helper field-copy assertion; it repeats the implementation without exercising plugin construction or execution.
  • Low-value test src/gateway/tool-resolution.memory-audience.test.ts: Remove the added provenance mock-call assertion; it observes constructor arguments rather than the MCP-to-plugin behavior exercised by the supplied Gateway proof.
Agent review details

How this fits together

The exec process registry retains launch facts, session-event admission creates the completion turn, and embedded or MCP tool construction passes its context to plugins.

flowchart LR
  A[Starting agent turn] --> B[Background exec process]
  B --> C[Completion notifier]
  C --> D[Session event admission]
  D --> E[Embedded tool context]
  D --> F[CLI MCP grant]
  E --> G[Plugin tool factory]
  F --> G
Loading

Technical review

Best possible solution:

Carry optional run correlation through the existing exec, session-event, and plugin-context owners while preserving independent live authorization.

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

Current-main source omits the originating run from completion provenance and plugin contexts, matching the supplied before traces; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is a small, complete extension of existing owners, with no parallel policy manager or alternative notification path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction and current-main comparison: The introduced diff carries originRunId through existing owners; comparison with fetched main confirms the production files still lack these additions. (src/agents/bash-tools.exec-run.ts:588, 04c2f9412cfd)
  • Non-owner completion semantics preserved: Session-event context retains CommandAuthorized=false and internal_system provenance, adding only the optional originating run ID. (src/auto-reply/reply/session-event-context.ts:85, 04c2f9412cfd)
  • MCP provenance comes from the host grant: Run-bound MCP requests copy the stored grant context; attach and header-derived contexts do not accept caller-supplied inputProvenance or runId. (src/gateway/mcp-http.request.ts:284, 04c2f9412cfd)
  • Supplied behavior evidence and owner direction: The full maintainer-authored body supplies before/after plugin execution traces from isolated built Gateways on embedded and Claude CLI MCP paths, using scripted provider and CLI fixtures; it explicitly retains non-owner wakes and treats correlation as informational. (04c2f9412cfd)
  • Exact-head checks: Both check-run pages contain no failed or pending checks, and openclaw/ci-gate, dependency review, and security-sensitive review report success for the reviewed head. (04c2f9412cfd)
  • Prior continuation contract: fix: owner-gated plugin calls fail after the parent yields #150295 established versioned plugin continuation authority; this PR preserves that contract and adds correlation metadata without promoting wakes to owner turns. (src/plugins/tool-types.ts:143, 861f60e0bc5c)

Likely related people:

  • Peter Steinberger: Raw commit 753a7a5 adds src/agents/bash-tools.exec-notify.ts:95 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 753a7a57be10; files: src/agents/bash-tools.exec-notify.ts)
  • Vito Cappello: Raw commit 861f60e adds src/plugins/tool-types.ts:85 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 861f60e0bc5c; files: src/plugins/tool-types.ts)
  • Stronggenetics: Raw commit 72f5840 adds src/agents/cli-runner/mcp-grant-context.ts:193 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 72f5840c1192; files: src/agents/cli-runner/mcp-grant-context.ts)

PR surface

Source +35, Tests +105, Docs +11. Total +151 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 41 6 +35
Tests 5 105 0 +105
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 157 6 +151

Review metrics

Metric Value Why it matters
Public plugin context 2 new optional fields runId and inputProvenance extend the existing SDK context without adding configuration or required parameters.

Labels

Label changes:

  • add P2: This is a bounded improvement for plugin authors correlating background completion turns.
  • add merge-risk: 🚨 compatibility: The public plugin context gains optional metadata; the maintainer-authored direction explicitly accepts this additive contract while preserving existing owner and continuation semantics.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded improvement for plugin authors correlating background completion turns.
  • merge-risk: 🚨 compatibility: The public plugin context gains optional metadata; the maintainer-authored direction explicitly accepts this additive contract while preserving existing owner and continuation semantics.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 21, 2026, 5:56 PM ET / 21:56 UTC.

@VACInc
VACInc merged commit f6ee991 into openclaw:main Oct 22, 2026
149 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
…tools (openclaw#179816)

A background exec completion wake reached plugins as
{ kind: "internal_system", sourceTool: "exec" } with no link to the run
that started the command, and plugin tool factories received neither the
turn's run id nor its input provenance. On claude-cli agents the MCP
loopback grant also dropped internal provenance. A plugin therefore could
not tell the completion of a command its owner started from any other
internal turn.

- exec records the starting run on the process and the completion wake
  stamps it as InputProvenance.runId.
- plugin tool contexts expose runId and inputProvenance on both the
  embedded runtime and the claude-cli MCP loopback; the CLI grant carries
  internal-system provenance, which requester policy does not read.
- the agent RPC reserves exec completion provenance for backend callers,
  so a client cannot forge it.

Wakes stay non-owner turns; the new fields are facts, not authority.

Co-authored-by: VACInc <[email protected]>

n572770 commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Additional downstream plugin-compatibility evidence from Windows x64 / Node 26.12.1, using the official 2026.10.10-beta.3 package at 15dffe5258a93c3d9c5dfd0a2b2de9989ebe7e14:

  • In that release, PluginHookAgentContext provides runId, while OpenClawPluginToolContext<2> does not. The v2 context does provide assertInvocationCurrent, native channel/account/sender and session identity.
  • A LINE business plugin that captures an explicit current-human task command in before_prompt_build and validates it in a trusted tool-policy callback cannot carry that exact run correlation into its v2 tool executor by reading a documented ctx.runId on beta.3.
  • The added public fields here address that SDK gap. We are moving away from local core patches and keeping compatibility handling in the plugin until an official packaged release contains this change. Correlation is not authorization: native invocation guards, sender/session checks and fresh business ACL checks remain necessary.

Please make the first packaged version carrying these optional tool-context fields clear in release notes/SDK compatibility guidance. No claim of a live end-to-end test of this PR is intended; this is release-contract/source verification. In particular, MODEL_REPLY_SOURCE_UNPROVEN / modelInputProtection failures from our earlier locally modified build are not being attributed to stock OpenClaw and should not be treated as a reproduction of this PR's bug.

No credentials, transcripts, private identifiers or business data are included.

obviyus added a commit that referenced this pull request Nov 14, 2026
…nds exit together (#199113)

## What Problem This Solves

Fixes: when several background commands exit close together, the agent gets one wake turn per command, so three exits cost three model turns and three replies.

## User Impact

User impact: completions that arrive while an earlier completion turn in the same conversation is still queued or running now reach the agent together in one turn, with each result's process ID, status, exit code and output tail. A single completion starts at once, exactly as before.

## Why This Change Was Made

Each exit enqueued its own session event and became its own turn. The session event owner already turns a set of exact queued occurrences into one ordinary turn (`occurrences`, used by session-state notices), and `combineSessionEventTargetsForHost` already checks that a set shares one destination and requester authority. This change reuses both:

- New `session-event-batch.ts` in the session event owner keeps one in-flight completion turn per conversation. A completion with nothing in flight starts at once through `enqueueSessionEventForHost`, unchanged. A completion that arrives while that turn is queued or running claims its queued occurrence and waits. One second after the turn settles, every waiting completion that shares the same exec request owners, launching run, route and combinable target starts one turn with all of their occurrences.
- `bash-tools.exec-notify.ts` only switches its enqueue import to the batched entry point. Each result keeps the wake format from #199122 (`Exec completed (<id>, code 0, 4m3s):` plus a tail of up to 2,000 chars).
- One shared turn carries at most about 8,000 characters of results. Occurrence text must stay byte-exact, so the bound limits membership, not text: results past the budget start the next turn.
- The exec completion guidance is count-neutral ("Treat each completion result above as an internal continuation…") so a batched turn no longer says "this completion" for several results.

Choices and accepted edges:

- **A 1 s settle, only for completions that already waited.** A first or lone completion still starts at once (measured base: its turn starts within about 1 s of the exit, before later exits arrive), so no delay is added to single wakes. Without a settle, exits about 1 s apart sometimes straddle the end of the turn they waited behind: on the intermediate head, 2 of 6 trials split into three turns because the last exit arrived just after the batch started. Waiting completions now start 1 s after that turn settles, so stragglers join.
- **Only one request's completions share a turn.** Stop aborts every exec request owner of a turn, so mixing requests would let one Stop retire another request's result. Completions from different requests keep separate turns.
- **Only one launching run's completions share a turn.** The completion turn's input provenance names the run that launched the command, which plugins use to correlate a completion with its run (#179816). Request owners carry over into completion turns, so commands launched by a later run can share owners with earlier ones; the batch also requires the same launching run, and each shared turn keeps a truthful `inputProvenance.runId`.
- **Cron-run completions never wait.** They check at acceptance that the originating run is still alive; holding them could turn an accepted completion into a refused one.
- Removing one member after its shared turn is queued (for example, the model polled that result) leaves the shared prompt as is; the turn is retired only when every member is removed. Before the shared turn is queued, removal drops just that member.
- A waiting completion starts after its predecessor settles, so a human message queued in `followup` or `collect` mode meanwhile can run first.
- Rebased on #199122 (wake format) and #199085. This PR touches only the import line in `bash-tools.exec-notify.ts` and the guidance wording in `agent-runner-run-params.ts`.

## Evidence

**Real-agent E2E** (isolated source Gateway via `ocx src`, real OpenAI model, 6 concurrent trial sessions per arm). Each trial asks the agent to start three background waiters with `yieldMs`, waits until the session is idle with all three running, then releases them 1 s apart. Base = current `main` (`afeadf1c4fe0`, includes #199122); fix = this PR rebased on it.

| Arm | Wake turns (6 trials) | Results acknowledged | Wake-turn tokens (total) | Wake-turn cost |
| --- | --- | --- | --- | --- |
| base, 3 exits | 18 (3 per trial) | 18/18 | 501,233 | $1.152 |
| fix, 3 exits | 12 (2 per trial) | 18/18 | 326,362 (-35%) | $0.930 |
| base, 1 exit | 6 | 6/6 | 153,377 | $0.402 |
| fix, 1 exit | 6 | 6/6 | 153,934 | $0.403 |

Single-exit wake latency (release to wake message, median of 6): base 0.85 s, fix 0.85 s. A single completion never waits for the settle. Time from release to the last reply in the 3-exit arm: base median 9.2 s, fix median 7.3 s.

Every fix trial: the first exit starts its turn at once; the two later exits arrive during it and share the next turn, each keeping its own id, exit code, duration and tail. Results from earlier runs before the rebase (same arms, older wake format) matched: 12 turns vs 18.

<details><summary>Redacted trace, trial 1 (times relative to release of the first waiter)</summary>

Base (before the rebase, old wake format):

```
  +8.8s USER: Exec completed (gentle-c, code 0) :: job 1 result: r11-1603127358
 +11.7s reply (26930 tok): job 1 result: r11-1603127358
 +19.1s USER: Exec completed (dawn-gla, code 0) :: job 2 result: r12-78193628
 +22.0s reply (27407 tok): job 2 result: r12-78193628
 +26.5s USER: Exec completed (kind-sum, code 0) :: job 3 result: r13-1811516849
 +29.2s reply (27885 tok): job 3 result: r13-1811516849
```

Fix (rebased head):

```
  +1.2s USER: Exec completed (tide-cov, code 0, 34s): job 1 result: r11-1383216
  +3.7s reply (26761 tok): job 1 result: r11-1383216
  +5.1s USER: Exec completed (tidy-com, code 0, 32s): job 2 result: r12-262323306
              Exec completed (rapid-bi, code 0, 29s): job 3 result: r13-179203848
  +7.7s reply (27281 tok): job 2 result: r12-262323306 / job 3 result: r13-179203848
```

</details>

**Regression tests:** `bash-tools.exec-background-followup.test.ts` runs three real background commands through the exec tool and the real session event owner with a held first model turn. Same launching run: base starts three completion turns (red); the fix starts two, the second carrying both later results and naming their run. Different launching runs with shared request owners: the later results keep separate turns, each naming its own run (red without the launch-run check). Five results of ~2,000 chars: the shared turn takes three and the fifth starts its own turn (size bound).

**Focused suites (`ocx test`, rebased head, 14 files):** `bash-tools.exec-background-followup`, `bash-tools.test`, `bash-tools.exec-runtime`, `bash-tools.exec-runtime.cleanup`, `bash-tools.visible-subagent-notify`, `bash-tools.exec-request-stop`, `bash-tools.exec.egress-lifecycle`, `bash-tools.notify-on-exit-ack`, `bash-tools.process.e2e`, `bash-tools.exec-notify.requester`, `bash-tools.exec-notify.queue-full`, `infra/exec-session-event`, `session-event-handoff`, `agent-runner-execution-session-events`: all pass. `exec-session-event`'s chained-completion case now waits for the second receipt, which starts after the 1 s settle.

**Full tier:** `ocx build --dts` (full profile) built `92847fc`; the self-contained source package passed its tarball integrity check, installed with npm into a scratch prefix, and the packed CLI reported `OpenClaw 2026.11.3 (92847fc)` with `gateway --help` exit 0. The later head commit only changes a test type.

**Gaps:** E2E covers exits from one request in an idle Control UI-style session; completions from different requests and channel-delivered sessions are covered by the shared owner's existing tests, not by a new live run.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…nds exit together (openclaw#199113)

## What Problem This Solves

Fixes: when several background commands exit close together, the agent gets one wake turn per command, so three exits cost three model turns and three replies.

## User Impact

User impact: completions that arrive while an earlier completion turn in the same conversation is still queued or running now reach the agent together in one turn, with each result's process ID, status, exit code and output tail. A single completion starts at once, exactly as before.

## Why This Change Was Made

Each exit enqueued its own session event and became its own turn. The session event owner already turns a set of exact queued occurrences into one ordinary turn (`occurrences`, used by session-state notices), and `combineSessionEventTargetsForHost` already checks that a set shares one destination and requester authority. This change reuses both:

- New `session-event-batch.ts` in the session event owner keeps one in-flight completion turn per conversation. A completion with nothing in flight starts at once through `enqueueSessionEventForHost`, unchanged. A completion that arrives while that turn is queued or running claims its queued occurrence and waits. One second after the turn settles, every waiting completion that shares the same exec request owners, launching run, route and combinable target starts one turn with all of their occurrences.
- `bash-tools.exec-notify.ts` only switches its enqueue import to the batched entry point. Each result keeps the wake format from openclaw#199122 (`Exec completed (<id>, code 0, 4m3s):` plus a tail of up to 2,000 chars).
- One shared turn carries at most about 8,000 characters of results. Occurrence text must stay byte-exact, so the bound limits membership, not text: results past the budget start the next turn.
- The exec completion guidance is count-neutral ("Treat each completion result above as an internal continuation…") so a batched turn no longer says "this completion" for several results.

Choices and accepted edges:

- **A 1 s settle, only for completions that already waited.** A first or lone completion still starts at once (measured base: its turn starts within about 1 s of the exit, before later exits arrive), so no delay is added to single wakes. Without a settle, exits about 1 s apart sometimes straddle the end of the turn they waited behind: on the intermediate head, 2 of 6 trials split into three turns because the last exit arrived just after the batch started. Waiting completions now start 1 s after that turn settles, so stragglers join.
- **Only one request's completions share a turn.** Stop aborts every exec request owner of a turn, so mixing requests would let one Stop retire another request's result. Completions from different requests keep separate turns.
- **Only one launching run's completions share a turn.** The completion turn's input provenance names the run that launched the command, which plugins use to correlate a completion with its run (openclaw#179816). Request owners carry over into completion turns, so commands launched by a later run can share owners with earlier ones; the batch also requires the same launching run, and each shared turn keeps a truthful `inputProvenance.runId`.
- **Cron-run completions never wait.** They check at acceptance that the originating run is still alive; holding them could turn an accepted completion into a refused one.
- Removing one member after its shared turn is queued (for example, the model polled that result) leaves the shared prompt as is; the turn is retired only when every member is removed. Before the shared turn is queued, removal drops just that member.
- A waiting completion starts after its predecessor settles, so a human message queued in `followup` or `collect` mode meanwhile can run first.
- Rebased on openclaw#199122 (wake format) and openclaw#199085. This PR touches only the import line in `bash-tools.exec-notify.ts` and the guidance wording in `agent-runner-run-params.ts`.

## Evidence

**Real-agent E2E** (isolated source Gateway via `ocx src`, real OpenAI model, 6 concurrent trial sessions per arm). Each trial asks the agent to start three background waiters with `yieldMs`, waits until the session is idle with all three running, then releases them 1 s apart. Base = current `main` (`faf88178b453`, includes openclaw#199122); fix = this PR rebased on it.

| Arm | Wake turns (6 trials) | Results acknowledged | Wake-turn tokens (total) | Wake-turn cost |
| --- | --- | --- | --- | --- |
| base, 3 exits | 18 (3 per trial) | 18/18 | 501,233 | $1.152 |
| fix, 3 exits | 12 (2 per trial) | 18/18 | 326,362 (-35%) | $0.930 |
| base, 1 exit | 6 | 6/6 | 153,377 | $0.402 |
| fix, 1 exit | 6 | 6/6 | 153,934 | $0.403 |

Single-exit wake latency (release to wake message, median of 6): base 0.85 s, fix 0.85 s. A single completion never waits for the settle. Time from release to the last reply in the 3-exit arm: base median 9.2 s, fix median 7.3 s.

Every fix trial: the first exit starts its turn at once; the two later exits arrive during it and share the next turn, each keeping its own id, exit code, duration and tail. Results from earlier runs before the rebase (same arms, older wake format) matched: 12 turns vs 18.

<details><summary>Redacted trace, trial 1 (times relative to release of the first waiter)</summary>

Base (before the rebase, old wake format):

```
  +8.8s USER: Exec completed (gentle-c, code 0) :: job 1 result: r11-1603127358
 +11.7s reply (26930 tok): job 1 result: r11-1603127358
 +19.1s USER: Exec completed (dawn-gla, code 0) :: job 2 result: r12-78193628
 +22.0s reply (27407 tok): job 2 result: r12-78193628
 +26.5s USER: Exec completed (kind-sum, code 0) :: job 3 result: r13-1811516849
 +29.2s reply (27885 tok): job 3 result: r13-1811516849
```

Fix (rebased head):

```
  +1.2s USER: Exec completed (tide-cov, code 0, 34s): job 1 result: r11-1383216
  +3.7s reply (26761 tok): job 1 result: r11-1383216
  +5.1s USER: Exec completed (tidy-com, code 0, 32s): job 2 result: r12-262323306
              Exec completed (rapid-bi, code 0, 29s): job 3 result: r13-179203848
  +7.7s reply (27281 tok): job 2 result: r12-262323306 / job 3 result: r13-179203848
```

</details>

**Regression tests:** `bash-tools.exec-background-followup.test.ts` runs three real background commands through the exec tool and the real session event owner with a held first model turn. Same launching run: base starts three completion turns (red); the fix starts two, the second carrying both later results and naming their run. Different launching runs with shared request owners: the later results keep separate turns, each naming its own run (red without the launch-run check). Five results of ~2,000 chars: the shared turn takes three and the fifth starts its own turn (size bound).

**Focused suites (`ocx test`, rebased head, 14 files):** `bash-tools.exec-background-followup`, `bash-tools.test`, `bash-tools.exec-runtime`, `bash-tools.exec-runtime.cleanup`, `bash-tools.visible-subagent-notify`, `bash-tools.exec-request-stop`, `bash-tools.exec.egress-lifecycle`, `bash-tools.notify-on-exit-ack`, `bash-tools.process.e2e`, `bash-tools.exec-notify.requester`, `bash-tools.exec-notify.queue-full`, `infra/exec-session-event`, `session-event-handoff`, `agent-runner-execution-session-events`: all pass. `exec-session-event`'s chained-completion case now waits for the second receipt, which starts after the 1 s settle.

**Full tier:** `ocx build --dts` (full profile) built `92847fc`; the self-contained source package passed its tarball integrity check, installed with npm into a scratch prefix, and the packed CLI reported `OpenClaw 2026.11.3 (92847fc)` with `gateway --help` exit 0. The later head commit only changes a test type.

**Gaps:** E2E covers exits from one request in an idle Control UI-style session; completions from different requests and channel-delivered sessions are covered by the shared owner's existing tests, not by a new live run.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 16, 2026
…#200097)

## What Problem This Solves

Background commands, `sessions_yield` waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs:

- A later turn could not yield on a command that an earlier turn started. `listYieldAwaitableExecs(runId)` matched `originRunId === runId`, so `sessions_yield` returned `nothing_pending` and the model started to poll.
- A paused subagent task continued only when the wake named the paused run. #200046 patched one caller of this: it moved the running commands to the new run (`moveRunningSessionsToRun`).
- Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered".

## Why This Change Was Made

The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner:

- `listYieldAwaitableExecs`, `awaitExecsForYield` and `openExecYieldResume` are keyed by the chat: agent id plus session key, so a raw shared key such as `global` stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs.
- Reply admission continues the task that is paused in the chat, whichever run paused it (`continuesPausedTask` replaces `pausedRunId`).
- Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of `completionRequesterSessionId` / `LifecycleRevision`, the settle-receipt exact compare, the collector and `agents_wait` incarnation filters, and the reset replacement notice are deleted.
- Deleted: `ProcessSession.originRunId`, `moveRunningSessionsToRun` (the #200046 patch), `matchesSubagentRequesterSession`, `recordRequesterReplacementNotice`, `listCollectorRunsForRequesterIncarnation` (now `listCollectorRunsForRequester`).
- Kept as a fact only: an exec wake still names the starting run in `inputProvenance.runId` (`ProcessSession.startedByRunId`), because plugins use it (#179816). It routes nothing.
- The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change.

Production delta: −227 lines in `src` (+127 / −354); whole PR −427.

## User Impact

- A chat can start a background command in one turn and wait for it with `sessions_yield` in a later turn. The exit continues the chat.
- A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run.
- A subagent result reaches the parent chat after `/new` or compaction instead of being withheld.

## Evidence

Real agent on an isolated source Gateway (`ocx src`, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base `96ad377596ca`, head = this PR.

| Journey | base | head |
|---|---|---|
| J1: #200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) | parent got `child-final` (with the #200046 patch) | parent got `child-final` (patch deleted); registry `generation=4 delivery=delivered` |
| J2: run 1 starts a background command; run 2 calls `sessions_yield` | `{"status":"nothing_pending"}` | `{"status":"yielded"}`; the exit wakes the chat, which replies `j2-woke` |
| J3: parent spawns a child and does not yield | ordinary completion (`subagent_announce`) | ordinary completion (`subagent_announce`) |
| J1 parent side: parent yields on its child | private completion (`subagent_settle`) | private completion (`subagent_settle`) |

Head arms ran on the production code of `3793f6d`; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover.

A `/new` while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR.

Unit: `openclaw-tools.requester-yield.test.ts` now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session.

Gates: oxfmt, oxlint on changed files, `pnpm tsgo:core`, `pnpm check:test-types`, `ocx test` on `src/agents/subagents/`, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, `src/cron/isolated-agent`. Build, full suites and cross-OS checks: hosted CI on this head. `src/gateway/server-startup-post-attach.test.ts` fails the same way on the merge base `059db8a`; this PR does not touch it.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…openclaw#200097)

## What Problem This Solves

Background commands, `sessions_yield` waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs:

- A later turn could not yield on a command that an earlier turn started. `listYieldAwaitableExecs(runId)` matched `originRunId === runId`, so `sessions_yield` returned `nothing_pending` and the model started to poll.
- A paused subagent task continued only when the wake named the paused run. openclaw#200046 patched one caller of this: it moved the running commands to the new run (`moveRunningSessionsToRun`).
- Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered".

## Why This Change Was Made

The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner:

- `listYieldAwaitableExecs`, `awaitExecsForYield` and `openExecYieldResume` are keyed by the chat: agent id plus session key, so a raw shared key such as `global` stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs.
- Reply admission continues the task that is paused in the chat, whichever run paused it (`continuesPausedTask` replaces `pausedRunId`).
- Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of `completionRequesterSessionId` / `LifecycleRevision`, the settle-receipt exact compare, the collector and `agents_wait` incarnation filters, and the reset replacement notice are deleted.
- Deleted: `ProcessSession.originRunId`, `moveRunningSessionsToRun` (the openclaw#200046 patch), `matchesSubagentRequesterSession`, `recordRequesterReplacementNotice`, `listCollectorRunsForRequesterIncarnation` (now `listCollectorRunsForRequester`).
- Kept as a fact only: an exec wake still names the starting run in `inputProvenance.runId` (`ProcessSession.startedByRunId`), because plugins use it (openclaw#179816). It routes nothing.
- The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change.

Production delta: −227 lines in `src` (+127 / −354); whole PR −427.

## User Impact

- A chat can start a background command in one turn and wait for it with `sessions_yield` in a later turn. The exit continues the chat.
- A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run.
- A subagent result reaches the parent chat after `/new` or compaction instead of being withheld.

## Evidence

Real agent on an isolated source Gateway (`ocx src`, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base `2baaa3c275a3`, head = this PR.

| Journey | base | head |
|---|---|---|
| J1: openclaw#200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) | parent got `child-final` (with the openclaw#200046 patch) | parent got `child-final` (patch deleted); registry `generation=4 delivery=delivered` |
| J2: run 1 starts a background command; run 2 calls `sessions_yield` | `{"status":"nothing_pending"}` | `{"status":"yielded"}`; the exit wakes the chat, which replies `j2-woke` |
| J3: parent spawns a child and does not yield | ordinary completion (`subagent_announce`) | ordinary completion (`subagent_announce`) |
| J1 parent side: parent yields on its child | private completion (`subagent_settle`) | private completion (`subagent_settle`) |

Head arms ran on the production code of `3793f6d`; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover.

A `/new` while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR.

Unit: `openclaw-tools.requester-yield.test.ts` now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session.

Gates: oxfmt, oxlint on changed files, `pnpm tsgo:core`, `pnpm check:test-types`, `ocx test` on `src/agents/subagents/`, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, `src/cron/isolated-agent`. Build, full suites and cross-OS checks: hosted CI on this head. `src/gateway/server-startup-post-attach.test.ts` fails the same way on the merge base `113d415`; this PR does not touch it.

Co-authored-by: Ayaan Zaidi <[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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

2 participants