Skip to content

fix: let finished background commands reach the agent before an active goal advances - #204265

Merged
obviyus merged 16 commits into
mainfrom
feat/owed-exec-result
Nov 24, 2026
Merged

obviyus merged 16 commits into
mainfrom
feat/owed-exec-result

Conversation

@obviyus

@obviyus obviyus commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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.

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 fix: keep a goal advancing after a background command's completion turn #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 ….

obviyus and others added 2 commits November 24, 2026 03:50
Closes #204187.

- Add src/sessions/owed.ts: owe() stores an exec result in session_pending_inputs (kind as additive JSON); shouldWake() reads stored rows.
- The exec wake turn adopts its owed row by id; the transcript append consumes it once.
- Goal continuation does not advance while an owed result is pending.
- Restart recovery wakes owed rows from stored state; a failed wake wakes once more from the row.
- Remove the in-memory pendingExitWakes set.

Co-authored-by: obviyus <[email protected]>
- A restart reads the owed kind from the stored row; an adopted row now keeps it.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 23, 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: L labels Nov 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
- A wake from stored state settles itself, including after restart recovery.
- The live retry keeps the request owners and takes over the removal handle.
- shouldWake follows every queued-input page.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
@clawsweeper

clawsweeper Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR persists background command results so completion turns can precede Goal continuation and survive Gateway restarts.

Example: Command build-42 exits with code 0 while its conversation has an active Goal.

  • Before: An automatic Advance turn can run before the agent reads build-42’s result.
  • After: The intended behavior saves the result, delivers its completion turn, and then advances the Goal.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction has clear value, but recovery can lose results and restrictions, exact-head CI has a diff-caused failure, and the central shipped behavior remains unproven.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: An active Goal can advance before reading a finished background command’s result, and an undelivered result can disappear across restart.
Reason: The ordering contract has concrete source and failure evidence, and the collaborator-authored PR establishes direction; the remaining persistence window prevents complete coverage.

Merge readiness

⛔ Blocked before merge - 7 items remain

Keep this PR open: it addresses a verified ordering bug, but completion recovery has correctness and authority defects that block merging.

Priority: P2
Reviewed head: 0b347ed81448001959b755939336187d8083109d

Before merge

  • Preserve the captured target when retrying a live completion (P1) - If the initial completion fails during target preparation, the retry calls wakeOwedExec with wakeOptions but omits target. session-event-handoff computes its producer tool ceiling exclusively from options.expectedTarget.toolsAllow, so a producer restricted to a narrower tool surface retries with that ceiling absent. The same path loses target.deliver:false and can send an explicitly silent completion and its Goal successors to the external route. Pass the original captured target through live retry admission; continuing under current authority does not require dropping its restrictions.
  • Retry a folded batch from its stored joined payload (P1) - With two held completions B and C, fold writes B+C into B’s row and marks C interrupted. If the shared wake then fails before staging, B’s settlement callback retries the original per-command Owed object containing only B; C no longer qualifies as pending. The adopted retry explicitly replaces the stored row with its incoming bytes, erasing C before the agent reads it. Read the pending row’s current payload for retry, or retain sibling rows until the shared input is consumed.
  • Cover the persistence window before allowing Goal advancement (P2) - The process owner records markExited before calling notifyOnExit, but owe first awaits session lookup, store preparation, and a snapshot before inserting the result. If the active turn finishes during those awaits, shouldWake can read no owed rows and eligible sees no completion mailbox input, allowing Advance to queue first. The new regression awaits completeRequesterExec, including owe, before ending the first turn, so it excludes this remaining window. Order result publication and Goal admission through the existing owners so a completed command cannot become temporarily invisible.
  • Retain silent delivery policy in stored completion recovery (P1) - A completion produced with target.deliver:false can remain owed across restart, but the saved message contains only text, identity, provenance, and kind. Recovery reconstructs wakeOwedExec without a delivery restriction, so normal session routing can publish the result and subsequent Goal replies externally. Persist and restore the explicit delivery suppression alongside the result; this policy is independent of the intentionally refreshed session-principal authority.
  • Update the cleanup fixture for persisted completion admission (P2) - The synthetic target in bash-tools.exec-runtime.cleanup.test.ts omits storePath, so this new guard skips its notify path before enqueue. Exact-head CI confirms the resulting failure at line 452: observed ['task'] instead of ['task', 'enqueue']. Adapt that consumer fixture to the new persistence boundary while preserving its notification-order and routing-release assertions.
  • Resolve security concern: Completion retry drops the producer tool ceiling - A requester whose producing turn has a restricted sessionEventToolsAllow surface can reach a retry admitted without expectedTarget.toolsAllow after a preparation failure; that retry can expose tools permitted by the broader session, including filesystem effects excluded from the producing turn.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Preserve the captured target when retrying a live completion — src/agents/bash-tools.exec-notify.ts:361-363
  • [P1] Retry a folded batch from its stored joined payload — src/agents/bash-tools.exec-notify.ts:363
  • [P2] Cover the persistence window before allowing Goal advancement — src/agents/bash-tools.exec-notify.ts:355-358
  • [medium] Completion retry drops the producer tool ceiling — src/agents/bash-tools.exec-notify.ts:363

