Skip to content

fix(agents): wake on every background exit and carry the result - #199122

Merged
obviyus merged 5 commits into
mainfrom
fix/exec-uniform-exit-wake
Nov 14, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/exec-uniform-exit-wake

Conversation

@obviyus

@obviyus obviyus commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: a background command that waits silently (it exits 0 with no output when the awaited thing is true, for example ci-wait, sleep 600 or gh run watch --exit-status) never wakes a Control UI, dashboard or API conversation. These sessions default to tools.exec.notifyOnExitEmptySuccess=false. The agent is told this, so it keeps the turn open and polls the command every 30 s until it exits. When the automations tool is available, OpenAI agents instead schedule a one-shot automation that re-checks every minute. Each re-check is a model turn, and most of them answer NO_REPLY.

User Impact

User impact: an agent that waits for CI, a deploy or a delay starts one background command and ends its turn. The command's exit wakes the conversation, and the wake already contains the result. This holds for a silent success too. Fewer model round trips and tokens per wait. Saved, recurring and cross-session follow-ups still use automations.

Why This Change Was Made

Root cause (current main):

  • resolveExecNotificationDefaults defaults notifyOnExitEmptySuccess to true only for chat-channel providers. A wake-armed command in any other session wakes nobody on silent success. The running result therefore says "Its exit wakes this conversation if it prints output or fails, not after a silent success … If it may succeed silently, collect it with poll." The agent follows that and polls.
  • The wake text compacts output to 180 chars. Woken agents re-read the result with process log or re-run the check.
  • The automations description offers "To come back here later (wait for CI, recheck), add an at + agentTurn job", and the exec description says "No sleep loops for reminders/follow-ups; use automations". So an in-conversation one-time wait becomes a polling automation.

Fix (inside the existing exec/process, automations and skill owners; no new tool, state or stored-row change):

  • Default flip (approved): tools.exec.notifyOnExitEmptySuccess now defaults to true for every session. The knob stays as an opt-out. Retiring it would change the durable process record, which stores the captured value. hasExitWake now also requires the captured empty-success wake, so an opt-out session gets the manual-collection guidance. The Control UI waiting card (wakesSession) reads the same fact, so it no longer appears for an opt-out session that a silent success would not continue. The "may succeed silently, collect with poll" branch is gone. Existing suppressions are unchanged: cancel, request Stop, manual kill, terminal poll observed, hidden subagents and ended cron runs.
  • One contract on every surface (running result, idle poll, exec description): the exit wakes the conversation with the result, silent success included; end the turn if only waiting remains; do not poll or start another command for the same result. To wait for a condition or a time, run one command that loops until it holds, exits non-zero on failure states and prints the result. The running result now shows the deadline (…, pid 123), times out in 29m59s.) instead of an ISO timestamp. The sibling list and the yieldMs cap note stay.
  • Wake message: Exec completed (<id>, code 0, 4m3s): followed by the retained output tail (last 2,000 chars, raw newlines). Longer output says last 2000 of N output chars (process log has the rest). If the retention cap already discarded the start, it says process log keeps the last N; earlier output was discarded. A silent exit says … with no output.. Timeout retry guidance is unchanged. Memory export's exec-notice filter (memory-host-sdk isExecCompletionEvent) recognizes the new format as well as the historical ones, so notices and output tails stay out of searchable memory.
  • Automations description: a one-time wait inside this conversation is one background exec, not an automation. Automations are for saved reminders, recurring work and cross-session follow-ups.
  • GitHub skill: a "Wait for CI" recipe (gh pr checks <n> --watch --fail-fast, gh run watch <id> --exit-status) as one background exec.
  • Docs: docs/tools/exec.md, docs/gateway/background-process.md, docs/gateway/config-tools/built-in-tools.md, docs/web/control-ui/chat.md, config help. Prompt snapshots refreshed for the automations text.

Accepted edge cases: subagent sessions and active cron runs now also get an event on silent success. Before, this happened only when they had a chat provider. Subagents get it as a queued system event, not a wake. An active cron run gets it as a follow-up after the run. An operator who wants quiet successes sets notifyOnExitEmptySuccess=false.

Evidence

