Skip to content

fix: background completion is dropped when the config changes mid-turn - #169529

Merged
RomneyDa merged 13 commits into
openclaw:mainfrom
wangmiao0668000666:fix/session-event-config-change-readmit
Oct 16, 2026
Merged

RomneyDa merged 13 commits into
openclaw:mainfrom
wangmiao0668000666:fix/session-event-config-change-readmit

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #169054

What Problem This Solves

A background completion that an active turn already accepted (tools.exec.notifyOnExit, restart continuations, hook wakes, ACP/CLI notices) is silently dropped when a config publication (config.apply/config.patch, hot reload, auth.order rotation) lands before it starts. The queued follow-up run holds the config captured at enqueue, the session-event owner rejects it with Session event configuration changed; retry under the current policy, and no producer retries — so the assistant never runs its follow-up turn. Regression from #167113 in the 2026.10.5 line.

User Impact

Accepted background completions now still run after a mid-turn config change, under the newly published policy (e.g. a just-added tools.deny applies). Stop, abort, queue abandonment, and producer retirement still settle terminally; a publication storm is bounded (2 re-admissions) and then settles as failed with an error log instead of looping or leaking into a later ordinary turn.

Why This Change Was Made

session-event-handoff.ts is the single owner. The stale-config guard stays (running under a superseded policy would be wrong). Instead, when that guard rejects an occurrence that never started, never attempted delivery, was not aborted and was not abandoned, finish() releases custody and re-dispatches the same occurrence through enqueueSessionEventForHost, which re-reads current config and re-runs every destination/authority check. The producer contract carries over: captured target (store, tool ceiling, settings, delivery opt-out), assertCurrent, abortSignal, onAdopted, and — if never accepted — the submitting assertAcceptanceCurrent. The original receipt's cancel()/settled forward to the live attempt.