Tests

  • Missing end-to-end proof: Provide redacted runtime output showing command exit during an active turn, completion before Advance, subsequent Goal advancement, and latest-stable upgrade/restart recovery with existing settings and data intact.
Agent review details

How this fits together

Background exec exits enter the session-event queue; pending-input storage retains their results, and Goal continuation consults that storage before scheduling another agent turn.

flowchart TD
  A[Background command exits] --> B[Pending input store]
  B --> C[Session event admission]
  C --> D[Agent completion turn]
  D --> E[Transcript consumption]
  B --> F[Goal continuation check]
  E --> F
Loading

Technical review

Best possible solution:

Use the existing pending-input and session-event owners to preserve complete result payloads and captured policy through persistence, retries, consumption, and recovery.

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

Current main exposes the reported claim-to-mailbox admission window, and the PR adds a deterministic boundary regression; this read-only review executed no target code.

Is this the best way to solve the issue?

Persisting results in the existing pending-input store fits the reported failure, but recovery must consume authoritative stored payloads while retaining the original admission restrictions.

Full review comments:

  • [P1] Preserve the captured target when retrying a live completion — src/agents/bash-tools.exec-notify.ts:361-363
    If the initial completion fails during target preparation, the retry calls wakeOwedExec with wakeOptions but omits target. session-event-handoff computes its producer tool ceiling exclusively from options.expectedTarget.toolsAllow, so a producer restricted to a narrower tool surface retries with that ceiling absent. The same path loses target.deliver:false and can send an explicitly silent completion and its Goal successors to the external route. Pass the original captured target through live retry admission; continuing under current authority does not require dropping its restrictions.
    Confidence: 0.98
  • [P1] Retry a folded batch from its stored joined payload — src/agents/bash-tools.exec-notify.ts:363
    With two held completions B and C, fold writes B+C into B’s row and marks C interrupted. If the shared wake then fails before staging, B’s settlement callback retries the original per-command Owed object containing only B; C no longer qualifies as pending. The adopted retry explicitly replaces the stored row with its incoming bytes, erasing C before the agent reads it. Read the pending row’s current payload for retry, or retain sibling rows until the shared input is consumed.
    Confidence: 0.98
  • [P2] Cover the persistence window before allowing Goal advancement — src/agents/bash-tools.exec-notify.ts:355-358
    The process owner records markExited before calling notifyOnExit, but owe first awaits session lookup, store preparation, and a snapshot before inserting the result. If the active turn finishes during those awaits, shouldWake can read no owed rows and eligible sees no completion mailbox input, allowing Advance to queue first. The new regression awaits completeRequesterExec, including owe, before ending the first turn, so it excludes this remaining window. Order result publication and Goal admission through the existing owners so a completed command cannot become temporarily invisible.
    Confidence: 0.94
  • [P1] Retain silent delivery policy in stored completion recovery — src/sessions/owed.ts:46-53
    A completion produced with target.deliver:false can remain owed across restart, but the saved message contains only text, identity, provenance, and kind. Recovery reconstructs wakeOwedExec without a delivery restriction, so normal session routing can publish the result and subsequent Goal replies externally. Persist and restore the explicit delivery suppression alongside the result; this policy is independent of the intentionally refreshed session-principal authority.
    Confidence: 0.99
  • [P2] Update the cleanup fixture for persisted completion admission — src/agents/bash-tools.exec-notify.ts:340
    The synthetic target in bash-tools.exec-runtime.cleanup.test.ts omits storePath, so this new guard skips its notify path before enqueue. Exact-head CI confirms the resulting failure at line 452: observed ['task'] instead of ['task', 'enqueue']. Adapt that consumer fixture to the new persistence boundary while preserving its notification-order and routing-release assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Exec completion and yielded-session wake ownership changes intended behavior with a stated reason (51a07cc: Retain pending completion wakes after process finalization so valid yielded waits are not incorrectly failed.)
  • Batched completion turns keeps the original intent (597e400: Combine compatible background results into fewer model turns while preserving result text, request ownership, launching-run identity, and routing.)
  • Goal continuation precedence keeps the original intent (c845d6d: Continue unfinished Goals through the existing queue while giving user input and existing continuations priority.)
  • Pending-input replay identity changes intended behavior with a stated reason (e9999a0: Reconcile replay variations only against the complete accepted request identity.)
  • Queued-input restart recovery keeps the original intent (703c82d: Recover acknowledged queued inputs after crashes and record terminal causes instead of silently losing them.)