Real agent, isolated source Gateway (ocx src, pinned Bun fork, own state/port/HOME). Arms: openai/gpt-6-astra (OpenClaw runtime) and Claude Opus through the shared Claude proxy. Direct tool surface. Each trial is a fresh session. Fake CI flips to passed 240 s after the first check. 6 trials per arm. base = f091e80650aa (current main), fix = this head. Measured from the Gateway's own transcript store.

(a) Silent waiter. "ci-wait blocks until all checks pass, then exits 0 without printing. Start it as a background command, by itself. After it exits, run ci-status once…", automations denied:

Arm Silent waiter woken by its exit process poll calls Turns Tokens / trial
base, OpenAI 0/6 43 6 314k
fix, OpenAI 6/6 0 12 168k
base, Claude 0/6 48 6 420k
fix, Claude 6/6 0 12 209k

Base: start the waiter, then process poll timeout=30000 about 8 times until it exits, in one long turn. Fix: start it, end the turn, then Exec completed (…, code 0, 4m2s) with no output. wakes the agent, which runs ci-status once and answers. All 24 trials delivered the final answer.

A softer variant ("run it as is, by itself", no "background") lets the agent choose. Base OpenAI: 5 trials backgrounded the waiter; 0/5 woken, 36 polls. Fix: 3/3 woken, 0 polls; the other 3 trials blocked in turn with awaitResults. Claude base blocked in turn in 6/6. Claude fix: 3/3 backgrounded waiters woken, 0 polls.

(b) S2, existing scenario (printing status check, automations denied). No regression:

Arm Final delivered process poll calls NO_REPLY wake turns Tokens / trial
base, OpenAI 5/6 0 2 206k
fix, OpenAI 6/6 0 0 174k
base, Claude 6/6 8 0 310k
fix, Claude 6/6 0 0 203k

The undelivered base trial wrote a loop that matched *"all checks pass"*. That pattern never matched all 15 checks passed, so the loop ran past the trial window (an agent parsing bug). A separate Claude run on the parent of the previous waiter fix (18892937) made 69 polls in 6 trials. On main it made 8 polls.

(c) S1, automations allowed (same prompt): which mechanism does the agent choose for the wait?

Arm Trials with one-shot automation Trials with background exec Turns NO_REPLY turns Tokens / trial
base, OpenAI 6/6 0/6 30 18 708k
fix, OpenAI 0/6 6/6 (all woken, 0 polls) 12 0 161k
base, Claude 0/6 5/6 (7 polls) 11 0 279k
fix, Claude 0/6 6/6 (all woken, 0 polls) 12 0 199k
fix (this head), OpenAI 0/6 6/6 (5 woken, 0 polls) 11 0 161k
fix (this head), Claude 0/6 6/6 (all woken, 0 polls) 12 0 199k

The first fix rows ran before review made the automations and skill wording conditional on an actual wake. The "this head" rows reran S1 on the final text. In one OpenAI trial, the agent's waiter matched all checks passed and never matched all 15 checks passed, so it ran past the window. That is the same agent parsing bug as in (b); the trial made 0 polls and scheduled no automation.

Base OpenAI scheduled an at job that re-ran ci-status every minute and answered NO_REPLY until CI passed. With the fix, the first wake already carried the passing line, so the agent answered without another tool call.

(d) No-wait control. "Run lint (about 20 s, prints nothing when clean), then tell me whether it passed":

Arm Final delivered Spurious (NO_REPLY) wake turns Turns
base, OpenAI 6/6 0 6
fix, OpenAI 6/6 0 8
base, Claude 6/6 0 6
fix, Claude 6/6 0 6

The 2 extra OpenAI fix turns are not spurious. Those trials ended the turn with "lint is running". The silent exit woke them, and they reported "Lint passed (exit code 0, no output; 21 seconds)". On base, that turn shape would leave the user without an answer. Commands collected in turn (awaitResults, or a poll that observed the exit) produced no wake.

Redacted trace, Claude silent waiter, fix:

