Skip to content

fix(exec): agent gets one wake turn per command when background commands exit together - #199113

Merged
obviyus merged 10 commits into
mainfrom
waiter-batch-exec-completions
Nov 14, 2026
Merged

obviyus merged 10 commits into
mainfrom
waiter-batch-exec-completions

Conversation

@obviyus

@obviyus obviyus commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

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 fix(agents): wake on every background exit and carry the result #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 (fix(exec): plugin tools can tell which run started a background exec completion wake #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 fix(agents): wake on every background exit and carry the result #199122 (wake format) and fix(gateway): durable execs are reported as stopped after a Gateway restart #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.

Redacted trace, trial 1 (times relative to release of the first waiter)

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

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.

@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 clawsweeper:intake:bug 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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

Batch background-command completions waiting behind an active completion turn while preserving each result and its originating request.

Example: Three commands from one agent run exit one second apart while the first completion turn runs.

  • Before: The agent receives three separate completion turns.
  • After: The first result starts immediately; the other two share the next turn.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Real-agent before/after evidence, distinct boundary regressions, and successful exact-head CI support a correct, useful change.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied real-agent Gateway output exercises concurrent exec exits through ordinary completion admission and shows compatible later results sharing a turn; single-exit controls preserve immediate admission, and the final commit changes only a test type.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Several nearby background-command exits produce separate model turns and potentially repetitive replies.
Reason: The maintainer-authored direction has measured user value, preserves immediate lone completions, and explicitly accepts the bounded wait and human-message ordering tradeoffs.

Merge readiness

✅ Ready for maintainer review

This PR is useful and ready for landing consideration: compatible completion results share a turn, the earlier launch-run finding is fixed, and no actionable defect remains.

Priority: P2
Reviewed head: d14e5862c698ef29414ad652f6b7bdcb68234095

Before merge

None.

Findings

None.

Agent review details

How this fits together

Background exec exits enter the session-event owner with captured destinations and request ownership; ordinary conversation execution consumes their results and delivers any resulting reply.

flowchart TD
  A[Background command exits] --> B[Exec notification producer]
  B --> C[Completion batching]
  C --> D[Exact queued occurrences]
  D --> E[Ordinary session admission]
  E --> F[Agent continuation and reply]
Loading

Technical review

Best possible solution:

Land the bounded batching through the existing session-event admission owner with request, destination, and launching-run identity preserved.

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

Current-main source enqueues each exit separately, and the supplied real-agent baseline demonstrates three turns for three nearby exits; this read-only review executed no target code.

Is this the best way to solve the issue?

The change uses existing occurrence custody, target combination, and ordinary admission, adding only the waiting membership and settlement timing needed to combine compatible completions.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Exec completion admission keeps the original intent (753a7a5: Move background completions into ordinary conversation execution with captured destinations, permissions, FIFO ordering, and cancellation.)
  • Launching-run provenance keeps the original intent (f6ee991: Let plugins correlate a completion with its launching run without granting new authority.)
  • Completion silence guidance keeps the original intent (4fbcba2: Permit silent exec continuations without an empty-response error while retaining required subagent results.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit dbc41ff adds src/agents/bash-tools.exec-notify.ts:300 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dbc41ff76ba1; files: src/agents/bash-tools.exec-notify.ts)
  • Ayaan Zaidi: Raw commit 00636f0 adds src/agents/bash-tools.exec-notify.ts:139 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 00636f0c7abc; files: src/agents/bash-tools.exec-notify.ts)

PR surface

Source +221, Tests +78, Docs +1. Total +300 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 227 6 +221
Tests 2 79 1 +78
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 307 7 +300

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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Repeated completion turns add model cost and unnecessary replies in concurrent background-command workflows without preventing command execution.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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:42:11.515Z sha 1f75e28 :: needs changes before merge. :: [P2] Require the same launch run when combining completion results
  • reviewed 2026-11-14T20:35:57.996Z sha bde2274 :: needs maintainer review before merge. :: none

Reviewed November 14, 2026, 4:42 PM ET / 21:42 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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 and others added 8 commits November 15, 2026 02:28
…ared turn

Each background exec exit started its own ordinary turn, so three commands
that exit while the first completion turn runs cost three turns. A completion
now waits while an earlier completion turn of the same conversation is queued
or running; every compatible completion still waiting when it settles shares
the next turn through the existing multi-occurrence session event. A single
completion starts at once, as before.

Co-authored-by: obviyus <[email protected]>
…letion turn

Exit notification follows process settlement, so a slow runner could release
the first turn before the third exit was queued.

Co-authored-by: obviyus <[email protected]>
The first completion's own occurrence can still be queued when its turn
starts, so wait for the two exits that are not in the first prompt.

Co-authored-by: obviyus <[email protected]>
A completion turn can change the session's captured destination facts. On a
slow runner the first exit's turn started before the third command captured
its destination, so the two later exits correctly did not share a turn. Hold
all three commands until each has captured its destination.

Co-authored-by: obviyus <[email protected]>
The shared turn's input provenance names one launching run, so completions of
commands started by different runs keep separate turns even when they share
request owners.

Co-authored-by: obviyus <[email protected]>
Exits about a second apart often straddle the end of the turn they waited
behind: in 2 of 6 real-agent trials the last exit arrived just after the
batch started and got its own turn. Waiting completions now start one second
after that turn settles. A first or lone completion still starts at once.

Co-authored-by: obviyus <[email protected]>
…t-neutral

Each result now carries up to a 2,000-char tail, so one shared turn takes at
most about 8,000 characters of results; later results start the next turn.
The completion guidance no longer says "this completion" when a turn carries
several results.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the waiter-batch-exec-completions branch from bde2274 to 92847fc Compare November 14, 2026 21:11
@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 merged commit 597e400 into main Nov 14, 2026
129 checks passed
@obviyus
obviyus deleted the waiter-batch-exec-completions branch November 14, 2026 21:44
@obviyus

obviyus commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 597e400. Background commands that finish while a completion turn is queued or running now share one follow-up turn (each result keeps its id, exit code, duration and tail; at most ~8,000 chars per turn). Real-agent E2E: 3 near-simultaneous exits 3 -> 2 wake turns, wake-turn tokens -35%; a single exit is unchanged.