Testing

Proof path: in-process harness.

Security

Needs attention: The new live retry can remove a captured producer tool restriction before starting another agent turn.

Evidence

Security concerns:

  • [medium] Completion retry drops the producer tool ceiling — src/agents/bash-tools.exec-notify.ts:363
    A requester whose producing turn has a restricted sessionEventToolsAllow surface can reach a retry admitted without expectedTarget.toolsAllow after a preparation failure; that retry can expose tools permitted by the broader session, including filesystem effects excluded from the producing turn.
    Confidence: 0.97

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 597e400 adds src/auto-reply/reply/session-event-batch.ts:182 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 597e400e97d7; files: src/auto-reply/reply/session-event-batch.ts)

PR surface

Source +352, Tests +129, Docs +1. Total +482 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 415 63 +352
Tests 3 130 1 +129
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 546 64 +482

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.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #204187
Summary: This PR is the proposed repair for the linked exec-result versus Goal-continuation admission race.

Members:

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

Labels

Label changes:

  • add P2: The underlying bug intermittently advances Goals with stale command context and has a focused completion-lifecycle repair boundary.
  • add merge-risk: 🚨 message-delivery: Retry and restart recovery can discard an explicitly silent completion’s delivery suppression.
  • add merge-risk: 🚨 session-state: A failed shared wake can overwrite joined stored results with one command’s original text.
  • add merge-risk: 🚨 security-boundary: A failed live completion retries without the captured producer tool ceiling.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The underlying bug intermittently advances Goals with stale command context and has a focused completion-lifecycle repair boundary.
  • merge-risk: 🚨 security-boundary: A failed live completion retries without the captured producer tool ceiling.
  • merge-risk: 🚨 session-state: A failed shared wake can overwrite joined stored results with one command’s original text.
  • merge-risk: 🚨 message-delivery: Retry and restart recovery can discard an explicitly silent completion’s delivery suppression.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

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

Workflow

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

Reviewed November 23, 2026, 6:18 PM ET / 23:18 UTC.

- A retry reads the stored row, which carries every folded result.

Co-authored-by: obviyus <[email protected]>
obviyus and others added 2 commits November 24, 2026 05:07
- Admission revalidates the requester's authority and store on the retry.

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

- A refused enqueue or retry settles the stored row instead of leaving it owed with no wake.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Rejected review findings:

  • [P2] Commit folded text and constituent retirement atomically (src/sessions/owed.ts, fold): rejected. The failure needs a Gateway crash in the window between two consecutive writes during a batch flush. Its effect is one duplicated exec result after restart, never a lost one: the result stays visible and the agent is told to stay silent for duplicate results. Making it atomic needs a new pending-input kernel mutation. That is lasting complexity for a rare, visible, recoverable fault, so it is recorded as an accepted edge in the PR body.
  • [P2, round 2] Keep stored wakes bound to their original store, restart half (src/gateway/queued-chat-inputs.ts): rejected. Restart recovery reads the owed row from a store the current config selects, and the stored wake resolves the same configured store. A different store would need a config change inside the restart window. The live-retry half is fixed: the retry now carries the captured target, including its store.

- Captured targets always carry a store; owed-result storage keeps its own owner suite.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Rejected review findings:

  • [P1] Preserve the originating requester when replaying owed exec results (src/gateway/queued-chat-inputs.ts): rejected. This matches the shipped restart contract and does not widen it. docs/gateway/background-process.md (durable processes): "An adopted completion or lost-process outcome is new system input to the owning session under that session principal's current authority. OpenClaw does not restore the original requester or operator continuation." prepareAdoptedDurableProcessNotification already wakes restart completions through withoutGatewayToolCallerIdentity for any starter, and lost background commands are already reported after restart the same way. Before a restart, the live path keeps the requester's restrictions (the retry now carries the captured target). Restoring a requester across restart would need stored requester authority, which the owed-result design adds in a later slice (OriginFacts).
  • [P2] Commit folded text and constituent retirement atomically (src/sessions/owed.ts, fold): still rejected, as in the earlier comment. A crash between two consecutive writes at most duplicates one visible result. It never loses one.

obviyus and others added 2 commits November 24, 2026 06:22
- Both pending-input kernels restage an owed row with its new bytes; ordinary rows keep theirs.