+212s exec {"yieldMs": 1000} '<ws>/pr-1/ci-wait'
+214s   -> Command still running (session nova-valley:…, pid …), times out in 29m59s. Its exit wakes this conversation with the result, silent success included. If only waiting remains, end this turn now; do not poll it or start another command for the same result. …
+218s reply: I've started `ci-wait` for PR #4241 in the background. When it exits, I'll run `ci-status` …
+457s USER: Exec completed (nova-val, code 0, 4m2s) with no output.
+462s exec {} '<ws>/pr-1/ci-status'
+463s   -> PR #4241: all 15 checks passed. Summary: build-1-… green
+470s reply: PR #4241 is ready. …

Same scenario, base: exec background returns "Its exit wakes this conversation if it prints output or fails, not after a silent success…", then eight process poll timeout=30000 calls each return (no new output) Process still running. until Process exited with code 0..

Tests (vitest-source):

  • bash-tools.test.ts: a non-chat session wakes on empty success by default; an explicit false stays quiet.
  • bash-tools.exec-background-followup.test.ts: the running result carries the single contract and times out in; a dashboard conversation is woken on silent success with exit, duration and a bounded 2,000-char tail.
  • memory-host-sdk session-files.test.ts: historical and current exec notices (silent, tail, retention-truncated) stay out of the memory export.
  • The first two files are red on main (7 failures) and green here. The exec/process, durable notify, descriptions, automations schema, config help, prefix-stability and system-prompt suites pass. The UTF-16 boundary test now covers the retained-tail boundary.

Upgrade: the stored config and state shapes do not change. A saved true or false keeps its meaning (bash-tools.test.ts covers the explicit false). An omitted setting adopts the new default when the command starts. Durable records keep the policy they captured at start.

Full tier on this head: full build with declarations, then a packed tarball install. Tarball integrity, openclaw --version (2026.11.3 (f3d42f9), the pre-rebase head with the same code) and gateway --help pass, and the packed bash-tools.exec-output chunk carries the new guidance.

Limits:

  • The E2E ran on the direct tool surface. Code Mode was not measured.
  • The test host was heavily loaded during the runs, and some first sends needed a longer client timeout. One Claude fix trial in (a)-soft never started (n=5).
  • Spurious-turn counting is structural: wake turns whose reply is exactly NO_REPLY.

@clawsweeper

clawsweeper Bot commented Nov 14, 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: M labels Nov 14, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 14, 2026
obviyus and others added 3 commits November 15, 2026 00:55
A wake-armed background exec now wakes its conversation on silent
success too (tools.exec.notifyOnExitEmptySuccess defaults to true), so
one contract holds: the exit wakes the conversation with the result,
end the turn, do not poll. The running result shows its deadline, the
wake carries exit code, duration and a bounded 2,000-char tail, and the
automations and GitHub skill text route one-time waits to one
background command.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the fix/exec-uniform-exit-wake branch from b6014c5 to 18c0a9a Compare November 14, 2026 19:27
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR enables silent-success background completion wakes by default and includes duration and retained output in the completion event.

Example: A dashboard agent backgrounds ci-wait, which exits successfully without output after four minutes.

  • Before: The command does not wake the conversation, so the agent must collect its result by polling.
  • After: An Exec completed event wakes the conversation with exit code 0, duration, and an explicit no-output result.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and supplied Gateway evidence are convincing, with prior findings resolved; required upgrade validation remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Agents waiting for a silent background command in dashboard or API conversations keep polling or schedule repeated model checks instead of resuming once with the result.
Reason: The supplied comparative runs demonstrate useful reductions in polling, and maintainer authorship supplies direction for the documented default change.

Merge readiness

✅ Ready for maintainer review

This PR addresses a demonstrated background-wait problem that remains on main, and the previous findings are resolved; no new correctness defect was found.

Priority: P2
Reviewed head: 2b3f7b5ca4c9c6813ef8c130c4376c1c225ad73c

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supply a redacted latest-stable-to-head upgrade run showing saved true/false settings and existing session data remain intact while an omitted setting adopts the new wake default.
Agent review details

How this fits together

The exec owner captures notification policy and conversation identity when a command starts, then sends its terminal result through the existing session-event queue; process guidance, UI process observations, and memory export consume those facts.

flowchart TD
  A[Agent exec call] --> B[Captured process policy]
  B --> C[Background process]
  C --> D[Completion notification owner]
  D --> E[Session event queue]
  E --> F[Agent continuation]
  B --> G[Process guidance and UI]
  E --> H[Memory export filter]