Maintainer update (merge with main after #173452)

#173452 moved the config check from admission/adoption into assertEffectCurrent, which is still fed to execution-start assertSourceCurrent, so the drop still reproduced on main (now at execution start instead of onAdopted). The branch now:

  • merges current main and ports the re-admission onto assertEffectCurrent;
  • gives each re-admission its own MessageSid (<occurrence>:readmission-<n>): inbound dedupe is retained once a turn is adopted, so reusing the occurrence id made the re-dispatch a silent duplicate drop (the previous mocked-dispatch tests could not observe this);
  • keeps passive-notice preservation (preserveOccurrenceOnRejection) only until some attempt has adopted the occurrence (autoreview P2);
  • keeps durable exec sources retryable (ClawSweeper P1): followup-turn-execution.ts now asserts the event's internalEventExecution.assertCurrent before recovery.admitUserTurn, so a stale-policy attempt never records the exec:<process-id> restart-recovery source claim that would make the re-admission a terminal duplicate; the resulting pre-adoption abandonment is treated as the policy rejection, not a terminal cleanup;
  • replaces the old mocked-adoption cases (incompatible with main's slimmed handoff test harness, which forbids synthetic adoption) with a real queue/dispatcher regression.

Production: src/auto-reply/reply/session-event-handoff.ts (~+105/-9) and a 3-line pre-admission assertion in followup-turn-execution.ts.

Known residual: a publication landing during admitUserTurn's own awaits can still terminalize the durable source before execution start rejects the attempt; it then settles failed with an error log (current main behavior), not silently. Closing that fully would mean changing restart-recovery source-retirement policy, which is out of scope. No config, protocol, storage, or migration surface.

Evidence

New src/auto-reply/reply/session-event-config-readmission.test.ts drives the real dispatcher, followup queue, durable restart-recovery admission and session store (only runEmbeddedAgent is mocked) on a channel-routed session with the real exec producer identity (sourceTurnId: "exec:<id>"): turn 1 is held in the model, the exec completion is accepted as a deferred follow-up, tools.deny: ["write"] is published, turn 1 is released.

Real exec producer proof

New case in src/agents/bash-tools.process.e2e.test.ts (re-admits a real deferred exec completion under a policy published mid-turn): the real exec runtime spawns a real background child with notifyOnExit, the real exec-notify producer enqueues its completion (asserted sourceTurnId: exec:<process-instance-id>) on a channel-routed session while an active turn is held; the completion is accepted as deferred, tools.deny: ["write"] is published, the active turn is released. Only model inference is synthetic (the harness's existing mock-isolation).

  • RED with main's session-event-handoff.ts + followup-turn-execution.ts swapped in: fails (completion never runs).
  • GREEN on this head: completion settles completed, executionStarted: true, the completion turn's prompt contains the child's output, and it binds config.tools.deny === ["write"]; no system events remain. Whole file 12/12 passed (pnpm test src/agents/bash-tools.process.e2e.test.ts --maxWorkers=1: 284s wall on a loaded host; the new case ~6s).

Final-effect authority proof (real managed write tool)

session-event-config-readmission.test.ts now runs five scenarios on a channel-routed session with sourceTurnId: exec:<id>. In the re-admitted completion turn the synthetic model builds the real managed tool surface (createAgentHarnessHostCapabilities + buildEmbeddedAttemptToolRunContext + resolveEmbeddedAttemptToolConstructionPlan, same path as session-event-permissions) and calls the real write tool against the workspace; the assertion is on the file on disk:

Scenario Publication while deferred Result on this head On main
published-deny tools.deny: ["write"] completion runs; no file written completion dropped (fails)
retained-ceiling tools.deny: ["exec"] (write allowed by current policy); captured target toolsAllow: ["read"] completion runs; no file written (producer ceiling retained across re-admission) dropped (fails)
allow-control tools.deny: ["exec"], no ceiling completion runs; file written (proves the probe can write after re-admission) dropped (fails)
revoked-producer producer assertCurrent throws after publication settles failed, model never invoked, no file same
publication-storm new policy at every liveness check settles failed after the bounded budget, no file same

All 5 pass on this head; the first three fail with main's session-event-handoff.ts + followup-turn-execution.ts. Only model decisions are synthetic; admission, queue, durable source admission, tool construction, and filesystem effects are real. A packaged-Gateway rerun of the contributor's driver on the restructured path was not repeated (the driver is not in the tree).

  • Durable-source RED (routed session + exec:<id>, before the pre-admission assertion): completion settles failed; the same test without sourceTurnId passes, isolating the durable source claim. Reverting either the pre-admission assertion or the abandonment classification fails the test.

  • RED on main (origin/main production file, same test): storm: false fails — completion settles { status: "failed", executionStarted: false }. Control with no publication completes, isolating the publication as the cause.

  • GREEN on this head: completion settles completed, executionStarted: true; the second model run binds config.tools.deny === ["write"]; no system events remain.

  • Storm (storm: true): every liveness check publishes a distinct policy; the completion settles failed, never runs, and nothing is left for a later turn (terminal bound).

  • Adjacent suites on the final head: session-event-handoff, session-event-permissions, followup-turn-admission, followup-turn-execution (+steering), followup-runner (+turn-callbacks, heartbeat-drain), agent-runner-execution-session-events, queue/lifecycle + new file — 160/160 passed. Codex autoreview (P1) on the final branch: scoped-clean. pnpm tsgo:core clean; oxlint/oxfmt clean.

  • pnpm test src/auto-reply/reply/session-event-config-readmission.test.ts --maxWorkers=1: ~70–130s wall on a loaded host (2 cases, ~8–20s each, dominated by real reply-runtime prewarm like sibling session-event-permissions cases). Lives in its own file because session-event-permissions.test.ts is at the line-cap ratchet; registered in the database-worker core paths (needs the host SQLite broker).

  • CI: the earlier checks-node-changed-1 red was src/agents/bash-tools.process.e2e.test.ts (keeps post-exit finalizer failure truthful…), outside this PR's files.

The contributor's earlier packaged-Gateway RED/GREEN traces (hook wake + tools.deny rewrite, retained producer ceiling, destination replacement) were captured on the pre-#173452 shape; they remain in the collapsed section below for history.

Credit: original fix, design, and Gateway proof by @wangmiao0668000666.

Original PR description (pre-#173452 shape)

Closes #169054

What Problem This Solves

Fixes: a background completion that an active turn already accepted is silently destroyed when a configuration change lands before that event starts, so the assistant never runs its follow-up turn.

An automatic exec completion (tools.exec.notifyOnExit), a restart continuation, an ACP parent-stream notice, a CLI stall notice, or a hook event that defers to the running turn is accepted by that turn. Any config publication in between — config.apply, config.patch, a hot reload, an auth.order rotation — made the session-event owner treat the occurrence as failed (Session event configuration changed; retry under the current policy) and its settlement path then cancelled the queued occurrence. No producer retries, so the event was lost without a trace.

User Impact

An event that an active turn already accepted is no longer discarded when a configuration change lands mid-turn. The occurrence stays under the session-event owner's custody and is re-admitted through a fresh dispatch that binds the current policy, so the follow-up turn still runs — with the operator's latest tool restrictions, not the stale ones.

Terminal settlements consume the occurrence exactly as before, and this now holds across the re-admission chain too: Stop, abort, queue-owner abandonment (queue-capacity drops, lifecycle cleanup), and producer cancellation of a pending re-admission all consume the occurrence — canceled work never leaks into the next ordinary turn. When the bounded re-admission budget (two attempts) is exhausted, or the re-dispatch itself rejects synchronously (retired producer, moved destination, revoked ingress), the occurrence settles as failed with an explicit error log instead of being parked in the passive queue, where a later ordinary turn would have drained it as contract-less prompt text under its own authority.

An event that never reached an accepted turn keeps its current behavior, and a real destination change (store replacement, agent deletion, unresolvable agent) still fails. Events that already started or attempted delivery still fail as before.

Why This Change Was Made

assertOwnerCurrent in src/auto-reply/reply/session-event-handoff.ts compared the captured config object identity plus the runtime-config publication metadata and threw for any change. That guard must stay: the queued follow-up run captured its execution config at dispatch time, so letting adoption proceed after a publication would run the event under the stale policy — including a tools.deny the operator just added.

So instead of relaxing the guard, settlement now converts exactly one failure mode into a fresh re-admission: when a policy publication rejects an occurrence that never started and never attempted delivery — whether the publication races admission before acceptance or lands at adoption while deferred — finish() releases custody back to the occurrence and calls enqueueSessionEventForHost again with the same occurrence. The new dispatch re-reads the runtime config, re-captures and re-validates the destination, and re-runs every destination check — execution authority is therefore always the current policy by construction.

The re-admission carries the full producer contract forward: the captured expectedTarget (physical session identity, permission ceiling, settings, delivery opt-out), the producer's live assertCurrent revocation callback, the explicit abortSignal, the durable producer's onAdopted commit hook, and — while the original attempt never reached acceptance — the submitting invocation's live assertAcceptanceCurrent, so revoked ingress still rejects the retry before any session preparation or turn admission. A retired producer, moved store, or reset destination still rejects at re-admission; nothing re-mints a producer binding. The original receipt's cancel() forwards to the live re-admission attempt, and its settled promise chains to the re-admitted receipt, so exec-completion acknowledgement and exactly-once semantics are preserved.

Two terminal-path invariants pin the retry chain to the original contract:

  • Re-admissions never opt into preserveOccurrenceOnRejection — that flag is reserved for occurrences that already existed as passive notices before a failed promotion. A producer-owned occurrence whose retry is canceled, stopped, abandoned, or admission-refused is consumed terminally, never released into the passive queue.
  • When the bounded budget is exhausted, or the re-dispatch itself throws synchronously, settlement consumes the occurrence and logs an explicit error. The generic system-event queue carries no captured target, permission ceiling, delivery opt-out, or producer assertion, so leaving the occurrence there would silently drop the producer contract; the failed settlement is observable instead.

No producer retry loops, validator, option, config value, or persistence policy are added.

Production LOC is +137/-8 across one file.

Classification: behavior-completing

Evidence

Real shipped-Gateway proof (RED → GREEN)

Driver: proof-169529.mjs (linked below) runs the packaged Gateway from this PR's dist/ with a stateful mock OpenAI Responses provider. Flow: an ordinary turn is held open by the provider gate → a POST /hooks/wake event (mode: "now", explicit sessionKey) is accepted and deferred behind it ({"ok":true,"mode":"now","eventOutcome":"queued"}) → tools.deny: ["write"] is published by rewriting the config file → turn 1 is released. When the completion turn reaches the model it attempts a write tool call, so the tool result shows exactly which policy the executing turn bound.

GREEN (dist rebuilt from the exact head; the current head 9cf97d1f275 adds only test-file changes on top of 2bfb02d057a, production code is byte-identical):

POST /hooks/wake -> 200 {"ok":true,"mode":"now","eventOutcome":"queued"}
publishing tools.deny=[write] via config file rewrite
releasing turn 1
provider #1: COMPLETION TURN arrived (marker visible); calling write
provider #2: completion-turn write result back; final text
write tool result seen by model: Tool write not found
write denial visible to model: true
forbidden file exists: false
SCENARIO_A_RESULT=PROOF_OK

The stale-policy adoption was rejected, the occurrence was re-admitted through a fresh dispatch, and the completion turn executed under the published policy: write was gone from the toolset (Tool write not found) and no filesystem I/O happened.

RED (same tree with session-event-handoff.ts at the PR-base version, dist rebuilt):

POST /hooks/wake -> 200 {"ok":true,"mode":"now","eventOutcome":"queued"}
publishing tools.deny=[write] via config file rewrite
releasing turn 1
completion turn never arrived (occurrence silently consumed)
SCENARIO_A_RESULT=PROOF_INCOMPLETE

and the base Gateway log shows the silent loss verbatim:

[session-events] session event execution failed source=hook agentId=main sessionKey=agent:main:pr169529proof eventId=3cc6dde6-… error="Error: Session event configuration changed; retry under the current policy"
[hooks] hook wake failed status=failed error="Error: Session event configuration changed; retry under the current policy"

Control (this PR's head, no config publication, turn 1 aborted via chat.send /stop): the deferred occurrence is adopted after the abort and executes under the unchanged policy — the write succeeds and the file is created:

chat.send /stop -> {"ok":true,"payload":{"ok":true,"aborted":true,"runIds":["8c96dafc-…"]}}
provider #1: COMPLETION TURN arrived (marker visible); calling write
control: write result returned: true; file exists: true
SCENARIO_B_RESULT=PROOF_OK

A vs control differ only in the config publication, which isolates the GREEN write denial to the freshly bound policy. The control also confirms the deferred-event machinery itself is exercised end-to-end.

Double-publication collapse (this PR's head): two publications land while the occurrence is deferred (tools.deny: ["write"], then ["write", "message"]); settlement must re-admit exactly once under the latest policy — one completion turn, no per-publication retry storm, no duplicate execution:

publishing tools.deny=["write"] via config file rewrite
publishing tools.deny=["write","message"] via config file rewrite
releasing turn 1
provider #1: COMPLETION TURN arrived (marker visible); calling write
write tool result seen by model: Tool write not found
write denied under the latest policy: true
completion turn count (must be 1): 1
forbidden file exists: false
SCENARIO_C_RESULT=PROOF_OK

Driver script: proof-169529.mjs at the PR-head tree root is intentionally not part of the diff; full run logs are available on request.

Retained-authority final effects (shipped Gateway, exact head)

Two further shipped-Gateway scenarios close the retained-authority gap with final-effect evidence, using deterministic state the config watcher cannot stage on demand.

Scenario D — retained producer tool ceiling beats the current policy. Turn 1 is admitted under tools.deny: ["write"], so the background exec completion it produces captures a tool ceiling that excludes write. While the completion defers behind the held turn, the driver publishes a config that removes the denial — the current policy now allows write. The re-admitted completion turn still cannot write:

provider #0: launching background exec
provider #1: background exec started; holding turn 1
publishing config with write ALLOWED (deny removed)
releasing turn 1
provider #2: COMPLETION TURN arrived (marker visible); calling write
provider #3: completion-turn write result back; final text
write tool result seen by model: Tool write not found
write denied under retained producer ceiling: true
forbidden file exists: false
SCENARIO_D_RESULT=PROOF_OK

The current policy permitted write at execution time, so only the retained producer ceiling (expectedTarget.toolsAllow, captured from the producing turn's admitted tool set) explains the rejection — enforced before filesystem I/O. A lost ceiling would have created the file.

Scenario E — destination replacement settles before I/O, with no drain. A deferred wake occurrence faces a publication that also moves session.store. On a real Gateway the store move tears the queue down at reload, so the occurrence settles as queue-owner abandonment (the re-dispatch never runs); the synchronous re-dispatch rejection for a captured-destination mismatch is the other terminal shape, pinned by the producer retires before re-admission unit. Either way the occurrence is consumed before any I/O, and a later ordinary turn does not inherit it:

POST /hooks/wake -> 200 {"ok":true,"mode":"now","eventOutcome":"queued"}
publishing config with a REPLACED session store
releasing turn 1
completion turn arrived (must be false): false
gateway log: readmission rejected=false abandoned=true
wake text drained into a later ordinary turn (must be false): false
forbidden file exists: false
SCENARIO_E_RESULT=PROOF_OK

with the Gateway log showing the terminal settlement verbatim:

[reload] config change detected; evaluating reload (tools.deny, session.store)
[hooks] hook wake failed status=cancelled error="Session event was abandoned before execution"
[reload] config hot reload applied (tools.deny, session.store)

The delivery opt-out boundary is the same owner code on every attempt: deliver() checks options.deliver === false || target?.deliver === false before any transport send, the re-admission carries the captured target forward unchanged, and the capture-side invariant is pinned by captures the original store, route and producer restrictions across asynchronous lookup (deliver: false retained on the target).

Terminal-path coverage (exact-head unit, driving the real queue boundary)

The three terminal findings concern internal custody transitions with no external trigger surface — instrumenting the shipped Gateway showed the deferred occurrence's adoption is only attempted once the reply queue drains to it, so successive rejections cannot be staged deterministically through the watcher (~1s publication latency vs a sub-second re-dispatch window). These paths are pinned by exact-head unit tests that drive the real claim/consume APIs and the real queue-lifecycle callback pair (onAbandoned → onSettled), and every one fails against the previous reviewed head 1438fbb02e3:

  • consumes a canceled re-admission instead of preserving it for a later turn — cancels the original receipt while the retry is deferred; the retried occurrence settles cancelled and nothing survives for a later turn. On 1438fbb02e3 the canceled occurrence leaked into the passive queue (expected [ { …(5) } ] to deeply equal []).
  • settles terminally after the bounded re-admission budget is exhausted — three consecutive publications reject the occurrence and both retries; the third settles failed with the explicit readmission attempts exhausted error and consumes the occurrence. On 1438fbb02e3 it leaked into passive custody (same assertion diff).
  • settles terminally when the producer retires before re-admission — the producer's assertCurrent starts throwing between the policy rejection and settlement; the synchronous re-dispatch rejection consumes the occurrence and logs readmission rejected. On 1438fbb02e3 it was retained passively (same assertion diff).
  • carries submitting authority into a pre-acceptance re-admission and settles on revocation — the hook's assertAcceptanceCurrent is invoked again by the re-dispatch and, once revoked, rejects it before any new turn admission; the occurrence settles failed and consumed. On 1438fbb02e3 the retry proceeded without the ingress assertion, so the expected terminal revocation settlement never happened (test timed out).

Exact-head unit proof receipt

  • Product head SHA: 9cf97d1f275 (full SHA in the commit list above)
  • Pre-change RED baselines: 8f8a68d434a62d5977a8e7d8e51d368448a780c6^ (PR base; the silent-loss scenario) and the previous reviewed head 1438fbb02e322f4cc8bc1cfd38653b3f4ecd6391 (the four terminal-path regressions)
  • Production entry: node node_modules/vitest/vitest.mjs run --config test/vitest/vitest.config.ts src/auto-reply/reply/session-event-handoff.test.ts --maxWorkers=1
  • Canonical owner exercised: enqueueSessionEventForHost in src/auto-reply/reply/session-event-handoff.ts
  • Decision surface: occurrence custody (ownership.release() vs ownership.cancel()), the policy snapshot the re-admitted dispatch binds, and the ingress assertion carried across the pre-acceptance retry
  • Recorder/readback boundary: receipt.settled status, dispatch invocation count and its captured cfg, the session-events error log, plus peekSystemEventEntries(sessionKey)
  • Acceptance RED (base): with the production file at the pre-PR version, re-admits an accepted deferred occurrence under the current policy after a config publication fails — the receipt settles with executionStarted: false and no second dispatch happens, i.e. the occurrence was consumed, which is the silent loss
  • Acceptance RED (round-2 head 1438fbb02e3): the four terminal-path cases above fail — the canceled, exhausted, and producer-retired occurrences each leaked into the passive queue, and the revoked-ingress case proceeded without the submitting assertion
  • Acceptance GREEN: on the exact head, Tests 29 passed (29), including all seven re-admission cases
  • Terminal control: consumes a deferred occurrence the queue owner abandons, even after a config publication still drives the real onAbandoned → onSettled pair after a publication and asserts no re-admission and a consumed occurrence — abandoned work cannot be resurrected by a publication
  • Cleanup: every case runs under withOpenClawTestState isolated state/config; no production Gateway, session, token, or configuration was touched

Inspectable RED -> GREEN (unit)

RED (production file at round-2 head 1438fbb02e3, final test text, no timers or sleeps):

× session event target custody > consumes a canceled re-admission instead of preserving it for a later turn
× session event target custody > settles terminally after the bounded re-admission budget is exhausted
× session event target custody > settles terminally when the producer retires before re-admission
× session event target custody > carries submitting authority into a pre-acceptance re-admission and settles on revocation
 Tests  4 failed | 25 skipped (29)

GREEN (exact head, whole file):

 ✓ session event target custody > re-admits a pending occurrence when a policy publication races admission
 ✓ session event target custody > re-admits an accepted deferred occurrence under the current policy after a config publication
 ✓ session event target custody > consumes a deferred occurrence the queue owner abandons, even after a config publication
 ✓ session event target custody > consumes a canceled re-admission instead of preserving it for a later turn
 ✓ session event target custody > settles terminally after the bounded re-admission budget is exhausted
 ✓ session event target custody > settles terminally when the producer retires before re-admission
 ✓ session event target custody > carries submitting authority into a pre-acceptance re-admission and settles on revocation
 Test Files  1 passed (1)
      Tests  29 passed (29)

Verification

  • session-event-handoff.test.ts — 29 passed (22 existing + 7 re-admission cases); the cancellation and exhaustion cases await an owned dispatch gate resolved by the collecting mock, no polling
  • session-event-permissions.test.ts, agent-runner-execution-session-events.test.ts, followup-turn-admission.test.ts, queue/lifecycle.test.ts, queue/cleanup.session-authority.test.ts — 80 passed across the five adjacent suites (109 total with the owner file)
  • Scoped tsgo typecheck on the changed production file and the test file: clean (the dispatch mock is now typed with the real async dispatch contract, so Vitest 5 mockImplementationOnce signature checking passes)
  • oxfmt --check and oxlint -c .oxlintrc.json on the two changed files: clean (0 warnings, 0 errors)
  • Shipped-Gateway GREEN: single publication (A), /stop control (B), double-publication collapse (C), retained producer ceiling after the denial is lifted (D), destination replacement with no drain (E) — plus base RED — all on dist/ rebuilt from the exact head
Review responses (fourth pass)
  • [P3] Replace retry-count polling with an owned completion signal: fixed. The collecting dispatch now resolves an owned gate when it observes the Nth call (collectDeferredAdoptions returns whenDispatchCalled(count)); the cancellation case awaits the retry's own dispatch before cancel, and the exhaustion loop awaits each re-admission's dispatch before the next publication. No vi.waitFor remains in the file.
  • [medium] Retained authority forwarded without final-effect evidence: addressed with shipped-Gateway final effects. Scenario D proves the retained producer tool ceiling is enforced at execution: the completion turn runs while the current policy allows write, yet the write is rejected (Tool write not found) with no filesystem I/O, because the occurrence re-admitted with the producing turn's captured ceiling. Scenario E proves a replaced destination never reaches I/O — the occurrence settles terminally (queue-owner abandonment at reload on a real Gateway; the synchronous re-dispatch rejection is unit-pinned), nothing drains into a later ordinary turn (verified by driving one), and no file is created. The delivery opt-out rides the same owner boundary: deliver() consults the retained target on every attempt before any transport send.
  • [merge risk] Final-effect enforcement of producer ceiling / opt-out / destination: covered by D (ceiling), the owner-level opt-out boundary (above), and E (destination) respectively; forwarding plus enforcement is now demonstrated, not just forwarding.
Review responses (third pass)
  • [P1] Consume canceled readmissions instead of preserving them: fixed by removing preserveOccurrenceOnRejection from the re-admission. That flag is reserved for occurrences that already existed as passive notices before a failed promotion (the restart/coalesce producers); a producer-owned retry that is canceled, stopped, abandoned, or admission-refused now settles through the normal consume path. The original receipt's cancel() still forwards to the live attempt, and the canceled retry settles cancelled with the occurrence consumed (unit: consumes a canceled re-admission…, RED on 1438fbb02e3).
  • [P1] Retain producer authority when bounded readmission falls back: fixed by settling terminally instead of falling back to passive custody. Retry exhaustion and synchronous re-dispatch rejection (retired producer, moved destination, revoked ingress) consume the occurrence and log an explicit error; the generic system-event queue never receives the producer-owned occurrence, so no later ordinary turn can drain it as contract-less prompt text under its own authority (units: …budget is exhausted, …producer retires before re-admission, both RED on 1438fbb02e3).
  • [P1] Carry submitting authority until the first acceptance: fixed. If the original attempt never reached acceptance, the still-live assertAcceptanceCurrent is captured before settlement clears it and passed to the re-dispatch, whose synchronous assertion call then rejects revoked ingress before any session preparation or turn admission (unit: carries submitting authority…, RED on 1438fbb02e3 — the retry previously proceeded without the assertion).
  • [P2] Type the dispatch mock with its asynchronous call contract: fixed. The mock is declared as vi.fn<typeof dispatchInboundMessageWithRoutedChannelDispatcher> with the throwing default retained; implementations use the real parameter type and return a well-formed DispatchFromConfigResult via a tiny dispatchResult() helper. Scoped tsgo over the production file and the test file is clean.
  • [security, high] Passive fallback removes the producer's security ceiling: eliminated — the passive fallback no longer exists for producer-owned occurrences; terminal settlements consume, and the only custody-transfer path is the fresh dispatch that re-runs every destination and authority check under the current policy.
  • [security, high] Pre-acceptance retry drops ingress authority: eliminated — the retry carries the submitting invocation's live assertion until its first acceptance, so revoked ingress rejects the re-dispatch synchronously (see the revocation unit).
  • [provenance] Producer-owned occurrence settlement: preserved — fresh producer-owned occurrences still settle terminally on every terminal signal; preserveOccurrenceOnRejection remains exclusive to pre-existing passive notices (the existing releases an occurrence when Gateway restart admission refuses the producer and cold-preparation custody cases still pass unchanged).
Scope, alternatives, and land-ready notes

Scope: one owner (session-event-handoff.ts) and its regression file. The state that changes is exactly "not started AND no delivery attempted AND settled by a policy publication".

States that still fail by design (unchanged, and asserted by existing tests): a queued occurrence that was never accepted; an occurrence that already started or attempted delivery; a store replacement; agent deletion; an unresolvable agent; lost reply-run ownership; an already-settled occurrence.

Alternative considered and rejected: keeping a passive-custody fallback after budget exhaustion (this PR's second cut). Review found the generic queue carries no producer contract, so a later ordinary turn would drain the occurrence as prompt text under its own authority — and exec completions would be stranded entirely. Terminal settlement with an explicit error keeps the failure observable and the authority contract intact.

Alternative considered and rejected: pushing retry into the five producers. That spreads the same rule across 5-6 files and leaves the accepted-but-unstarted window open in the owner itself; central re-admission keeps the rule in one place.

Land-ready reasoning: the change is behavior-completing in one owner, reuses the existing dispatch and destination checks rather than adding new ones, adds no config/protocol/storage/migration surface, and ships deterministic regressions that fail on current main and on the previous reviewed head, plus a shipped-Gateway RED/GREEN proof.

🤖 Generated with Claude Code

An automatic exec completion (or restart continuation, ACP notice, or hook
event) that the active turn already accepted was destroyed when any config
publication landed before that event started: the session-event owner treated
the policy change as a failed occurrence and its settlement path cancelled the
queued occurrence, which no producer retries.

An accepted occurrence that has neither started nor attempted delivery now
refreshes its policy snapshot and continues through the existing destination
checks; a store replacement, agent deletion, or unmovable destination still
fails. The custody decision follows the same progress rule, which also covers
the producers that pass preserveOccurrenceOnRejection.
@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Re-admit unstarted session events under current policy when a configuration publication rejects their queued attempt.

Example: An exec completion waits behind an active turn while tools.deny changes to ["write"].

  • Before: The completion fails before execution and never reaches the assistant.
  • After: The completion receives a fresh dispatch under the published policy while retaining its producer restrictions.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused repair and production-owner harness support correctness, while current shipped-entry-point proof remains outstanding and the documented admission window limits completeness.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: The assistant never receives a background command's completion when configuration changes while that completion waits behind an active turn.
Reason: The repair restores documented completion behavior through the existing owner; the body acknowledges that publication during durable admission can still fail, so Related rather than Closes accurately preserves that remaining issue scope.

Regression provenance

Regression provenance — verified: source commit 753a7a57be10 by Peter Steinberger; canonical PR #167113 (blame-to-merge-commit).

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: it addresses a concrete completion-loss bug still present on current main, and inspection found no new actionable patch defect.

Priority: P1
Reviewed head: 1d327ac2821e486307c0f9dbf765f602b894c584

Before merge

  • Add real behavior proof - The current harness exercises real queue admission, durable exec identity, managed-tool write effects, policy denial, retained ceilings, and producer revocation, but embedded execution is mocked; the full body confirms that packaged-Gateway traces cover the earlier implementation only. Provide current Gateway logs or terminal output for a real exec completion deferred behind an active turn, followed by policy publication and restricted completion execution; redact credentials, IPs, phone numbers, and private endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Supply current packaged-Gateway output showing a real deferred exec completion surviving configuration reload under the expected restrictions; the supplied Gateway traces predate the restructure.
Agent review details

How this fits together

The session-event owner receives background completion notices and captured producer authority, dispatches ordinary queued reply turns, and returns acceptance and terminal settlement receipts.

flowchart TD
  A[Background exec completion] --> B[Session event owner]
  B --> C[Ordinary reply queue]
  C --> D[Current policy check]
  D -->|Publication rejection before start| B
  D -->|Authorized| E[Agent execution]
  E --> F[Result delivery and settlement]
Loading

Technical review

Best possible solution:

Keep re-admission in the session-event owner, preserving current policy, captured authority, terminal cancellation, and durable source identity.

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

Current main source establishes capture, deferral, publication rejection, and terminal occurrence removal; the report supplies matching failure logs, and the contributor reports failing-base/passing-head regressions, which were inspected but not executed during this read-only review.

Is this the best way to solve the issue?

Central fresh dispatch is appropriate because it binds current policy without duplicating retry rules across producers; the documented publication window during durable admission remains an inherited best-effort limitation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Session-event policy rejection, custody, cancellation, and dispatch identity keeps the original intent (753a7a5: Immediate notifications moved into ordinary execution while retaining original destination, permission ceiling, cancellation, and separate acceptance and settlement.)
  • Effect-time configuration validation keeps the original intent (a578746: Runtime simplification retained current tool/send policy at security effects and fixed captured destinations while removing redundant bookkeeping fences.)
  • Queued durable input admission ordering keeps the original intent (3d9637e: Queued input remains retryable until durable acceptance; subsequent setup failure produces terminal settlement without replay.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit a578746 adds src/auto-reply/reply/session-event-handoff.ts:238 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a5787464af4e; files: src/auto-reply/reply/session-event-handoff.ts)
  • Dallin Romney: Raw commit 83d5304 adds src/auto-reply/reply/followup-turn-execution.ts:118 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 83d53044a4a3; files: src/auto-reply/reply/followup-turn-execution.ts)

PR surface

Source +92, Tests +351. Total +443 across 5 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 101 9 +92
Tests 3 353 2 +351
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 454 11 +443

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #169054
Summary: The open linked issue describes the same queued-event configuration-publication failure, and this PR is its repair candidate.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: An ordinary configuration reload can discard background command completions queued behind active turns, interrupting ongoing agent work.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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 (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-12T15:07:17.355Z sha 9cf97d1 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T15:27:45.021Z sha 6db60ae :: needs maintainer review before merge. :: none
  • reviewed 2026-10-13T00:24:16.902Z sha 4bd1bfd :: needs changes before merge. :: none
  • reviewed 2026-10-13T02:00:30.723Z sha 4bd1bfd :: needs maintainer review before merge. :: none
  • reviewed 2026-10-16T03:37:35.465Z sha a01a003 :: needs real behavior proof before merge. :: [P1] Preserve retryability of the durable exec source
  • reviewed 2026-10-16T04:01:37.367Z sha e6691fe :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-16T04:28:21.505Z sha b2aa64f :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-16T04:44:29.817Z sha dc791d3 :: needs real behavior proof before merge. :: none

Reviewed October 16, 2026, 12:56 AM ET / 04:56 UTC (Revision 15).

…licy

The first cut refreshed the handoff closure config at adoption time, but the
queued run still held the pre-publication config, so a completion deferred
behind an active turn would have executed with stale tool authority, and the
unconditional custody retention also kept Stop/abandoned occurrences alive
into the next ordinary turn.

Re-slice the repair: admission keeps rejecting on a policy publication, and
settlement now re-admits an accepted, unstarted occurrence through a fresh
enqueueSessionEventForHost dispatch, so admission, execution, and delivery all
bind the current policy and the destination is re-validated. Retention is
scoped to that publication rejection only; Stop, abort, and abandonment still
consume the occurrence, and re-admission is bounded to two attempts before the
occurrence waits in passive custody for an ordinary turn.

Co-Authored-By: Claude Code <[email protected]>
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Re-sliced the repair around the review's direction (readmit under current policy, keep cancellation terminal):

  • P1 (stale queued policy): the admission guard is absolute again — a policy publication always rejects admission. Settlement now re-admits an accepted, unstarted occurrence through a fresh enqueueSessionEventForHost dispatch, which re-reads the runtime config, re-captures the destination, and re-runs every destination check, so execution authority is the current policy by construction. The new regression asserts the second dispatch's cfg carries the published tools.deny.
  • P2 (Stop/abandon retention): retention is scoped to the publication rejection only (configPublicationChanged && !signal.aborted && !abandoned); onAbandoned now marks settlement terminal. New regression: abandon-after-publication consumes the occurrence, no re-admission dispatch, nothing leaks into the next turn.
  • Security item: resolved by the same construction — the stale-authority execution path is unreachable because adoption never proceeds across a publication.
  • Re-admission is bounded (2 attempts, then passive custody for the next ordinary turn), and the producer's onAdopted commit hook carries over to the re-admitted receipt chain.

Unit coverage: 26/26 in session-event-handoff.test.ts (2 new), 80/80 across five adjacent suites, scoped tsgo + oxlint + oxfmt clean. The shipped-Gateway real-behavior proof (post-reload execution under new policy, Stop terminality) is being produced and will be added to the body.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…admission

Review of the re-admission slice found three gaps, all addressed:

- The queue lifecycle reports a policy-rejected adoption as abandonment;
  track adoption attempts so only pre-adoption abandonment (Stop, lifecycle
  cleanup) is terminal.
- The re-admission re-enqueue now carries the captured expectedTarget,
  producer liveness assertion, and explicit abort signal, so the original
  destination identity, producer permission ceiling, settings, and delivery
  opt-out all still bind the retried turn.
- receipt.cancel forwards to the live re-admission attempt, keeping exec
  completion acknowledgement connected.

Also extend retention to publications that race admission before acceptance
(observed on a real Gateway: the window between enqueue and deferral is
seconds wide under load), chaining the producer's acceptance promise to the
re-admission so the producer contract is preserved.

Co-Authored-By: Claude Code <[email protected]>
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Round 2 (1438fbb02e3) addresses all three findings plus the security flag, and the shipped-Gateway proof the first review asked for is now in the body:

  • P1 (abandonment misreport): the owner now distinguishes a policy-rejected adoption (adoption was attempted and a publication was observed) from terminal abandonment; the real onAbandoned → onSettled pair is driven in a new test.
  • P1 (producer authority): the re-admission carries expectedTarget, assertCurrent, onAdopted, deliver, createIfMissing, contextKey, deliveryContext, and abortSignal — the captured permission ceiling and live revocation survive the retry, so the authority-widening path is eliminated by construction.
  • P2 (cancellation): receipt.cancel() forwards to the live re-admission attempt; the explicit abort signal is carried.

Real-behavior proof on the packaged Gateway from this head's dist/: a hooks-wake event deferred behind a held turn is re-admitted after a tools.deny publication and its completion turn executes under the new policy (write rejected as Tool write not found, no I/O), while the PR-base build loses the event entirely (session event execution failed … Session event configuration changed, completion turn never reaches the model). A no-publication control confirms the deferred path itself is exercised. Full RED/GREEN logs in the body.

…ing authority

Canceled or abandoned re-admissions now consume the occurrence instead of
releasing it into passive custody: the re-admission no longer opts into
preserveOccurrenceOnRejection (reserved for pre-existing passive notices),
so a producer canceling the original receipt while its retry is pending
settles as cancelled with nothing resurfacing in a later ordinary turn.

Retry exhaustion and synchronous re-dispatch rejection (retired producer,
moved destination, revoked ingress) also settle terminally with a loud
error instead of parking the producer-owned occurrence in the generic
queue, where a later ordinary turn would drain it as contract-less prompt
text under its own authority.

A pre-acceptance re-admission now carries the still-live
assertAcceptanceCurrent so revoked submitting ingress rejects the retry
before any session preparation or turn admission.

Tests: type the dispatch mock with the real async dispatch contract
(Vitest 5 mockImplementationOnce signature check), and add regressions
for canceled readmissions, budget exhaustion, retired producers, and
revoked ingress.

Co-Authored-By: Claude Code <[email protected]>
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Round 3 pushed (2bfb02d057a), addressing all four findings from the last review:

  1. Canceled readmissions are now terminal. The re-admission no longer sets preserveOccurrenceOnRejection — that flag stays reserved for occurrences that already existed as passive notices before a failed promotion. Canceling the original receipt while the retry is deferred settles the retry as cancelled and consumes the occurrence; nothing resurfaces in a later ordinary turn (new regression: consumes a canceled re-admission instead of preserving it for a later turn, RED on 1438fbb02e3).
  2. Budget exhaustion and synchronous re-dispatch rejection settle terminally. No more passive-custody fallback for producer-owned occurrences: the occurrence is consumed with an explicit error log (readmission attempts exhausted / readmission rejected), so it can never drain into a later turn as contract-less prompt text (new regressions: …budget is exhausted, …producer retires before re-admission, both RED on 1438fbb02e3).
  3. Submitting authority is carried until the first acceptance. A pre-acceptance re-admission now receives the still-live assertAcceptanceCurrent; revoked ingress rejects the re-dispatch synchronously before any session preparation (new regression: carries submitting authority into a pre-acceptance re-admission and settles on revocation, RED on 1438fbb02e3).
  4. Dispatch mock typing. The mock is declared with the real async dispatch contract (vi.fn<typeof dispatchInboundMessageWithRoutedChannelDispatcher>, throwing default retained); scoped tsgo over production + test files is clean.

Evidence added to the body:

  • Shipped-Gateway GREEN re-run on the exact round-3 head (write denied under the published policy, no filesystem I/O), plus a new double-publication collapse scenario: two publications while deferred → exactly one completion turn bound to the latest policy, no duplicate execution.
  • Unit RED/GREEN: 4 failed | 25 skipped on the previous reviewed head for the four new terminal-path cases; 29 passed (29) on the exact head. Adjacent suites: 80 passed. oxfmt/oxlint clean.

One honest scoping note (also in the body): the terminal custody transitions (cancel-during-retry, exhaustion, ingress revocation) have no external trigger surface — an instrumented Gateway run showed a deferred occurrence's adoption is only attempted once the reply queue drains to it, so chaining three rejections through real config publications is not deterministically stageable (watcher latency ~1s vs sub-second re-dispatch windows). Those paths are pinned by exact-head unit tests driving the real queue-lifecycle callback pair and claim/consume APIs instead.

🤖 Generated with Claude Code

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 12, 2026
The cancellation and exhaustion re-admission cases awaited vi.waitFor on
the dispatch call count, which couples the regression to host timing and
violates the no-polling test budget. The collecting dispatch now resolves
an owned gate when it observes the Nth call, and both cases await that
signal before cancelling or publishing the next policy change.

Co-Authored-By: Claude Code <[email protected]>
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Fourth-pass update on 9cf97d1f275 — both remaining items are addressed.

[P3] Retry-count polling → owned completion signal. The collecting dispatch now resolves an owned gate when it observes the Nth call, and both cases await that signal: the cancellation case awaits the retry's own dispatch before cancelling, and the exhaustion loop awaits each re-admission's dispatch before the next publication. No vi.waitFor remains in the file; the suite is deterministic against host timing. All 29 cases pass, plus 80 across the five adjacent suites (109 total), and scoped tsgo/oxfmt/oxlint are clean.

[medium] Retained authority — final-effect evidence on the shipped Gateway (dist from the exact head; the head adds only test-file changes, production code is byte-identical to the previously reviewed revision):

  • Retained tool ceiling — scenario D: turn 1 is admitted under tools.deny: ["write"], so its background exec completion captures a ceiling without write. Mid-deferral the driver publishes a config that removes the denial, so the current policy allows write. The re-admitted completion turn still gets Tool write not found and no file is created — only the retained ceiling explains the rejection. (A lost ceiling would have written the file.)
  • Replaced destination before I/O — scenario E: the publication also moves session.store. On a real Gateway the store move tears the queue down at reload, so the occurrence settles as queue-owner abandonment (the re-dispatch never runs; the synchronous re-dispatch rejection shape is unit-pinned by producer retires before re-admission). The completion turn never executes, and a follow-up ordinary turn driven afterwards confirms the consumed occurrence does not drain as prompt text.
  • Delivery opt-out — enforced at the owner boundary on every attempt: deliver() checks the retained target's deliver === false before any transport send, and the capture-side retention is pinned by the existing captures the original store, route and producer restrictions case.

One honest scoping note: scenario E shows the real-environment terminal shape of a destination replacement is abandonment at reload, not the synchronous re-dispatch rejection — the queue is gone before a re-dispatch could run. The unit suite pins both shapes; the Gateway evidence pins the invariant that matters (no execution, no drain, no I/O).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Oct 16, 2026
@RomneyDa

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 16, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Oct 16, 2026
@RomneyDa

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Oct 16, 2026
@RomneyDa

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@RomneyDa
RomneyDa merged commit 4217e95 into openclaw:main Oct 16, 2026
126 checks passed
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Thanks for merging this, @RomneyDa — much appreciated, including the extra review rounds. Glad the background-completion fix could land after all the iterations.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
openclaw#169529)

* fix: background completion is dropped when the config changes mid-turn

An automatic exec completion (or restart continuation, ACP notice, or hook
event) that the active turn already accepted was destroyed when any config
publication landed before that event started: the session-event owner treated
the policy change as a failed occurrence and its settlement path cancelled the
queued occurrence, which no producer retries.

An accepted occurrence that has neither started nor attempted delivery now
refreshes its policy snapshot and continues through the existing destination
checks; a store replacement, agent deletion, or unmovable destination still
fails. The custody decision follows the same progress rule, which also covers
the producers that pass preserveOccurrenceOnRejection.

* fix(auto-reply): re-admit config-rejected events under the current policy

The first cut refreshed the handoff closure config at adoption time, but the
queued run still held the pre-publication config, so a completion deferred
behind an active turn would have executed with stale tool authority, and the
unconditional custody retention also kept Stop/abandoned occurrences alive
into the next ordinary turn.

Re-slice the repair: admission keeps rejecting on a policy publication, and
settlement now re-admits an accepted, unstarted occurrence through a fresh
enqueueSessionEventForHost dispatch, so admission, execution, and delivery all
bind the current policy and the destination is re-validated. Retention is
scoped to that publication rejection only; Stop, abort, and abandonment still
consume the occurrence, and re-admission is bounded to two attempts before the
occurrence waits in passive custody for an ordinary turn.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): carry producer authority and cancellation through readmission

Review of the re-admission slice found three gaps, all addressed:

- The queue lifecycle reports a policy-rejected adoption as abandonment;
  track adoption attempts so only pre-adoption abandonment (Stop, lifecycle
  cleanup) is terminal.
- The re-admission re-enqueue now carries the captured expectedTarget,
  producer liveness assertion, and explicit abort signal, so the original
  destination identity, producer permission ceiling, settings, and delivery
  opt-out all still bind the retried turn.
- receipt.cancel forwards to the live re-admission attempt, keeping exec
  completion acknowledgement connected.

Also extend retention to publications that race admission before acceptance
(observed on a real Gateway: the window between enqueue and deferral is
seconds wide under load), chaining the producer's acceptance promise to the
re-admission so the producer contract is preserved.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): settle re-admission terminal paths and carry submitting authority

Canceled or abandoned re-admissions now consume the occurrence instead of
releasing it into passive custody: the re-admission no longer opts into
preserveOccurrenceOnRejection (reserved for pre-existing passive notices),
so a producer canceling the original receipt while its retry is pending
settles as cancelled with nothing resurfacing in a later ordinary turn.

Retry exhaustion and synchronous re-dispatch rejection (retired producer,
moved destination, revoked ingress) also settle terminally with a loud
error instead of parking the producer-owned occurrence in the generic
queue, where a later ordinary turn would drain it as contract-less prompt
text under its own authority.

A pre-acceptance re-admission now carries the still-live
assertAcceptanceCurrent so revoked submitting ingress rejects the retry
before any session preparation or turn admission.

Tests: type the dispatch mock with the real async dispatch contract
(Vitest 5 mockImplementationOnce signature check), and add regressions
for canceled readmissions, budget exhaustion, retired producers, and
revoked ingress.

Co-Authored-By: Claude Code <[email protected]>

* test(auto-reply): replace retry-count polling with owned dispatch gates

The cancellation and exhaustion re-admission cases awaited vi.waitFor on
the dispatch call count, which couples the regression to host timing and
violates the no-polling test budget. The collecting dispatch now resolves
an owned gate when it observes the Nth call, and both cases await that
signal before cancelling or publishing the next policy change.

Co-Authored-By: Claude Code <[email protected]>

* test(auto-reply): widen enqueue extras to a partial override bag

The CI core-test-messaging type graph type-checks the extras parameter
against the full producer option shape, where source stays required
after the Omit; widen the helper's override bag with Partial so the
assertCurrent-only override in the producer-retirement case compiles.

Co-Authored-By: Claude Code <[email protected]>

* ci: retrigger checks after main-side fixes landed

Main fixed the stale tsgo core test shard entry and the users-github
lint regression; this empty commit re-runs CI on the unchanged tree.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): keep passive custody only before any attempt adopts the event

* fix(auto-reply): keep durable exec sources retryable across policy re-admission

Reject a stale-policy session event before durable user-turn admission
records its source claim, and treat the resulting pre-adoption abandonment
as the policy rejection it is, so the re-admission under the same
exec:<id> source is not refused as a terminal duplicate. The regression
now uses a channel-routed session and the real exec source identity.

* test(agents): prove a real exec completion survives a mid-turn policy publication

* test(auto-reply): prove re-admitted completions enforce policy, ceiling and revocation at the real write tool

* test(auto-reply): keep mock-isolation reason on one line

---------

Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Claude Code <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 20, 2026
RomneyDa added a commit that referenced this pull request Oct 20, 2026
#169529)

* fix: background completion is dropped when the config changes mid-turn

An automatic exec completion (or restart continuation, ACP notice, or hook
event) that the active turn already accepted was destroyed when any config
publication landed before that event started: the session-event owner treated
the policy change as a failed occurrence and its settlement path cancelled the
queued occurrence, which no producer retries.

An accepted occurrence that has neither started nor attempted delivery now
refreshes its policy snapshot and continues through the existing destination
checks; a store replacement, agent deletion, or unmovable destination still
fails. The custody decision follows the same progress rule, which also covers
the producers that pass preserveOccurrenceOnRejection.

* fix(auto-reply): re-admit config-rejected events under the current policy

The first cut refreshed the handoff closure config at adoption time, but the
queued run still held the pre-publication config, so a completion deferred
behind an active turn would have executed with stale tool authority, and the
unconditional custody retention also kept Stop/abandoned occurrences alive
into the next ordinary turn.

Re-slice the repair: admission keeps rejecting on a policy publication, and
settlement now re-admits an accepted, unstarted occurrence through a fresh
enqueueSessionEventForHost dispatch, so admission, execution, and delivery all
bind the current policy and the destination is re-validated. Retention is
scoped to that publication rejection only; Stop, abort, and abandonment still
consume the occurrence, and re-admission is bounded to two attempts before the
occurrence waits in passive custody for an ordinary turn.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): carry producer authority and cancellation through readmission

Review of the re-admission slice found three gaps, all addressed:

- The queue lifecycle reports a policy-rejected adoption as abandonment;
  track adoption attempts so only pre-adoption abandonment (Stop, lifecycle
  cleanup) is terminal.
- The re-admission re-enqueue now carries the captured expectedTarget,
  producer liveness assertion, and explicit abort signal, so the original
  destination identity, producer permission ceiling, settings, and delivery
  opt-out all still bind the retried turn.
- receipt.cancel forwards to the live re-admission attempt, keeping exec
  completion acknowledgement connected.

Also extend retention to publications that race admission before acceptance
(observed on a real Gateway: the window between enqueue and deferral is
seconds wide under load), chaining the producer's acceptance promise to the
re-admission so the producer contract is preserved.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): settle re-admission terminal paths and carry submitting authority

Canceled or abandoned re-admissions now consume the occurrence instead of
releasing it into passive custody: the re-admission no longer opts into
preserveOccurrenceOnRejection (reserved for pre-existing passive notices),
so a producer canceling the original receipt while its retry is pending
settles as cancelled with nothing resurfacing in a later ordinary turn.

Retry exhaustion and synchronous re-dispatch rejection (retired producer,
moved destination, revoked ingress) also settle terminally with a loud
error instead of parking the producer-owned occurrence in the generic
queue, where a later ordinary turn would drain it as contract-less prompt
text under its own authority.

A pre-acceptance re-admission now carries the still-live
assertAcceptanceCurrent so revoked submitting ingress rejects the retry
before any session preparation or turn admission.

Tests: type the dispatch mock with the real async dispatch contract
(Vitest 5 mockImplementationOnce signature check), and add regressions
for canceled readmissions, budget exhaustion, retired producers, and
revoked ingress.

Co-Authored-By: Claude Code <[email protected]>

* test(auto-reply): replace retry-count polling with owned dispatch gates

The cancellation and exhaustion re-admission cases awaited vi.waitFor on
the dispatch call count, which couples the regression to host timing and
violates the no-polling test budget. The collecting dispatch now resolves
an owned gate when it observes the Nth call, and both cases await that
signal before cancelling or publishing the next policy change.

Co-Authored-By: Claude Code <[email protected]>

* test(auto-reply): widen enqueue extras to a partial override bag

The CI core-test-messaging type graph type-checks the extras parameter
against the full producer option shape, where source stays required
after the Omit; widen the helper's override bag with Partial so the
assertCurrent-only override in the producer-retirement case compiles.

Co-Authored-By: Claude Code <[email protected]>

* ci: retrigger checks after main-side fixes landed

Main fixed the stale tsgo core test shard entry and the users-github
lint regression; this empty commit re-runs CI on the unchanged tree.

Co-Authored-By: Claude Code <[email protected]>

* fix(auto-reply): keep passive custody only before any attempt adopts the event

* fix(auto-reply): keep durable exec sources retryable across policy re-admission

Reject a stale-policy session event before durable user-turn admission
records its source claim, and treat the resulting pre-adoption abandonment
as the policy rejection it is, so the re-admission under the same
exec:<id> source is not refused as a terminal duplicate. The regression
now uses a channel-routed session and the real exec source identity.

* test(agents): prove a real exec completion survives a mid-turn policy publication

* test(auto-reply): prove re-admitted completions enforce policy, ceiling and revocation at the real write tool

* test(auto-reply): keep mock-isolation reason on one line

---------

Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Claude Code <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit 4217e95)
Co-authored-by: RomneyDa <[email protected]>
@wangmiao0668000666
wangmiao0668000666 deleted the fix/session-event-config-change-readmit branch October 28, 2026 07:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: config hot reload drops session events queued behind an active turn ("Session event configuration changed"), never retried

2 participants