Co-authored-by: obviyus <[email protected]>
- Delete enqueueExecExitNotification; the live wake, its retry and restart recovery use wakeOwedExec.
- The owed row stores originFacts (requester, command owner, operator profile) as additive JSON; restage keeps it.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the CI reds on head 1b3e2e8e1d69 are not caused by this PR.

ci-triage on that head:

checks-node-changed-14	src/gateway/gateway-skill-authoring-plugin.e2e.test.ts
checks-node-changed-2	test/gateway-restart-resume.e2e.test.ts
checks-node-changed-4	test/e2e/qa-lab/runtime/cron-one-shot-run.e2e.test.ts
checks-node-changed-6	src/gateway/server-templates-add-authority.e2e.test.ts
checks-node-changed-9	test/e2e/qa-lab/runtime/gateway-provider-review-product-proof.e2e.test.ts
checks-node-changed-9	test/gateway-cold-agent-abort.e2e.test.ts
checks-node-changed-compact-large-8	src/gateway/server.chat-membership-authority.product.test.ts	MAIN-ALSO
checks-node-changed-extensions-bundle-9	extensions/tlon/src/monitor/index.test.ts
  • The six e2e files (and five more the changed-file lanes selected on the previous head) fail on pure main 86fcb81e64c0. I ran the eleven files there in one local run: all eleven fail. main CI never runs them, because only changed-file lanes select them. server-templates-add-authority.e2e.test.ts also fails on the merge base e2973f933f10, with the same assertion (a revoked operator still publishes).
  • server.chat-membership-authority.product.test.ts: ci-triage reports it as failing on main.
  • extensions/tlon/src/monitor/index.test.ts: 20/20 pass locally on both this head and main 86fcb81e. It imports no file this PR changes. This is a CI flake.

@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Rejected review findings (final head 1b3e2e8e1d69):

  • [P1] Restore the originating requester before replaying an owed result (src/gateway/queued-chat-inputs.ts): rejected. This keeps the existing restart contract and does not widen authority; the code citations are in fix: let finished background commands reach the agent before an active goal advances #204265 (comment). On main, every exec completion woken after a restart (lost ordinary commands and adopted durable processes, src/agents/bash-process-durable.ts:167,190,253) is captured inside withoutGatewayToolCallerIdentity (src/agents/bash-process-durable-notify.ts:13,42-43) and runs as a session-principal turn (session-event-handoff.ts:486-489). The owed-row restart wake takes the same path. The row now stores originFacts, so a later slice can intersect the recorded requester with current policy without a migration; consumption does not change in this PR.
  • [P2] Persist consumption of every member of a shared completion turn (src/config/sessions/session-pending-input-value.ts): rejected as an accepted edge, recorded in the PR body. A Gateway crash between a shared turn's commit and the settlement that hides its other rows can deliver those results a second time after restart. They are duplicated, never lost, and the duplicate is visible in the transcript. Closing the window needs a multi-row consumption mutation in the pending-input kernel; that cost is not justified for a crash-only duplicate.

obviyus and others added 3 commits November 24, 2026 09:24
- A pending-input stage can consume absorbed owed rows in the same transaction (SQLite and memory kernels).
- The batch flush folds members into the first row before the shared turn; a restart replays one row, so each result is delivered once.
- Retries read the stored row's text.

Co-authored-by: obviyus <[email protected]>
- No member is double-carried: each retries its own stored row. Both refusal paths share refuseSharedTurn.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Rejected review findings (final head 4b887e1047e9):

  • [P1] Restore the original caller before replaying an owed completion (src/gateway/queued-chat-inputs.ts): rejected. This is not a widening. On main, every exec completion woken after a Gateway restart already runs as a session-principal turn with no originating caller: lost ordinary commands and adopted durable processes (src/agents/bash-process-durable.ts:167,190,253) capture their target inside withoutGatewayToolCallerIdentity (src/agents/bash-process-durable-notify.ts:13,42-43), and session-event-handoff.ts:486-489 then sets sessionPrincipalTurn. The owed-row restart wake takes the same path, and the shipped contract documents it (docs/gateway/background-process.md, durable processes and lost background commands). Before a restart, the live wake and its retry keep the captured target and the requester's restrictions. Full citation: fix: let finished background commands reach the agent before an active goal advances #204265 (comment). The row stores originFacts, so the slice that restores requester authority across restart can intersect them with current policy without a migration.

The earlier P2 (shared-turn rows consumed separately) is fixed on this head: fold writes the joined text and consumes the other rows in one transaction.

@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the CI reds on head 4b887e1047e9 are not caused by this PR.

ci-triage:

checks-node-changed	src/agents/subagents/registry/subagent-registry.requester-wake.e2e.test.ts
checks-node-changed-compact-large-16-2	src/cron/session-context-accounting.gateway.integration.test.ts	MAIN-ALSO
checks-node-changed-compact-large-30	src/auto-reply/reply/agent-runner-compaction-fallback.test.ts	MAIN-ALSO
checks-node-changed-compact-large-32	src/agents/embedded-agent-runner.prompt-cache.test.ts	MAIN-ALSO
checks-node-changed-compact-large-41	src/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.ts	MAIN-ALSO
  • subagent-registry.requester-wake.e2e.test.ts: the same command on a frozen copy of this head and on a frozen copy of the merge base main c237dbd5bf18 gives the same result on both. The six "settles requester receipts" cases time out at 120 s on both trees, and the other 44 pass on both.
  • The other four are failing on main per ci-triage.
  • Earlier heads' changed-lane e2e reds (eleven files) fail on pure main 86fcb81e64c0 in one local run: fix: let finished background commands reach the agent before an active goal advances #204265 (comment)

@obviyus
obviyus merged commit 463d774 into main Nov 24, 2026
143 of 150 checks passed
@obviyus
obviyus deleted the feat/owed-exec-result branch November 24, 2026 06:49
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 463d774. A finished background command's result is now stored in the conversation when the command exits (owed row in session_pending_inputs, no schema change). An active Goal waits for it, its turn appends it once, and a Gateway restart before that turn still delivers it exactly once. Proof: a deterministic race test (red on the merge base, green on head), 20/20 full-file runs of server.chat-goal.test.ts, and real-Gateway runs showing Exec completed before Advance and a single append after restart. The Advance stall after completion turns was a separate bug, fixed in #204327.

obviyus added a commit that referenced this pull request Nov 24, 2026
…toring them fails