Loading

Technical review

Best possible solution:

Keep the existing notification owner, uniform wake guidance, bounded result tail, historical memory filtering, and explicit quiet-success opt-out.

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

Main's notification-default resolver and empty-success suppression establish the path, corroborated by the supplied base-versus-fix Gateway results; no target code was executed during this review.

Is this the best way to solve the issue?

The patch repairs the existing notification policy and updates its producers, consumers, and guidance without introducing another scheduler, state owner, or configuration option.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Empty-success notification default changes intended behavior with a stated reason (agents: notify chat exec empty-success completions #93525: Enabled empty-success notifications for reply-capable chat channels while deliberately keeping generic sessions quiet; the current helper later absorbed that policy.)
  • Wake-aware waiting guidance keeps the original intent (2a8e0b3: Reduce repeated background polling and overlapping waiters while avoiding wake promises to sessions without continuation support.)
  • Cron completion admission keeps the original intent (d867f17: Cron agents must collect results before ending the originating run because later completion admission requires that run to remain active.)
  • Completion routing and bounded output keeps the original intent (753a7a5: Continue background completions through ordinary session execution with captured identity, route, permissions, and cancellation.)
  • Memory export exclusion keeps the original intent (516a142: Moved the existing renderer into its shared owner while preserving memory behavior; this is a carried implementation, not a verified original introduction of the exclusion.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced changes verified: Reviewed the pinned merge-base-to-head diff, separating this PR's edits from unrelated base movement. (2b3f7b5ca4c9)
  • Main retains the reported limitation: Current main still derives the omitted empty-success setting from whether messageProvider identifies a chat channel; the PR instead defaults it to true while preserving explicit false. (src/agents/bash-tools.exec-request-preparation.ts:168, bb905f76e55d)
  • Prior findings resolved: The latest commit extends memory export's existing completion filter for duration, silent-success, and output-tail formats, adds an export regression, and distinguishes recoverable omitted output from discarded output. (packages/memory-host-sdk/src/host/session-entry-render.ts:229, 2b3f7b5ca4c9)
  • Recorded production behavior: The PR body supplies a redacted isolated-Gateway trace showing a silent waiter returning a background handle, the agent ending its turn, a completion event arriving, and the resumed agent collecting status and answering; it also reports comparative trials and red-on-base regressions. (2b3f7b5ca4c9)
  • Intentional default change: The earlier chat-only default was deliberate in agents: notify chat exec empty-success completions #93525, crediting Sapientropic and wenkang-xie; this maintainer-authored PR explicitly changes that direction, preserves the opt-out, and records the additional passive subagent and active-cron events. (src/agents/bash-tools.exec-request-preparation.ts:168, 23589d9e7c16)
  • Existing ownership and compatibility preserved: Notification routing, cancellation suppression, terminal-poll acknowledgment, and cron acceptance remain with their existing owners; durable records retain their captured notifyOnExitEmptySuccess field without a schema change. (src/agents/bash-process-durable.ts:172, 2b3f7b5ca4c9)

Likely related people:

  • Ayaan Zaidi: Raw commit 2a8e0b3 adds src/agents/bash-tools.exec-output.ts:61 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2a8e0b3c6ed6; files: src/agents/bash-tools.exec-output.ts)
  • Peter Steinberger: Raw commit 753a7a5 adds src/agents/bash-tools.exec-notify.ts:29 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)
  • Vincent Koc: Raw commit d867f17 adds src/agents/bash-tools.exec-output.ts:70 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d867f1791447; files: src/agents/bash-tools.exec-output.ts)

PR surface

Source -4, Tests +55, Docs +14, Generated 0. Total +65 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 56 60 -4
Tests 11 101 46 +55
Docs 5 28 14 +14
Config 0 0 0 0
Generated 1 2 2 0
Other 0 0 0 0
Total 26 187 122 +65

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Existing default changed 1 default changed; 0 new configuration options Omitting notifyOnExitEmptySuccess now enables silent-success events for non-chat sessions; explicit saved booleans retain their meaning.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Background waits in dashboard and API conversations consume avoidable model turns or fail to resume after silent success, with polling available as a workaround.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-14T19:44:12.828Z sha 18c0a9a :: needs changes before merge. :: [P2] [P2] Condition the waiting recipes on an actual completion wake | [P2] [P2] Cite the incident behind the new skill rule
  • reviewed 2026-11-14T20:12:05.633Z sha 944577e :: needs changes before merge. :: [P2] Update memory’s completion filter with the new event format | [P3] Distinguish omitted output from discarded output