obviyus added a commit that referenced this pull request Nov 15, 2026
…one-shot runs (#199283)

## What Problem This Solves

Fixes: one-shot runs cannot wait for a background command without polling. A hidden subagent or an isolated cron agent turn ends with its final reply, so "end the turn and let the exit wake you" does not work there:

- A hidden subagent gets the exit only as a passive system event in its next turn, which never comes. Its running result therefore says "Automatic completion wake is unavailable … use poll with a timeout", and the agent calls `process poll` every 10–30 s for the whole wait.
- An isolated cron run gets the same manual-collection guidance. When the run ends first, a queued exit still arrives later as an extra follow-up turn, which answers `NO_REPLY`.
- `sessions_yield` only awaited child sessions. With a running command and no child, it said "No pending child completion … did not pause the turn". In a hidden subagent it refused outright ("Use process to poll and collect it before yielding").

## User Impact

User impact: a subagent or automation that waits for CI, a deploy or any long command starts one background command and calls `sessions_yield`. The command's exit resumes the same run with the exit result, and the run reports normally. No poll loop, fewer model round trips and tokens, and no spurious `NO_REPLY` turns after a cron run. Ordinary chat sessions are unchanged: their exit still wakes the conversation when the turn ends.

## Why This Change Was Made

**Owners extended (no new tool, parameter, state or stored row):**

- **Exec wake target capture** (`prepareExecExitNotification`): hidden subagent and cron-run commands now capture their own session as the wake target and record `exitWakeAfterYield`, but only when `sessions_yield` is callable in that run. The exec tool reads this from the run's final callable tool set, the same way it reads `process` availability. Collectors (which never get `sessions_yield`) and tool policies that remove it keep the previous manual-collection guidance. `hasExitWake` stays the single fact that the running result, idle `process poll` text and the Control UI waiting card read. For a one-shot run it also requires a deadline, so a wait is always bounded by the command's `timeoutSeconds`. A timeout already ends the command, and that exit resumes the run. `timeoutSeconds: 0` keeps manual-collection guidance.
- **Running result text** (`describeExitWake`): one-shot runs read "This run resumes with its result when it exits, silent success included, if you call sessions_yield. If only waiting remains, call sessions_yield now; do not poll it or start another command for the same result." Ordinary sessions keep the step 2 text.
- **Yield claim** (`createRequesterYieldCallback`): a wake-armed running command that the current run started (`originRunId`) is a completion claim, like a pending child. An accepted yield marks those commands (`resumesYieldedRun`). The step 2 refusal of a hidden-subagent yield with uncollected background work stays for commands whose exit cannot resume the run.
- **Hidden subagent resume** (`maybeNotifyOnExit` + `prepareReplySubagentContinuation`): the exit of an awaited command is sent as the ordinary exec wake turn (same content as step 2: exit code, duration, 2,000-char tail) instead of a passive event. It carries the starting run as `sourceRunId`. Reply admission treats an `exec` wake exactly like a tool handoff result: it continues the paused task only when that run is the yielded one, so the subagent's final reply still goes to its requester through the registry. A hidden subagent that did not yield still gets only the passive notice.
- **Cron run resume** (`executeCronRun`): the cron executor opens a per-run resume slot. A yield on the run's own commands returns `{ resumesInPlace: true }`; the embedded runner ends the turn but keeps the reply operation open, and the executor runs the next turn in the same operation with the exit text as the prompt. The resumed turn's reply is the run's result. A cron yield for children keeps the existing scheduler-owned behavior. A requested Stop or kill releases the wait without a turn.
- **Text and docs**: `sessions_yield` and exec descriptions, the cron unattended preamble (the "will not resume after `sessions_yield`" sentence now applies only to child yields), `docs/tools/exec.md`, `docs/gateway/background-process.md`, `docs/tools/subagents/tool-reference.md`, `docs/concepts/subagent-yield-handoff.md`. Prompt snapshots regenerated.

**Accepted edge cases** (named, no code): a command that exits in the instant between an accepted subagent yield and the pause being published runs as a separate follow-up turn instead of continuing the paused task (same window as the existing tool-handoff resume). The Control UI waiting card in a hidden subagent session now shows for wake-armed commands, because the exit can resume the run. An interactive session that calls `sessions_yield` on a wake-armed command gets `yielded`, which ends the turn exactly as ending it normally would.

Production delta: +199/−49 lines in `src` (excluding tests).

## Evidence

**Real agent, isolated source Gateway** (`ocx src`, pinned Bun fork, own state/port/HOME, `env -i`). Claude Opus through the shared Claude proxy, OpenClaw runtime, direct tool surface, `automations` denied. A fake CI flips to passed 240 s after the first status check. Fresh session per trial, 6 trials per arm, measured from the Gateway's own transcript store. base = `10159aefda9c` (`main` at branch time), fix = `bfd56dc84d66` (first head). The second head (`d51e737ba7da`, manual collection kept where `sessions_yield` is not callable) reran 3 hidden-subagent and 3 cron trials: 6/6 delivered, **0** polls, 5/5 background waiters resumed by their exit (1 cron trial waited in turn).

| Scenario | Arm | Final result delivered | `process poll` calls | Exit resumed the run | Spurious `NO_REPLY` turns | Tokens / trial |
|---|---|---|---|---|---|---|
| (a) parent spawns a hidden subagent that waits for CI, parent reports | base | 6/6 | **76** (all in the subagent) | 0/6 | 0 | 594k |
| | fix | 6/6 | **0** | 5/5 waiters (1 trial waited in turn) | 0 | 314k |
| (b) isolated cron agent turn waits for CI | base | 6/6 | **61** (12 idle) | 0/6 (2 exits arrived after the run) | **3** | 477k |
| | fix | 6/6 | **0** | 5/5 waiters (1 trial waited in turn) | 0 | 156k |
| (c) ordinary dashboard session, S2 (`ci-status`) | base | 6/6 | 12 | 6/6 | 0 | 296k |
| | fix | 6/6 | **0** | 6/6 | 0 | 198k |

(a) parent: in every fix trial the parent yielded for the child and received the child's final summary through the existing subagent completion; in 5/6 the child's reply came from the exec-resumed turn. (b) base: the run polled until CI passed, answered, and the queued exit then started an extra follow-up turn in 3 trials. (c): the ordinary session's running-result text is unchanged. Claude calls `sessions_yield` after starting the waiter in 4/6 trials on base and 4/6 on this head. On base that returns `nothing_pending` and the agent then polls in 3 of those trials (12 polls); here the yield is accepted, the turn ends and the exit wakes the conversation. Two fix trials ran in a supplemental 2-trial arm, because a concurrent packaging step briefly rewrote `package.json` and broke two trial sends in the first arm.

Redacted trace, hidden subagent, fix (P = parent, S = subagent):

```text
P +13s sessions_spawn → accepted
P +17s sessions_yield → {"status":"yielded"}
S +22s exec {"yieldMs":120000,"timeoutSeconds":1500} 'cd pr-1 && …loop until ci-status passes…'
S +142s  -> Command still running (session delta-sage:…, pid …), times out in 23m. This run resumes with its result when it exits, silent success included, if you call sessions_yield. If only waiting remains, call sessions_yield now; do not poll it …
S +145s sessions_yield → {"status":"yielded"}
S +263s USER: Exec completed (delta-sa, code 0, 4m1s): … PR #4241: all 15 checks passed. Summary: build-1-… green
S +266s write pr-1/RESULT.md
S +269s reply: All 15 CI checks on PR #4241 have passed. … PR #4241: all 15 checks passed. Summary: build-1-… green
P +270s USER: [Subagent Context] Every subagent in this batch has now settled …
P +279s reply: The subagent says CI on PR #4241 passed. Its summary line is: PR #4241: all 15 checks passed …
```

Same scenario, base: the subagent's running result says "Automatic completion wake is unavailable after ending this turn … use poll with a timeout", then 14 `process poll timeout=30000` calls each return `PR #4241: 4 checks pending, 11 passed … Process still running.` until it exits.

Cron, fix: `exec` → running result with the `sessions_yield` text → `sessions_yield` → `{"status":"yielded"}` → `Exec completed (tender-c, code 0, 4m1s): …` as the next turn of the same run → `ci-status > RESULT.md` → final reply `PR #4241: all 15 checks passed …`, recorded as the run summary.

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

- `bash-tools.exec-background-followup.test.ts`: a hidden subagent's command resumes it only after `sessions_yield` awaits it (passive notice otherwise; wake turn with `source: "exec"`, `sourceRunId` and the step 2 content when yielded); a yielded cron run resumes in place with the exit text and sends no session event; cron running results carry the `sessions_yield` text.
- `bash-tools.exec-background-followup.test.ts` also keeps the `main` behavior where `sessions_yield` is not callable: a hidden subagent gets manual-collection guidance and no wake promise, and a cron run is told to collect before ending the turn.
- `openclaw-tools.requester-yield.test.ts`: a wake-armed command the run started is a yield claim only when it has a deadline; only an accepted yield arms the resume.
- The two new tests fail on `main`, where the resume path does not exist; the updated cron assertions also fail there. The exec/process, descriptions, `sessions_yield` tool, requester yield, embedded runner yield orchestration, cron run lifecycle, model-switch retry and prompt-snapshot suites pass. `tsgo:core` passes.

**Full tier**: `ocx build --dts` on the rebased head (`cace873cdf6c`), then a packed tarball install: tarball integrity, `openclaw --version` (`2026.11.3 (cace873)`) and `gateway --help` pass; the packed `bash-tools.exec-output` chunk carries the new guidance.

**Limits:**

- Claude only, direct tool surface; OpenAI and Code Mode were not measured for this step.
- In one trial per fix arm (a) and (b), the agent waited in turn with a capped `yieldMs` block instead of backgrounding; it made no polls.
- The cron harness has no chat channel, so every run (base and fix) records `completionStatus: failed` for delivery; the run summary is the agent's final reply in both arms.
- Gateway restart mid-wait is out of scope (step 5).

**CI:** rebased onto `main` `92016ce978f0` (picks up #199113, which only changed the exec-completion enqueue import; no conflict in the yield/wake path). Focused yield, exec, cron and embedded-runner suites and `tsgo:core` pass on the rebased head. If `checks-ui-e2e (1/2)` fails in `ui/src/e2e/chat-cli-history-redaction.e2e.test.ts` ("preserves tool source in Activity while bounding the visible preview", waiting for `.activity-empty`), that failure is on `main`: #199168 removed the Activity element, but this test still waits for it. Locally, `pnpm test:ui:e2e ui/src/e2e/chat-cli-history-redaction.e2e.test.ts` fails the same way on `main` `92016ce978f0` and on this head (1 failed, 1 passed in both). This PR touches no `ui/` file. Other PRs pass that shard because their changed files select only 6 UI test files that do not include this one; this PR's change set selects 19.

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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…one-shot runs (openclaw#199283)

## What Problem This Solves

Fixes: one-shot runs cannot wait for a background command without polling. A hidden subagent or an isolated cron agent turn ends with its final reply, so "end the turn and let the exit wake you" does not work there:

- A hidden subagent gets the exit only as a passive system event in its next turn, which never comes. Its running result therefore says "Automatic completion wake is unavailable … use poll with a timeout", and the agent calls `process poll` every 10–30 s for the whole wait.
- An isolated cron run gets the same manual-collection guidance. When the run ends first, a queued exit still arrives later as an extra follow-up turn, which answers `NO_REPLY`.
- `sessions_yield` only awaited child sessions. With a running command and no child, it said "No pending child completion … did not pause the turn". In a hidden subagent it refused outright ("Use process to poll and collect it before yielding").

## User Impact

User impact: a subagent or automation that waits for CI, a deploy or any long command starts one background command and calls `sessions_yield`. The command's exit resumes the same run with the exit result, and the run reports normally. No poll loop, fewer model round trips and tokens, and no spurious `NO_REPLY` turns after a cron run. Ordinary chat sessions are unchanged: their exit still wakes the conversation when the turn ends.

## Why This Change Was Made

**Owners extended (no new tool, parameter, state or stored row):**

- **Exec wake target capture** (`prepareExecExitNotification`): hidden subagent and cron-run commands now capture their own session as the wake target and record `exitWakeAfterYield`, but only when `sessions_yield` is callable in that run. The exec tool reads this from the run's final callable tool set, the same way it reads `process` availability. Collectors (which never get `sessions_yield`) and tool policies that remove it keep the previous manual-collection guidance. `hasExitWake` stays the single fact that the running result, idle `process poll` text and the Control UI waiting card read. For a one-shot run it also requires a deadline, so a wait is always bounded by the command's `timeoutSeconds`. A timeout already ends the command, and that exit resumes the run. `timeoutSeconds: 0` keeps manual-collection guidance.
- **Running result text** (`describeExitWake`): one-shot runs read "This run resumes with its result when it exits, silent success included, if you call sessions_yield. If only waiting remains, call sessions_yield now; do not poll it or start another command for the same result." Ordinary sessions keep the step 2 text.
- **Yield claim** (`createRequesterYieldCallback`): a wake-armed running command that the current run started (`originRunId`) is a completion claim, like a pending child. An accepted yield marks those commands (`resumesYieldedRun`). The step 2 refusal of a hidden-subagent yield with uncollected background work stays for commands whose exit cannot resume the run.
- **Hidden subagent resume** (`maybeNotifyOnExit` + `prepareReplySubagentContinuation`): the exit of an awaited command is sent as the ordinary exec wake turn (same content as step 2: exit code, duration, 2,000-char tail) instead of a passive event. It carries the starting run as `sourceRunId`. Reply admission treats an `exec` wake exactly like a tool handoff result: it continues the paused task only when that run is the yielded one, so the subagent's final reply still goes to its requester through the registry. A hidden subagent that did not yield still gets only the passive notice.
- **Cron run resume** (`executeCronRun`): the cron executor opens a per-run resume slot. A yield on the run's own commands returns `{ resumesInPlace: true }`; the embedded runner ends the turn but keeps the reply operation open, and the executor runs the next turn in the same operation with the exit text as the prompt. The resumed turn's reply is the run's result. A cron yield for children keeps the existing scheduler-owned behavior. A requested Stop or kill releases the wait without a turn.
- **Text and docs**: `sessions_yield` and exec descriptions, the cron unattended preamble (the "will not resume after `sessions_yield`" sentence now applies only to child yields), `docs/tools/exec.md`, `docs/gateway/background-process.md`, `docs/tools/subagents/tool-reference.md`, `docs/concepts/subagent-yield-handoff.md`. Prompt snapshots regenerated.

**Accepted edge cases** (named, no code): a command that exits in the instant between an accepted subagent yield and the pause being published runs as a separate follow-up turn instead of continuing the paused task (same window as the existing tool-handoff resume). The Control UI waiting card in a hidden subagent session now shows for wake-armed commands, because the exit can resume the run. An interactive session that calls `sessions_yield` on a wake-armed command gets `yielded`, which ends the turn exactly as ending it normally would.

Production delta: +199/−49 lines in `src` (excluding tests).

## Evidence

**Real agent, isolated source Gateway** (`ocx src`, pinned Bun fork, own state/port/HOME, `env -i`). Claude Opus through the shared Claude proxy, OpenClaw runtime, direct tool surface, `automations` denied. A fake CI flips to passed 240 s after the first status check. Fresh session per trial, 6 trials per arm, measured from the Gateway's own transcript store. base = `8ae26d8ad99d` (`main` at branch time), fix = `bfd56dc84d66` (first head). The second head (`d51e737ba7da`, manual collection kept where `sessions_yield` is not callable) reran 3 hidden-subagent and 3 cron trials: 6/6 delivered, **0** polls, 5/5 background waiters resumed by their exit (1 cron trial waited in turn).

| Scenario | Arm | Final result delivered | `process poll` calls | Exit resumed the run | Spurious `NO_REPLY` turns | Tokens / trial |
|---|---|---|---|---|---|---|
| (a) parent spawns a hidden subagent that waits for CI, parent reports | base | 6/6 | **76** (all in the subagent) | 0/6 | 0 | 594k |
| | fix | 6/6 | **0** | 5/5 waiters (1 trial waited in turn) | 0 | 314k |
| (b) isolated cron agent turn waits for CI | base | 6/6 | **61** (12 idle) | 0/6 (2 exits arrived after the run) | **3** | 477k |
| | fix | 6/6 | **0** | 5/5 waiters (1 trial waited in turn) | 0 | 156k |
| (c) ordinary dashboard session, S2 (`ci-status`) | base | 6/6 | 12 | 6/6 | 0 | 296k |
| | fix | 6/6 | **0** | 6/6 | 0 | 198k |

(a) parent: in every fix trial the parent yielded for the child and received the child's final summary through the existing subagent completion; in 5/6 the child's reply came from the exec-resumed turn. (b) base: the run polled until CI passed, answered, and the queued exit then started an extra follow-up turn in 3 trials. (c): the ordinary session's running-result text is unchanged. Claude calls `sessions_yield` after starting the waiter in 4/6 trials on base and 4/6 on this head. On base that returns `nothing_pending` and the agent then polls in 3 of those trials (12 polls); here the yield is accepted, the turn ends and the exit wakes the conversation. Two fix trials ran in a supplemental 2-trial arm, because a concurrent packaging step briefly rewrote `package.json` and broke two trial sends in the first arm.

Redacted trace, hidden subagent, fix (P = parent, S = subagent):

```text
P +13s sessions_spawn → accepted
P +17s sessions_yield → {"status":"yielded"}
S +22s exec {"yieldMs":120000,"timeoutSeconds":1500} 'cd pr-1 && …loop until ci-status passes…'
S +142s  -> Command still running (session delta-sage:…, pid …), times out in 23m. This run resumes with its result when it exits, silent success included, if you call sessions_yield. If only waiting remains, call sessions_yield now; do not poll it …
S +145s sessions_yield → {"status":"yielded"}
S +263s USER: Exec completed (delta-sa, code 0, 4m1s): … PR openclaw#4241: all 15 checks passed. Summary: build-1-… green
S +266s write pr-1/RESULT.md
S +269s reply: All 15 CI checks on PR openclaw#4241 have passed. … PR openclaw#4241: all 15 checks passed. Summary: build-1-… green
P +270s USER: [Subagent Context] Every subagent in this batch has now settled …
P +279s reply: The subagent says CI on PR openclaw#4241 passed. Its summary line is: PR openclaw#4241: all 15 checks passed …
```

Same scenario, base: the subagent's running result says "Automatic completion wake is unavailable after ending this turn … use poll with a timeout", then 14 `process poll timeout=30000` calls each return `PR openclaw#4241: 4 checks pending, 11 passed … Process still running.` until it exits.

Cron, fix: `exec` → running result with the `sessions_yield` text → `sessions_yield` → `{"status":"yielded"}` → `Exec completed (tender-c, code 0, 4m1s): …` as the next turn of the same run → `ci-status > RESULT.md` → final reply `PR openclaw#4241: all 15 checks passed …`, recorded as the run summary.

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

- `bash-tools.exec-background-followup.test.ts`: a hidden subagent's command resumes it only after `sessions_yield` awaits it (passive notice otherwise; wake turn with `source: "exec"`, `sourceRunId` and the step 2 content when yielded); a yielded cron run resumes in place with the exit text and sends no session event; cron running results carry the `sessions_yield` text.
- `bash-tools.exec-background-followup.test.ts` also keeps the `main` behavior where `sessions_yield` is not callable: a hidden subagent gets manual-collection guidance and no wake promise, and a cron run is told to collect before ending the turn.
- `openclaw-tools.requester-yield.test.ts`: a wake-armed command the run started is a yield claim only when it has a deadline; only an accepted yield arms the resume.
- The two new tests fail on `main`, where the resume path does not exist; the updated cron assertions also fail there. The exec/process, descriptions, `sessions_yield` tool, requester yield, embedded runner yield orchestration, cron run lifecycle, model-switch retry and prompt-snapshot suites pass. `tsgo:core` passes.

**Full tier**: `ocx build --dts` on the rebased head (`cace873cdf6c`), then a packed tarball install: tarball integrity, `openclaw --version` (`2026.11.3 (cace873)`) and `gateway --help` pass; the packed `bash-tools.exec-output` chunk carries the new guidance.

**Limits:**

- Claude only, direct tool surface; OpenAI and Code Mode were not measured for this step.
- In one trial per fix arm (a) and (b), the agent waited in turn with a capped `yieldMs` block instead of backgrounding; it made no polls.
- The cron harness has no chat channel, so every run (base and fix) records `completionStatus: failed` for delivery; the run summary is the agent's final reply in both arms.
- Gateway restart mid-wait is out of scope (step 5).

**CI:** rebased onto `main` `d0193c2d8434` (picks up openclaw#199113, which only changed the exec-completion enqueue import; no conflict in the yield/wake path). Focused yield, exec, cron and embedded-runner suites and `tsgo:core` pass on the rebased head. If `checks-ui-e2e (1/2)` fails in `ui/src/e2e/chat-cli-history-redaction.e2e.test.ts` ("preserves tool source in Activity while bounding the visible preview", waiting for `.activity-empty`), that failure is on `main`: openclaw#199168 removed the Activity element, but this test still waits for it. Locally, `pnpm test:ui:e2e ui/src/e2e/chat-cli-history-redaction.e2e.test.ts` fails the same way on `main` `d0193c2d8434` and on this head (1 failed, 1 passed in both). This PR touches no `ui/` file. Other PRs pass that shard because their changed files select only 6 UI test files that do not include this one; this PR's change set selects 19.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 15, 2026
Exec completions for a cron run must be admitted while the run is live.
Holding a second completion in the batching lane until the first settles
lets the run end first, and the ended-run refusal then drops it.
Restore the cron bypass (#199113) on the key, not on the removed
producer-side acceptance check.

Co-authored-by: obviyus <[email protected]>
obviyus added a commit that referenced this pull request Nov 15, 2026
…9585)

## What Problem This Solves

Fixes: a cron run can be handed late background work, such as a command exit or a completion, after it has ended. Each producer decided by itself whether a cron run could receive a later turn. When two producers disagreed (media expected a later turn; the runner waited for the media), production hit a deadlock and a retry storm of about 16.5k attempts.

## User Impact

A cron run receives background results only while its executor still owns it: as an inline tool result, or through `sessions_yield`, which the cron executor resumes in place. After the run ends, the Gateway refuses any new turn on its run session one time, with `cron run has ended; inspect the result in its run record`. Results stay in their durable records (process log, subagent registry, task record). Background commands that are still running when the run ends are not awaited. The run history now names them in its diagnostics, so the run does not look complete while its commands continue. Subagent behavior does not change.

## Why This Change Was Made

One rule now has one owner. `isEndedCronRun` (cron run key, and no run of that session has a live execution owner) is the same check exec-notify did before. Both turn admission owners call it:

- Gateway agent-turn preparation (`agent-session-prepare.ts`), next to the other session start refusals.
- The session-event handoff (`enqueueSessionEventForHost`), as the acceptance check. Exec exit wakes reach a session through this path, not through `agent` RPC. The check runs at enqueue and again until the occurrence is accepted.

`isOneShotRunSessionKey` (cron run key or subagent key) replaces the duplicated `subagent || cron run` checks.

| Producer | Before | After |
|---|---|---|
| Background exec exit (`bash-tools.exec-notify.ts`) | Own `assertExitNotificationAcceptanceCurrent` cron check; own `hiddenSubagent \|\| isCronRunSessionKey` one-shot check | No cron check. One-shot uses `isOneShotRunSessionKey`. The session-event admission refuses an ended run, and the warning still says `inspect the result with process log` |
| Exec exit-wake guidance (`bash-tools.exec-output.ts`) | Read the producer's cron assertion | One-shot runs promise a wake only through `sessions_yield` (`isOneShotRunSessionKey`) |
| Exec default timeout (`exec-tool-timeout.ts`) | `isSubagentSessionKey \|\| isCronRunSessionKey` | `isOneShotRunSessionKey` |
| Exec batching (`session-event-batch.ts`) | Bypassed batching when the exec cron assertion was present | No cron special case. A batched turn is admitted through the same gate |
| `agent` RPC turns on a cron run key (for example subagent completion, manual) | No ended-run refusal | Refused with the typed `INVALID_REQUEST` above |
| Media (`media-generate-background-shared.ts`) | Inline in cron runs (#199529) | Unchanged |
| `sessions_send` | Cron-specific branches | Unchanged. No site means only "requester cannot receive a later turn": the follow-up path lets yielded subagent requesters receive registry turns, and the executor keeps the `:trigger` case plus a wait-failure notice that applies to cron only |

The cron executor comments on the intended asymmetry: subagents are awaited because their output is the run's output; background commands are not, because they can be services. Jobs with `deleteAfterRun` still delete the run session, and that stops its commands (existing behavior). The `cronRunContinuation` marker is not changed (separate follow-up).

## Evidence

- New QA-lab Gateway e2e `test/e2e/qa-lab/runtime/cron-one-shot-run.e2e.test.ts` (real Gateway, mock-openai). Each case checks that the run reaches status `ok`, that an `agent` turn on the ended run key is refused with the typed error, and that no model request occurs after the run ends:
  - (a) background `sleep 3; echo …`, then `sessions_yield`: the run resumes in place, and its summary contains the command output.
  - (b) background `sleep 30; echo …`, no yield: the run ends in less than 25 s. Its diagnostics name the running command. Its exit later logs `completion was not admitted (cron run has ended…); inspect the result with process log` exactly once and starts no turn.
  - (c) the cron run spawns a child and ends its turn: the run completes with the child's result (regression guard).
  - New-behavior assertions: the `agent` refusal (all cases), the diagnostics entry and the refusal text (b). The yield resume and the child result are existing behavior. I did not run this e2e on the base.
- `test/e2e/qa-lab/media/cron-image-generation.e2e.test.ts` passes.
- Unit test at the admission boundary (`agent-session-preparation.worker.test.ts`): a cron run key is admitted while a run context owns it, and refused with `INVALID_REQUEST` after the run context is released.
- Focused suites pass: exec background follow-up, exec notify, session-event handoff/readmission/permissions, gateway agent-turn, cron isolated-agent (62 files), qa-lab mock-openai.
- On this head (rebased on main after #199529 landed): `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, mock-export, max-lines, line-cap and assertion-safety ratchets, format, and oxlint all pass. The only oxlint finding is the existing max-lines on `session-event-handoff.ts`, which is grandfathered and has the same line count as main.
- I did not run the full `ocx build --dts` and packed-install smoke on this rebased head. Both passed on the identical pre-rebase change.

<details><summary>Follow-up finding: image_generate in a hidden subagent that never yields</summary>

From reading the code only; no test. `shouldDetachMediaGenerationTask` detaches for every non-cron key, so a subagent's image detaches. Its completion goes through `deliverSubagentAnnouncement` as an `agent` turn on the subagent key. Gateway admission does not refuse it: inter-session input that is not `subagent_settle` does not reactivate the child registry row (`agent-run-subagent.ts`). The result is not the refused-completion retry storm. It looks like a late orphan turn in the finished child session, whose output probably does not reach the parent. The fix is not a one-line predicate swap, so it is not in this PR.

</details>


**Review follow-up (b8b06bb):** live cron completions bypass the exec completion batching lane again, keyed on the cron run session key instead of the removed producer-side acceptance check (the reason #199113 excluded them). New regression `admits every completion that arrives while its cron run is live` in `bash-tools.exec-background-followup.test.ts`: two background commands finish while the run is live and both are admitted; it fails with the bypass removed and passes with it.


**Review follow-up 2:** the ended-run rule counts only the executor's own run (the run carrying the job invocation), so an accepted completion follow-up on the same session cannot make an ended origin look live (the case #172690 guarded with captured origin run ids). The admission boundary test now holds a follow-up owner while the executor releases and expects the refusal; it fails on the previous predicate and passes now. `check-lint-core-4` fails only in `lint extension package stripe`, which this PR does not touch.

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

## What Problem This Solves

Fixes: a cron run can be handed late background work, such as a command exit or a completion, after it has ended. Each producer decided by itself whether a cron run could receive a later turn. When two producers disagreed (media expected a later turn; the runner waited for the media), production hit a deadlock and a retry storm of about 16.5k attempts.

## User Impact

A cron run receives background results only while its executor still owns it: as an inline tool result, or through `sessions_yield`, which the cron executor resumes in place. After the run ends, the Gateway refuses any new turn on its run session one time, with `cron run has ended; inspect the result in its run record`. Results stay in their durable records (process log, subagent registry, task record). Background commands that are still running when the run ends are not awaited. The run history now names them in its diagnostics, so the run does not look complete while its commands continue. Subagent behavior does not change.

## Why This Change Was Made

One rule now has one owner. `isEndedCronRun` (cron run key, and no run of that session has a live execution owner) is the same check exec-notify did before. Both turn admission owners call it:

- Gateway agent-turn preparation (`agent-session-prepare.ts`), next to the other session start refusals.
- The session-event handoff (`enqueueSessionEventForHost`), as the acceptance check. Exec exit wakes reach a session through this path, not through `agent` RPC. The check runs at enqueue and again until the occurrence is accepted.

`isOneShotRunSessionKey` (cron run key or subagent key) replaces the duplicated `subagent || cron run` checks.

| Producer | Before | After |
|---|---|---|
| Background exec exit (`bash-tools.exec-notify.ts`) | Own `assertExitNotificationAcceptanceCurrent` cron check; own `hiddenSubagent \|\| isCronRunSessionKey` one-shot check | No cron check. One-shot uses `isOneShotRunSessionKey`. The session-event admission refuses an ended run, and the warning still says `inspect the result with process log` |
| Exec exit-wake guidance (`bash-tools.exec-output.ts`) | Read the producer's cron assertion | One-shot runs promise a wake only through `sessions_yield` (`isOneShotRunSessionKey`) |
| Exec default timeout (`exec-tool-timeout.ts`) | `isSubagentSessionKey \|\| isCronRunSessionKey` | `isOneShotRunSessionKey` |
| Exec batching (`session-event-batch.ts`) | Bypassed batching when the exec cron assertion was present | No cron special case. A batched turn is admitted through the same gate |
| `agent` RPC turns on a cron run key (for example subagent completion, manual) | No ended-run refusal | Refused with the typed `INVALID_REQUEST` above |
| Media (`media-generate-background-shared.ts`) | Inline in cron runs (openclaw#199529) | Unchanged |
| `sessions_send` | Cron-specific branches | Unchanged. No site means only "requester cannot receive a later turn": the follow-up path lets yielded subagent requesters receive registry turns, and the executor keeps the `:trigger` case plus a wait-failure notice that applies to cron only |

The cron executor comments on the intended asymmetry: subagents are awaited because their output is the run's output; background commands are not, because they can be services. Jobs with `deleteAfterRun` still delete the run session, and that stops its commands (existing behavior). The `cronRunContinuation` marker is not changed (separate follow-up).

## Evidence

- New QA-lab Gateway e2e `test/e2e/qa-lab/runtime/cron-one-shot-run.e2e.test.ts` (real Gateway, mock-openai). Each case checks that the run reaches status `ok`, that an `agent` turn on the ended run key is refused with the typed error, and that no model request occurs after the run ends:
  - (a) background `sleep 3; echo …`, then `sessions_yield`: the run resumes in place, and its summary contains the command output.
  - (b) background `sleep 30; echo …`, no yield: the run ends in less than 25 s. Its diagnostics name the running command. Its exit later logs `completion was not admitted (cron run has ended…); inspect the result with process log` exactly once and starts no turn.
  - (c) the cron run spawns a child and ends its turn: the run completes with the child's result (regression guard).
  - New-behavior assertions: the `agent` refusal (all cases), the diagnostics entry and the refusal text (b). The yield resume and the child result are existing behavior. I did not run this e2e on the base.
- `test/e2e/qa-lab/media/cron-image-generation.e2e.test.ts` passes.
- Unit test at the admission boundary (`agent-session-preparation.worker.test.ts`): a cron run key is admitted while a run context owns it, and refused with `INVALID_REQUEST` after the run context is released.
- Focused suites pass: exec background follow-up, exec notify, session-event handoff/readmission/permissions, gateway agent-turn, cron isolated-agent (62 files), qa-lab mock-openai.
- On this head (rebased on main after openclaw#199529 landed): `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, mock-export, max-lines, line-cap and assertion-safety ratchets, format, and oxlint all pass. The only oxlint finding is the existing max-lines on `session-event-handoff.ts`, which is grandfathered and has the same line count as main.
- I did not run the full `ocx build --dts` and packed-install smoke on this rebased head. Both passed on the identical pre-rebase change.

<details><summary>Follow-up finding: image_generate in a hidden subagent that never yields</summary>

From reading the code only; no test. `shouldDetachMediaGenerationTask` detaches for every non-cron key, so a subagent's image detaches. Its completion goes through `deliverSubagentAnnouncement` as an `agent` turn on the subagent key. Gateway admission does not refuse it: inter-session input that is not `subagent_settle` does not reactivate the child registry row (`agent-run-subagent.ts`). The result is not the refused-completion retry storm. It looks like a late orphan turn in the finished child session, whose output probably does not reach the parent. The fix is not a one-line predicate swap, so it is not in this PR.

</details>


**Review follow-up (b8b06bb):** live cron completions bypass the exec completion batching lane again, keyed on the cron run session key instead of the removed producer-side acceptance check (the reason openclaw#199113 excluded them). New regression `admits every completion that arrives while its cron run is live` in `bash-tools.exec-background-followup.test.ts`: two background commands finish while the run is live and both are admitted; it fails with the bypass removed and passes with it.


**Review follow-up 2:** the ended-run rule counts only the executor's own run (the run carrying the job invocation), so an accepted completion follow-up on the same session cannot make an ended origin look live (the case openclaw#172690 guarded with captured origin run ids). The admission boundary test now holds a follow-up owner while the executor releases and expects the refusal; it fails on the previous predicate and passes now. `check-lint-core-4` fails only in `lint extension package stripe`, which this PR does not touch.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 24, 2026
…e goal advances (#204265)

Closes #204187

## What Problem This Solves

With an active Goal, a background command that finishes during a turn can lose its place to the Goal's automatic "Advance the active goal" turn. The agent then advances the Goal before it has read the command result. A Gateway restart between a command's exit and its completion turn also loses the result, because the result exists only in memory.

## User Impact

User impact: a finished background command always reaches the agent before an active Goal advances, and a Gateway restart no longer loses a command result that was waiting for its turn.

- After a restart, the completion turn runs with the session principal's current authority. The original channel owner's owner-only tools do not carry across the restart; durable outcomes already behave this way.
- Completions that arrive while an earlier completion turn runs still share one turn (#199113).

## Why This Change Was Made

The exec result becomes stored state when the command exits (first slice of the owed-result model):

- New `src/sessions/owed.ts`. `owe(item)` is the only writer of new owed rows. It stores the result in the existing `session_pending_inputs` table, with `kind: "exec"` and `originFacts` (requester, command owner, operator profile id) as additive JSON in the row message. There is no schema change. `shouldWake(chat)` reads stored rows: it is true while the chat has owed rows that no live turn holds. Consumption does not read `originFacts` yet; a later slice intersects it with current policy without a migration.
- The exec wake turn adopts its owed row by id (the turn's input idempotency key) and writes its own bytes into it. Before a shared batch turn starts, `fold` writes the joined text into the first member's row and consumes the other members' rows in one transaction, so a restart at any point replays each result once. If the fold fails, the shared turn is refused and each member retries its own row. The transcript append consumes the row in the same transaction, so a second consumer or a retry after restart appends nothing.
- Goal continuation calls `shouldWake` and does not advance while an owed result is pending. The completion turn runs first, and its end continues the Goal.
- One wake path, `wakeOwedExec`, serves the live wake, its single retry and restart recovery. A wake that fails before it becomes a turn, or is refused at enqueue, retries once from the stored row; the live retry keeps the captured target, so admission revalidates the requester's authority. A stop, or a second failure, ends the row with a visible cause. Restart recovery wakes owed rows, which it used to refuse as queued human input.

| Part | Files | Lines |
|---|---|---|
| Deleted in-memory exec path | `bash-tools.exec-notify.ts`: the `pendingExitWakes` set and its reads, `enqueueExecExitNotification`, and the separate settle/log block (`hasExecYieldWake` and the yield sweep now read stored rows) | −46 |
| Shrunk to stay under the line cap | `session-accessor.pending-inputs.ts`: two duplicated "already consumed" receipts become `consumedPendingInputReceipt` (moved to `session-pending-input-value.ts`) | +26 −33 |
| Owed primitive | `sessions/owed.ts` (`owe`, `fold`, `shouldWake`, `readPendingOwed`, `withhold`: +200); `session-pending-input-value.ts` (`readOwedKind`, owed restage, moved receipt: +44); owed-row adoption in `session-accessor.pending-input-request.ts` (+18 −2); absorbed-row consumption in both pending-input kernels and the mutation type (+32) | +294 −2 |
| Glue | `bash-tools.exec-notify.ts` (`wakeOwedExec`, settlement, owed row with origin facts: +104); `session-event-batch.ts` (fold before a shared turn, one refusal path: +68 −15); `queued-chat-inputs.ts` restart wake (+22 −1); `goal-continuation.ts` (+11); `session-yield-sweep.ts` (+4 −1) | +209 −17 |
| **Production total** | 12 files | **+529 −98 (net +431)** |

No parallel in-memory exec-completion path is left. Every exec completion, live or after restart, is an owed row delivered by `wakeOwedExec`. What remains in memory is the shared session-event admission that runs the turn for every producer (cron, hooks, plugins). Its occurrence still carries a copy of the text; that copy can go when session-event admission reads stored rows for all producers, in later owed-result slices. The cron yield-resume path (`execYieldResumes`) is a different consumer and stays out of this slice.

## Evidence

- **Race, deterministic:** a new `server.chat-goal.test.ts` case holds the real exec wake in target preparation until the first turn's Goal check runs. It is red on the merge base (Advance overtakes the completion) and green on head.
- **No deadlock:** a new case makes the first wake fail in preparation; the stored row wakes the completion turn and the Goal then advances. The existing "keeps pursuing after … exec completion" cases end every completion turn before a model call; they stay green.
- **Shared turn:** a new case refuses a shared completion turn before admission; both results are still delivered afterwards. A storage case shows `fold` leaves exactly one row carrying both results; it is red when the absorbed rows are not consumed (both rows remain, so a restart would deliver the second result twice).
- **Storage:** a new pending-input case is red without the kind-preserving restage (restart recovery would refuse an adopted row) and green on head.
- **Touched suites:** exec background follow-up (28/28, shared-turn cases included), yield sweep (6/6), and the pending-input, queued-input, Goal continuation, session-event and restart-resume suites (19 files, 284 tests).
- **Real Gateway, scratch port and state, real model:** an exec result pending in `session_pending_inputs` across a Gateway restart is appended to the transcript exactly once after the restart (5 runs). On head `0abfb478`, which differs from the final head only in the batch's fold-failure path, the same run also shows `Exec completed` before `[System] Advance the active goal` (with #204327 merged).
- **Repeat runs (final head `4b887e10`, frozen copy):** `server.chat-goal.test.ts` as a whole file, 20 separate runs: 20/20 passed with 72/72 each (1,440 test executions). Both "keeps pursuing after … takes the next turn" variants passed in every run (40/40).

Separate bug, fixed and merged in #204327 (issue #204319): on a real Gateway, a Goal did not advance after a background command's completion turn. Post-turn session maintenance waited in the mailbox and the Goal check deferred to it. This happens on `main` too. A plain Goal advances normally on `main`; an earlier note here that it never advanced came from a bad test prompt. With #204327 the real-Gateway transcript reads: Goal request → `Exec completed …` → `[System] Advance the active goal …`.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 25, 2026
…e goal advances (#204265)

Closes #204187

## What Problem This Solves

With an active Goal, a background command that finishes during a turn can lose its place to the Goal's automatic "Advance the active goal" turn. The agent then advances the Goal before it has read the command result. A Gateway restart between a command's exit and its completion turn also loses the result, because the result exists only in memory.

## User Impact

User impact: a finished background command always reaches the agent before an active Goal advances, and a Gateway restart no longer loses a command result that was waiting for its turn.

- After a restart, the completion turn runs with the session principal's current authority. The original channel owner's owner-only tools do not carry across the restart; durable outcomes already behave this way.
- Completions that arrive while an earlier completion turn runs still share one turn (#199113).

## Why This Change Was Made

The exec result becomes stored state when the command exits (first slice of the owed-result model):

- New `src/sessions/owed.ts`. `owe(item)` is the only writer of new owed rows. It stores the result in the existing `session_pending_inputs` table, with `kind: "exec"` and `originFacts` (requester, command owner, operator profile id) as additive JSON in the row message. There is no schema change. `shouldWake(chat)` reads stored rows: it is true while the chat has owed rows that no live turn holds. Consumption does not read `originFacts` yet; a later slice intersects it with current policy without a migration.
- The exec wake turn adopts its owed row by id (the turn's input idempotency key) and writes its own bytes into it. Before a shared batch turn starts, `fold` writes the joined text into the first member's row and consumes the other members' rows in one transaction, so a restart at any point replays each result once. If the fold fails, the shared turn is refused and each member retries its own row. The transcript append consumes the row in the same transaction, so a second consumer or a retry after restart appends nothing.
- Goal continuation calls `shouldWake` and does not advance while an owed result is pending. The completion turn runs first, and its end continues the Goal.
- One wake path, `wakeOwedExec`, serves the live wake, its single retry and restart recovery. A wake that fails before it becomes a turn, or is refused at enqueue, retries once from the stored row; the live retry keeps the captured target, so admission revalidates the requester's authority. A stop, or a second failure, ends the row with a visible cause. Restart recovery wakes owed rows, which it used to refuse as queued human input.

| Part | Files | Lines |
|---|---|---|
| Deleted in-memory exec path | `bash-tools.exec-notify.ts`: the `pendingExitWakes` set and its reads, `enqueueExecExitNotification`, and the separate settle/log block (`hasExecYieldWake` and the yield sweep now read stored rows) | −46 |
| Shrunk to stay under the line cap | `session-accessor.pending-inputs.ts`: two duplicated "already consumed" receipts become `consumedPendingInputReceipt` (moved to `session-pending-input-value.ts`) | +26 −33 |
| Owed primitive | `sessions/owed.ts` (`owe`, `fold`, `shouldWake`, `readPendingOwed`, `withhold`: +200); `session-pending-input-value.ts` (`readOwedKind`, owed restage, moved receipt: +44); owed-row adoption in `session-accessor.pending-input-request.ts` (+18 −2); absorbed-row consumption in both pending-input kernels and the mutation type (+32) | +294 −2 |
| Glue | `bash-tools.exec-notify.ts` (`wakeOwedExec`, settlement, owed row with origin facts: +104); `session-event-batch.ts` (fold before a shared turn, one refusal path: +68 −15); `queued-chat-inputs.ts` restart wake (+22 −1); `goal-continuation.ts` (+11); `session-yield-sweep.ts` (+4 −1) | +209 −17 |
| **Production total** | 12 files | **+529 −98 (net +431)** |

No parallel in-memory exec-completion path is left. Every exec completion, live or after restart, is an owed row delivered by `wakeOwedExec`. What remains in memory is the shared session-event admission that runs the turn for every producer (cron, hooks, plugins). Its occurrence still carries a copy of the text; that copy can go when session-event admission reads stored rows for all producers, in later owed-result slices. The cron yield-resume path (`execYieldResumes`) is a different consumer and stays out of this slice.

## Evidence

- **Race, deterministic:** a new `server.chat-goal.test.ts` case holds the real exec wake in target preparation until the first turn's Goal check runs. It is red on the merge base (Advance overtakes the completion) and green on head.
- **No deadlock:** a new case makes the first wake fail in preparation; the stored row wakes the completion turn and the Goal then advances. The existing "keeps pursuing after … exec completion" cases end every completion turn before a model call; they stay green.
- **Shared turn:** a new case refuses a shared completion turn before admission; both results are still delivered afterwards. A storage case shows `fold` leaves exactly one row carrying both results; it is red when the absorbed rows are not consumed (both rows remain, so a restart would deliver the second result twice).
- **Storage:** a new pending-input case is red without the kind-preserving restage (restart recovery would refuse an adopted row) and green on head.
- **Touched suites:** exec background follow-up (28/28, shared-turn cases included), yield sweep (6/6), and the pending-input, queued-input, Goal continuation, session-event and restart-resume suites (19 files, 284 tests).
- **Real Gateway, scratch port and state, real model:** an exec result pending in `session_pending_inputs` across a Gateway restart is appended to the transcript exactly once after the restart (5 runs). On head `0abfb478`, which differs from the final head only in the batch's fold-failure path, the same run also shows `Exec completed` before `[System] Advance the active goal` (with #204327 merged).
- **Repeat runs (final head `4b887e10`, frozen copy):** `server.chat-goal.test.ts` as a whole file, 20 separate runs: 20/20 passed with 72/72 each (1,440 test executions). Both "keeps pursuing after … takes the next turn" variants passed in every run (40/40).

Separate bug, fixed and merged in #204327 (issue #204319): on a real Gateway, a Goal did not advance after a background command's completion turn. Post-turn session maintenance waited in the mailbox and the Goal check deferred to it. This happens on `main` too. A plain Goal advances normally on `main`; an earlier note here that it never advanced came from a bad test prompt. With #204327 the real-Gateway transcript reads: Goal request → `Exec completed …` → `[System] Advance the active goal …`.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 463d774)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 25, 2026
…e goal advances (openclaw#204265)

Closes openclaw#204187

## What Problem This Solves

With an active Goal, a background command that finishes during a turn can lose its place to the Goal's automatic "Advance the active goal" turn. The agent then advances the Goal before it has read the command result. A Gateway restart between a command's exit and its completion turn also loses the result, because the result exists only in memory.

## User Impact

User impact: a finished background command always reaches the agent before an active Goal advances, and a Gateway restart no longer loses a command result that was waiting for its turn.

- After a restart, the completion turn runs with the session principal's current authority. The original channel owner's owner-only tools do not carry across the restart; durable outcomes already behave this way.
- Completions that arrive while an earlier completion turn runs still share one turn (openclaw#199113).

## Why This Change Was Made

The exec result becomes stored state when the command exits (first slice of the owed-result model):

- New `src/sessions/owed.ts`. `owe(item)` is the only writer of new owed rows. It stores the result in the existing `session_pending_inputs` table, with `kind: "exec"` and `originFacts` (requester, command owner, operator profile id) as additive JSON in the row message. There is no schema change. `shouldWake(chat)` reads stored rows: it is true while the chat has owed rows that no live turn holds. Consumption does not read `originFacts` yet; a later slice intersects it with current policy without a migration.
- The exec wake turn adopts its owed row by id (the turn's input idempotency key) and writes its own bytes into it. Before a shared batch turn starts, `fold` writes the joined text into the first member's row and consumes the other members' rows in one transaction, so a restart at any point replays each result once. If the fold fails, the shared turn is refused and each member retries its own row. The transcript append consumes the row in the same transaction, so a second consumer or a retry after restart appends nothing.
- Goal continuation calls `shouldWake` and does not advance while an owed result is pending. The completion turn runs first, and its end continues the Goal.
- One wake path, `wakeOwedExec`, serves the live wake, its single retry and restart recovery. A wake that fails before it becomes a turn, or is refused at enqueue, retries once from the stored row; the live retry keeps the captured target, so admission revalidates the requester's authority. A stop, or a second failure, ends the row with a visible cause. Restart recovery wakes owed rows, which it used to refuse as queued human input.

| Part | Files | Lines |
|---|---|---|
| Deleted in-memory exec path | `bash-tools.exec-notify.ts`: the `pendingExitWakes` set and its reads, `enqueueExecExitNotification`, and the separate settle/log block (`hasExecYieldWake` and the yield sweep now read stored rows) | −46 |
| Shrunk to stay under the line cap | `session-accessor.pending-inputs.ts`: two duplicated "already consumed" receipts become `consumedPendingInputReceipt` (moved to `session-pending-input-value.ts`) | +26 −33 |
| Owed primitive | `sessions/owed.ts` (`owe`, `fold`, `shouldWake`, `readPendingOwed`, `withhold`: +200); `session-pending-input-value.ts` (`readOwedKind`, owed restage, moved receipt: +44); owed-row adoption in `session-accessor.pending-input-request.ts` (+18 −2); absorbed-row consumption in both pending-input kernels and the mutation type (+32) | +294 −2 |
| Glue | `bash-tools.exec-notify.ts` (`wakeOwedExec`, settlement, owed row with origin facts: +104); `session-event-batch.ts` (fold before a shared turn, one refusal path: +68 −15); `queued-chat-inputs.ts` restart wake (+22 −1); `goal-continuation.ts` (+11); `session-yield-sweep.ts` (+4 −1) | +209 −17 |
| **Production total** | 12 files | **+529 −98 (net +431)** |

No parallel in-memory exec-completion path is left. Every exec completion, live or after restart, is an owed row delivered by `wakeOwedExec`. What remains in memory is the shared session-event admission that runs the turn for every producer (cron, hooks, plugins). Its occurrence still carries a copy of the text; that copy can go when session-event admission reads stored rows for all producers, in later owed-result slices. The cron yield-resume path (`execYieldResumes`) is a different consumer and stays out of this slice.

## Evidence

- **Race, deterministic:** a new `server.chat-goal.test.ts` case holds the real exec wake in target preparation until the first turn's Goal check runs. It is red on the merge base (Advance overtakes the completion) and green on head.
- **No deadlock:** a new case makes the first wake fail in preparation; the stored row wakes the completion turn and the Goal then advances. The existing "keeps pursuing after … exec completion" cases end every completion turn before a model call; they stay green.
- **Shared turn:** a new case refuses a shared completion turn before admission; both results are still delivered afterwards. A storage case shows `fold` leaves exactly one row carrying both results; it is red when the absorbed rows are not consumed (both rows remain, so a restart would deliver the second result twice).
- **Storage:** a new pending-input case is red without the kind-preserving restage (restart recovery would refuse an adopted row) and green on head.
- **Touched suites:** exec background follow-up (28/28, shared-turn cases included), yield sweep (6/6), and the pending-input, queued-input, Goal continuation, session-event and restart-resume suites (19 files, 284 tests).
- **Real Gateway, scratch port and state, real model:** an exec result pending in `session_pending_inputs` across a Gateway restart is appended to the transcript exactly once after the restart (5 runs). On head `0abfb478`, which differs from the final head only in the batch's fold-failure path, the same run also shows `Exec completed` before `[System] Advance the active goal` (with openclaw#204327 merged).
- **Repeat runs (final head `4b887e10`, frozen copy):** `server.chat-goal.test.ts` as a whole file, 20 separate runs: 20/20 passed with 72/72 each (1,440 test executions). Both "keeps pursuing after … takes the next turn" variants passed in every run (40/40).

Separate bug, fixed and merged in openclaw#204327 (issue openclaw#204319): on a real Gateway, a Goal did not advance after a background command's completion turn. Post-turn session maintenance waited in the mailbox and the Goal check deferred to it. This happens on `main` too. A plain Goal advances normally on `main`; an earlier note here that it never advanced came from a bad test prompt. With openclaw#204327 the real-Gateway transcript reads: Goal request → `Exec completed …` → `[System] Advance the active goal …`.

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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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