The exec completion runs in the async context of the turn that started the command. An
incognito turn's session-actor binding and work signal end with that turn, so the owed
row write (and, before #204265, the live wake) failed and the result was only logged.
Store and wake outside that context. If owe() still fails, wake the chat once live.

Key the durable restart notice test by the adopted process instance, and declare the
exec completion tests for src/sessions/owed.ts in the changed-test planner, which
missed them for #204265.

Co-authored-by: obviyus <[email protected]>
obviyus added a commit that referenced this pull request Nov 24, 2026
…toring them fails (#204532)

## Problem

1. **Incognito chats never get a background command's completion turn.** On a scratch Gateway with a real model, an incognito chat runs a background command, replies, and then nothing happens when the command finishes. The completion runs in the async context of the turn that started the command. For an incognito chat, that context holds the turn's session-actor binding and work signal, and both end with the turn.
   - Before #204265 (`463d7748^`): the live wake fails with `SessionDeliveryGenerationUnavailableError`.
   - On `main`: `owe()` fails first, and the Gateway logs `[exec] completion was not admitted (Chat session storage admission ended)`.

   So this predates #204265. #204265 only moved the failure point.
2. **A failed `owe()` drops the result.** Since #204265, `notifyOnExit` stores the result (`owe()`) before it wakes the chat, and its catch only logs a failed `owe()`. Any store failure (busy database, store fence) silently drops a produced result.
3. **Five exec-notification test files went red on scheduled `main`** (run 45348156095); #204507 fixed four. #204265's PR CI did not select them. It changed `src/sessions/owed.ts`, and these tests live in `src/agents/`, past the two-import walk. This is the cross-directory miss the #204346 closing loop covers.

## Solution

- `notifyOnExit` stores and wakes outside the producing turn's session-actor binding and work scope (`runWithoutSessionActorStorage`, `runOutsideAsyncWorkScope`). Both are existing helpers for independent work. The completion acquires its own session actor, so incognito chats store the owed row and get their completion turn.
- If `owe()` still fails, the completion wakes its chat once through the same live wake, without a stored row. That one result loses restart recovery, and the Gateway logs why. It is never only logged.
- #204507 already moved four of the five red files to the owed-row contract (owed-id context keys). The fifth, `bash-process-durable.test.ts`, still counted restart notices by the old slug key `exec:<slug>`; its helper now resolves the adopted process instance (`processSessionInstanceId`).
- New `bash-tools.exec-notify.store-failure.test.ts`: `owe()` rejects, and the completion still wakes its chat once.
- #204346 closing loop: `src/sessions/owed.ts` is now an owner in `scripts/lib/ci-changed-node-test-plan.mts`. A change to it selects a declared set: the 5 test files and the new store-failure test. A planner test checks that selection.

## Impact

- Fixes a pre-existing loss: incognito exec results were also lost before #204265 (baseline b8c95a3 repro). On the measured production deployment: 0 events in the retained ~3.8-day window.

- Incognito chats get background command completion turns.
- A produced exec result is never only logged when its row cannot be stored.
- Ordinary chats: no change (Goal ordering and restart exactly-once re-proven below).
- Production: 1 file, +27 −7.

## Evidence

- **Incognito, real Gateway** (scratch state and ports, real model; the chat runs a background command, replies `STARTED`, then must answer the completion):
  - before #204265 (`463d7748^`): no completion turn; `[exec] completion delivery failed (SessionDeliveryGenerationUnavailableError …)`.
  - `main`: no completion turn; `[exec] completion was not admitted (Chat session storage admission ended)`.
  - this PR: the completion turn runs (`SEEN_…` reply); no exec warnings, so the owed row was stored.
- **Ordinary chats, real Gateway, this PR:** `Exec completed` precedes the Goal's Advance turn and is appended once; a result pending across a Gateway restart is appended exactly once after it (4/4 checks).
- **Store failure:** `bash-tools.exec-notify.store-failure.test.ts` fails on `main` (the wake is called 0 times) and passes here.
- **Tests (rebased on `main`):** the 5 files plus exec background follow-up, requester, queue-full, yield sweep and planner integration: all pass, except that locally on macOS `bash-process-durable.test.ts` stops at the Darwin ACL guard in `@openclaw/fs-safe` before its assertion (CI on Linux runs it). `server.chat-goal.test.ts` 72/72. `pnpm tsgo:core` passes.
- **Planner:** `ci-changed-node-test-plan.integration.test.ts` checks that a change to `src/sessions/owed.ts` selects the 6 declared tests.

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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 25, 2026
…toring them fails (#204532)

1. **Incognito chats never get a background command's completion turn.** On a scratch Gateway with a real model, an incognito chat runs a background command, replies, and then nothing happens when the command finishes. The completion runs in the async context of the turn that started the command. For an incognito chat, that context holds the turn's session-actor binding and work signal, and both end with the turn.
   - Before #204265 (`463d7748^`): the live wake fails with `SessionDeliveryGenerationUnavailableError`.
   - On `main`: `owe()` fails first, and the Gateway logs `[exec] completion was not admitted (Chat session storage admission ended)`.

   So this predates #204265. #204265 only moved the failure point.
2. **A failed `owe()` drops the result.** Since #204265, `notifyOnExit` stores the result (`owe()`) before it wakes the chat, and its catch only logs a failed `owe()`. Any store failure (busy database, store fence) silently drops a produced result.
3. **Five exec-notification test files went red on scheduled `main`** (run 45348156095); #204507 fixed four. #204265's PR CI did not select them. It changed `src/sessions/owed.ts`, and these tests live in `src/agents/`, past the two-import walk. This is the cross-directory miss the #204346 closing loop covers.

- `notifyOnExit` stores and wakes outside the producing turn's session-actor binding and work scope (`runWithoutSessionActorStorage`, `runOutsideAsyncWorkScope`). Both are existing helpers for independent work. The completion acquires its own session actor, so incognito chats store the owed row and get their completion turn.
- If `owe()` still fails, the completion wakes its chat once through the same live wake, without a stored row. That one result loses restart recovery, and the Gateway logs why. It is never only logged.
- #204507 already moved four of the five red files to the owed-row contract (owed-id context keys). The fifth, `bash-process-durable.test.ts`, still counted restart notices by the old slug key `exec:<slug>`; its helper now resolves the adopted process instance (`processSessionInstanceId`).
- New `bash-tools.exec-notify.store-failure.test.ts`: `owe()` rejects, and the completion still wakes its chat once.
- #204346 closing loop: `src/sessions/owed.ts` is now an owner in `scripts/lib/ci-changed-node-test-plan.mts`. A change to it selects a declared set: the 5 test files and the new store-failure test. A planner test checks that selection.

- Fixes a pre-existing loss: incognito exec results were also lost before #204265 (baseline b8c95a3 repro). On the measured production deployment: 0 events in the retained ~3.8-day window.

- Incognito chats get background command completion turns.
- A produced exec result is never only logged when its row cannot be stored.
- Ordinary chats: no change (Goal ordering and restart exactly-once re-proven below).
- Production: 1 file, +27 −7.

- **Incognito, real Gateway** (scratch state and ports, real model; the chat runs a background command, replies `STARTED`, then must answer the completion):
  - before #204265 (`463d7748^`): no completion turn; `[exec] completion delivery failed (SessionDeliveryGenerationUnavailableError …)`.
  - `main`: no completion turn; `[exec] completion was not admitted (Chat session storage admission ended)`.
  - this PR: the completion turn runs (`SEEN_…` reply); no exec warnings, so the owed row was stored.
- **Ordinary chats, real Gateway, this PR:** `Exec completed` precedes the Goal's Advance turn and is appended once; a result pending across a Gateway restart is appended exactly once after it (4/4 checks).
- **Store failure:** `bash-tools.exec-notify.store-failure.test.ts` fails on `main` (the wake is called 0 times) and passes here.
- **Tests (rebased on `main`):** the 5 files plus exec background follow-up, requester, queue-full, yield sweep and planner integration: all pass, except that locally on macOS `bash-process-durable.test.ts` stops at the Darwin ACL guard in `@openclaw/fs-safe` before its assertion (CI on Linux runs it). `server.chat-goal.test.ts` 72/72. `pnpm tsgo:core` passes.
- **Planner:** `ci-changed-node-test-plan.integration.test.ts` checks that a change to `src/sessions/owed.ts` selects the 6 declared tests.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 0164469)
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 25, 2026
…toring them fails (openclaw#204532)

## Problem

1. **Incognito chats never get a background command's completion turn.** On a scratch Gateway with a real model, an incognito chat runs a background command, replies, and then nothing happens when the command finishes. The completion runs in the async context of the turn that started the command. For an incognito chat, that context holds the turn's session-actor binding and work signal, and both end with the turn.
   - Before openclaw#204265 (`7a8c93cd^`): the live wake fails with `SessionDeliveryGenerationUnavailableError`.
   - On `main`: `owe()` fails first, and the Gateway logs `[exec] completion was not admitted (Chat session storage admission ended)`.

   So this predates openclaw#204265. openclaw#204265 only moved the failure point.
2. **A failed `owe()` drops the result.** Since openclaw#204265, `notifyOnExit` stores the result (`owe()`) before it wakes the chat, and its catch only logs a failed `owe()`. Any store failure (busy database, store fence) silently drops a produced result.
3. **Five exec-notification test files went red on scheduled `main`** (run 45348156095); openclaw#204507 fixed four. openclaw#204265's PR CI did not select them. It changed `src/sessions/owed.ts`, and these tests live in `src/agents/`, past the two-import walk. This is the cross-directory miss the openclaw#204346 closing loop covers.

## Solution

- `notifyOnExit` stores and wakes outside the producing turn's session-actor binding and work scope (`runWithoutSessionActorStorage`, `runOutsideAsyncWorkScope`). Both are existing helpers for independent work. The completion acquires its own session actor, so incognito chats store the owed row and get their completion turn.
- If `owe()` still fails, the completion wakes its chat once through the same live wake, without a stored row. That one result loses restart recovery, and the Gateway logs why. It is never only logged.
- openclaw#204507 already moved four of the five red files to the owed-row contract (owed-id context keys). The fifth, `bash-process-durable.test.ts`, still counted restart notices by the old slug key `exec:<slug>`; its helper now resolves the adopted process instance (`processSessionInstanceId`).
- New `bash-tools.exec-notify.store-failure.test.ts`: `owe()` rejects, and the completion still wakes its chat once.
- openclaw#204346 closing loop: `src/sessions/owed.ts` is now an owner in `scripts/lib/ci-changed-node-test-plan.mts`. A change to it selects a declared set: the 5 test files and the new store-failure test. A planner test checks that selection.

## Impact

- Fixes a pre-existing loss: incognito exec results were also lost before openclaw#204265 (baseline e5607f8 repro). On the measured production deployment: 0 events in the retained ~3.8-day window.

- Incognito chats get background command completion turns.
- A produced exec result is never only logged when its row cannot be stored.
- Ordinary chats: no change (Goal ordering and restart exactly-once re-proven below).
- Production: 1 file, +27 −7.

## Evidence

- **Incognito, real Gateway** (scratch state and ports, real model; the chat runs a background command, replies `STARTED`, then must answer the completion):
  - before openclaw#204265 (`7a8c93cd^`): no completion turn; `[exec] completion delivery failed (SessionDeliveryGenerationUnavailableError …)`.
  - `main`: no completion turn; `[exec] completion was not admitted (Chat session storage admission ended)`.
  - this PR: the completion turn runs (`SEEN_…` reply); no exec warnings, so the owed row was stored.
- **Ordinary chats, real Gateway, this PR:** `Exec completed` precedes the Goal's Advance turn and is appended once; a result pending across a Gateway restart is appended exactly once after it (4/4 checks).
- **Store failure:** `bash-tools.exec-notify.store-failure.test.ts` fails on `main` (the wake is called 0 times) and passes here.
- **Tests (rebased on `main`):** the 5 files plus exec background follow-up, requester, queue-full, yield sweep and planner integration: all pass, except that locally on macOS `bash-process-durable.test.ts` stops at the Darwin ACL guard in `@openclaw/fs-safe` before its assertion (CI on Linux runs it). `server.chat-goal.test.ts` 72/72. `pnpm tsgo:core` passes.
- **Planner:** `ci-changed-node-test-plan.integration.test.ts` checks that a change to `src/sessions/owed.ts` selects the 6 declared tests.

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

## Problem

`src/gateway/session-yield-sweep.test.ts` > "settles only an unreachable parked lifecycle (exec-completion)" fails intermittently on scheduled `main` (run 45403387860): `expected undefined to be 'failed'` at the final status check.

Since #204265, the yield sweep keeps a yielded session waiting while it has a stored owed exec result (`shouldWake`, `session-yield-sweep.ts:45`). When the exec completion's wake settles as `cancelled`, `settleOwedExecWake` withholds the owed row asynchronously: `readPendingOwed` and then `withhold` on the database worker. The test resolved the wake and advanced the fake clock straight away. When the sweep tick ran before `withhold` committed, the sweep still saw the pending row and correctly left the session waiting, so the status stayed unset.

## Solution

Test-only change. After the wake settles, the test waits until `shouldWake` (the stored-row check the sweep itself uses) reports no owed result, then advances the clock. Product behavior is unchanged: the next sweep tick settles the session.

#204609 and #204621 do not touch this path. #204609 changes only `session-restart-resume-custody.ts`, which only the restart path imports. #204621 changes reply-operation backend readiness, which none of these modules use; the test's wake is mocked.

## Impact

No change to production code or user behavior.

## Evidence

- Before: intermittent red on scheduled `main` with the assertion above: run 45403387860, and again in run 45849028735 (2026-11-26, `checks-node-compact-large-14`, after #205835), `expected undefined to be 'failed'` in the exec-completion case. The race mechanism (`settleOwedExecWake` withholds the owed row after the wake settles) is unchanged on current `main`.
- Negative control (deterministic): with a 500 ms delay inserted before that `withhold` (local throwaway change), current `main` fails the exec-completion case 3/3 with the same assertion; with this change it passes 3/3.
- Without the delay, interleaved runs of `session-yield-sweep.test.ts` with this change applied to current `main`: 20/20 green (main alone was also 20/20 locally; the natural race is rare).

## Merge danger

Two-way door: test-only, a revert fully undoes it. Blast radius: one test file.

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

## Problem

`src/gateway/session-yield-sweep.test.ts` > "settles only an unreachable parked lifecycle (exec-completion)" fails intermittently on scheduled `main` (run 45403387860): `expected undefined to be 'failed'` at the final status check.

Since openclaw#204265, the yield sweep keeps a yielded session waiting while it has a stored owed exec result (`shouldWake`, `session-yield-sweep.ts:45`). When the exec completion's wake settles as `cancelled`, `settleOwedExecWake` withholds the owed row asynchronously: `readPendingOwed` and then `withhold` on the database worker. The test resolved the wake and advanced the fake clock straight away. When the sweep tick ran before `withhold` committed, the sweep still saw the pending row and correctly left the session waiting, so the status stayed unset.

## Solution

Test-only change. After the wake settles, the test waits until `shouldWake` (the stored-row check the sweep itself uses) reports no owed result, then advances the clock. Product behavior is unchanged: the next sweep tick settles the session.

openclaw#204609 and openclaw#204621 do not touch this path. openclaw#204609 changes only `session-restart-resume-custody.ts`, which only the restart path imports. openclaw#204621 changes reply-operation backend readiness, which none of these modules use; the test's wake is mocked.

## Impact

No change to production code or user behavior.

## Evidence

- Before: intermittent red on scheduled `main` with the assertion above: run 45403387860, and again in run 45849028735 (2026-11-26, `checks-node-compact-large-14`, after openclaw#205835), `expected undefined to be 'failed'` in the exec-completion case. The race mechanism (`settleOwedExecWake` withholds the owed row after the wake settles) is unchanged on current `main`.
- Negative control (deterministic): with a 500 ms delay inserted before that `withhold` (local throwaway change), current `main` fails the exec-completion case 3/3 with the same assertion; with this change it passes 3/3.
- Without the delay, interleaved runs of `session-yield-sweep.test.ts` with this change applied to current `main`: 20/20 green (main alone was also 20/20 locally; the natural race is rare).

## Merge danger

Two-way door: test-only, a revert fully undoes it. Blast radius: one test file.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Goal continuation can run before a background exec result (admission-window race)

1 participant