Reviewed November 14, 2026, 3:32 PM ET / 20:32 UTC (Revision 3).

@obviyus

obviyus commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 14, 2026
@obviyus

obviyus commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 14, 2026
@obviyus
obviyus merged commit 00636f0 into main Nov 14, 2026
149 checks passed
@obviyus
obviyus deleted the fix/exec-uniform-exit-wake branch November 14, 2026 20:56
@obviyus

obviyus commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 00636f0. A backgrounded exec whose exit wakes the conversation now wakes it on silent success too, and the wake carries exit code, duration and a 2,000-char tail. Real-agent E2E: silent waiter woken 0/6 -> 6/6 for OpenAI and Claude, polls 43 -> 0 and 48 -> 0; automations no longer used for one-time waits (6/6 -> 0/6).

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
…claw#199122)

## What Problem This Solves

Fixes: a background command that waits silently (it exits 0 with no output when the awaited thing is true, for example `ci-wait`, `sleep 600` or `gh run watch --exit-status`) never wakes a Control UI, dashboard or API conversation. These sessions default to `tools.exec.notifyOnExitEmptySuccess=false`. The agent is told this, so it keeps the turn open and polls the command every 30 s until it exits. When the automations tool is available, OpenAI agents instead schedule a one-shot automation that re-checks every minute. Each re-check is a model turn, and most of them answer `NO_REPLY`.

## User Impact

User impact: an agent that waits for CI, a deploy or a delay starts one background command and ends its turn. The command's exit wakes the conversation, and the wake already contains the result. This holds for a silent success too. Fewer model round trips and tokens per wait. Saved, recurring and cross-session follow-ups still use automations.

## Why This Change Was Made

**Root cause (current `main`):**

- `resolveExecNotificationDefaults` defaults `notifyOnExitEmptySuccess` to true only for chat-channel providers. A wake-armed command in any other session wakes nobody on silent success. The running result therefore says "Its exit wakes this conversation if it prints output or fails, not after a silent success … If it may succeed silently, collect it with poll." The agent follows that and polls.
- The wake text compacts output to 180 chars. Woken agents re-read the result with `process log` or re-run the check.
- The automations description offers "To come back here later (wait for CI, recheck), add an at + agentTurn job", and the exec description says "No sleep loops for reminders/follow-ups; use automations". So an in-conversation one-time wait becomes a polling automation.

**Fix (inside the existing exec/process, automations and skill owners; no new tool, state or stored-row change):**

- Default flip (approved): `tools.exec.notifyOnExitEmptySuccess` now defaults to true for every session. The knob stays as an opt-out. Retiring it would change the durable process record, which stores the captured value. `hasExitWake` now also requires the captured empty-success wake, so an opt-out session gets the manual-collection guidance. The Control UI waiting card (`wakesSession`) reads the same fact, so it no longer appears for an opt-out session that a silent success would not continue. The "may succeed silently, collect with poll" branch is gone. Existing suppressions are unchanged: cancel, request Stop, manual kill, terminal poll observed, hidden subagents and ended cron runs.
- One contract on every surface (running result, idle poll, exec description): the exit wakes the conversation with the result, silent success included; end the turn if only waiting remains; do not poll or start another command for the same result. To wait for a condition or a time, run one command that loops until it holds, exits non-zero on failure states and prints the result. The running result now shows the deadline (`…, pid 123), times out in 29m59s.`) instead of an ISO timestamp. The sibling list and the `yieldMs` cap note stay.
- Wake message: `Exec completed (<id>, code 0, 4m3s):` followed by the retained output tail (last 2,000 chars, raw newlines). Longer output says `last 2000 of N output chars (process log has the rest)`. If the retention cap already discarded the start, it says `process log keeps the last N; earlier output was discarded`. A silent exit says `… with no output.`. Timeout retry guidance is unchanged. Memory export's exec-notice filter (`memory-host-sdk` `isExecCompletionEvent`) recognizes the new format as well as the historical ones, so notices and output tails stay out of searchable memory.
- Automations description: a one-time wait inside this conversation is one background exec, not an automation. Automations are for saved reminders, recurring work and cross-session follow-ups.
- GitHub skill: a "Wait for CI" recipe (`gh pr checks <n> --watch --fail-fast`, `gh run watch <id> --exit-status`) as one background exec.
- Docs: `docs/tools/exec.md`, `docs/gateway/background-process.md`, `docs/gateway/config-tools/built-in-tools.md`, `docs/web/control-ui/chat.md`, config help. Prompt snapshots refreshed for the automations text.

Accepted edge cases: subagent sessions and active cron runs now also get an event on silent success. Before, this happened only when they had a chat provider. Subagents get it as a queued system event, not a wake. An active cron run gets it as a follow-up after the run. An operator who wants quiet successes sets `notifyOnExitEmptySuccess=false`.

## Evidence

**Real agent, isolated source Gateway** (`ocx src`, pinned Bun fork, own state/port/HOME). Arms: `openai/gpt-6-astra` (OpenClaw runtime) and Claude Opus through the shared Claude proxy. Direct tool surface. Each trial is a fresh session. Fake CI flips to passed 240 s after the first check. 6 trials per arm. base = `c73a5496eba7` (current `main`), fix = this head. Measured from the Gateway's own transcript store.

**(a) Silent waiter.** "`ci-wait` blocks until all checks pass, then exits 0 without printing. Start it as a background command, by itself. After it exits, run `ci-status` once…", `automations` denied:

| Arm | Silent waiter woken by its exit | `process poll` calls | Turns | Tokens / trial |
|---|---|---|---|---|
| base, OpenAI | **0/6** | 43 | 6 | 314k |
| fix, OpenAI | **6/6** | **0** | 12 | 168k |
| base, Claude | **0/6** | 48 | 6 | 420k |
| fix, Claude | **6/6** | **0** | 12 | 209k |

Base: start the waiter, then `process poll timeout=30000` about 8 times until it exits, in one long turn. Fix: start it, end the turn, then `Exec completed (…, code 0, 4m2s) with no output.` wakes the agent, which runs `ci-status` once and answers. All 24 trials delivered the final answer.

A softer variant ("run it as is, by itself", no "background") lets the agent choose. Base OpenAI: 5 trials backgrounded the waiter; 0/5 woken, 36 polls. Fix: 3/3 woken, 0 polls; the other 3 trials blocked in turn with `awaitResults`. Claude base blocked in turn in 6/6. Claude fix: 3/3 backgrounded waiters woken, 0 polls.

**(b) S2, existing scenario** (printing status check, `automations` denied). No regression:

| Arm | Final delivered | `process poll` calls | `NO_REPLY` wake turns | Tokens / trial |
|---|---|---|---|---|
| base, OpenAI | 5/6 | 0 | 2 | 206k |
| fix, OpenAI | 6/6 | 0 | 0 | 174k |
| base, Claude | 6/6 | 8 | 0 | 310k |
| fix, Claude | 6/6 | **0** | 0 | 203k |

The undelivered base trial wrote a loop that matched `*"all checks pass"*`. That pattern never matched `all 15 checks passed`, so the loop ran past the trial window (an agent parsing bug). A separate Claude run on the parent of the previous waiter fix (`39efe6fb`) made 69 polls in 6 trials. On `main` it made 8 polls.

**(c) S1, automations allowed** (same prompt): which mechanism does the agent choose for the wait?

| Arm | Trials with one-shot automation | Trials with background exec | Turns | `NO_REPLY` turns | Tokens / trial |
|---|---|---|---|---|---|
| base, OpenAI | **6/6** | 0/6 | 30 | 18 | 708k |
| fix, OpenAI | **0/6** | 6/6 (all woken, 0 polls) | 12 | 0 | 161k |
| base, Claude | 0/6 | 5/6 (7 polls) | 11 | 0 | 279k |
| fix, Claude | 0/6 | 6/6 (all woken, 0 polls) | 12 | 0 | 199k |
| fix (this head), OpenAI | **0/6** | 6/6 (5 woken, 0 polls) | 11 | 0 | 161k |
| fix (this head), Claude | 0/6 | 6/6 (all woken, 0 polls) | 12 | 0 | 199k |

The first fix rows ran before review made the automations and skill wording conditional on an actual wake. The "this head" rows reran S1 on the final text. In one OpenAI trial, the agent's waiter matched `all checks passed` and never matched `all 15 checks passed`, so it ran past the window. That is the same agent parsing bug as in (b); the trial made 0 polls and scheduled no automation.

Base OpenAI scheduled an `at` job that re-ran `ci-status` every minute and answered `NO_REPLY` until CI passed. With the fix, the first wake already carried the passing line, so the agent answered without another tool call.

**(d) No-wait control.** "Run `lint` (about 20 s, prints nothing when clean), then tell me whether it passed":

| Arm | Final delivered | Spurious (`NO_REPLY`) wake turns | Turns |
|---|---|---|---|
| base, OpenAI | 6/6 | 0 | 6 |
| fix, OpenAI | 6/6 | 0 | 8 |
| base, Claude | 6/6 | 0 | 6 |
| fix, Claude | 6/6 | 0 | 6 |

The 2 extra OpenAI fix turns are not spurious. Those trials ended the turn with "lint is running". The silent exit woke them, and they reported "Lint passed (exit code 0, no output; 21 seconds)". On base, that turn shape would leave the user without an answer. Commands collected in turn (`awaitResults`, or a poll that observed the exit) produced no wake.

Redacted trace, Claude silent waiter, fix:

```text
+212s exec {"yieldMs": 1000} '<ws>/pr-1/ci-wait'
+214s   -> Command still running (session nova-valley:…, pid …), times out in 29m59s. Its exit wakes this conversation with the result, silent success included. If only waiting remains, end this turn now; do not poll it or start another command for the same result. …
+218s reply: I've started `ci-wait` for PR openclaw#4241 in the background. When it exits, I'll run `ci-status` …
+457s USER: Exec completed (nova-val, code 0, 4m2s) with no output.
+462s exec {} '<ws>/pr-1/ci-status'
+463s   -> PR openclaw#4241: all 15 checks passed. Summary: build-1-… green
+470s reply: PR openclaw#4241 is ready. …
```

Same scenario, base: `exec background` returns "Its exit wakes this conversation if it prints output or fails, not after a silent success…", then eight `process poll timeout=30000` calls each return `(no new output) Process still running.` until `Process exited with code 0.`.

**Tests** (`vitest-source`):

- `bash-tools.test.ts`: a non-chat session wakes on empty success by default; an explicit `false` stays quiet.
- `bash-tools.exec-background-followup.test.ts`: the running result carries the single contract and `times out in`; a dashboard conversation is woken on silent success with exit, duration and a bounded 2,000-char tail.
- `memory-host-sdk` `session-files.test.ts`: historical and current exec notices (silent, tail, retention-truncated) stay out of the memory export.
- The first two files are red on `main` (7 failures) and green here. The exec/process, durable notify, descriptions, automations schema, config help, prefix-stability and system-prompt suites pass. The UTF-16 boundary test now covers the retained-tail boundary.

**Upgrade:** the stored config and state shapes do not change. A saved `true` or `false` keeps its meaning (`bash-tools.test.ts` covers the explicit `false`). An omitted setting adopts the new default when the command starts. Durable records keep the policy they captured at start.

**Full tier** on this head: full build with declarations, then a packed tarball install. Tarball integrity, `openclaw --version` (`2026.11.3 (f3d42f9)`, the pre-rebase head with the same code) and `gateway --help` pass, and the packed `bash-tools.exec-output` chunk carries the new guidance.

**Limits:**

- The E2E ran on the direct tool surface. Code Mode was not measured.
- The test host was heavily loaded during the runs, and some first sends needed a longer client timeout. One Claude fix trial in (a)-soft never started (n=5).
- Spurious-turn counting is structural: wake turns whose reply is exactly `NO_REPLY`.

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]>
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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.

1 participant