Repository navigation
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesRe-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"].
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial Regression provenanceRegression provenance — verified: source 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 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +92, Tests +351. Total +443 across 5 files. Added test files: 1. View PR surface stats
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (14 earlier review cycles; latest 8 shown)
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]>
|
@clawsweeper re-review Re-sliced the repair around the review's direction (readmit under current policy, keep cancellation terminal):
Unit coverage: 26/26 in |
|
🦞👀 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]>
|
Round 2 (
Real-behavior proof on the packaged Gateway from this head's |
…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]>
|
Round 3 pushed (
Evidence added to the body:
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 |
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]>
|
Fourth-pass update on [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 [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):
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 re-review |
|
🦞👀 Re-review progress:
|
…ng and revocation at the real write tool
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Thanks for merging this, @RomneyDa — much appreciated, including the extra review rounds. Glad the background-completion fix could land after all the iterations. |
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]>
Co-authored-by: RomneyDa <[email protected]>
#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]>
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.orderrotation) lands before it starts. The queued follow-up run holds the config captured at enqueue, the session-event owner rejects it withSession 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.denyapplies). 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.tsis 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 throughenqueueSessionEventForHost, 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 submittingassertAcceptanceCurrent. The original receipt'scancel()/settledforward 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-startassertSourceCurrent, so the drop still reproduced on main (now at execution start instead ofonAdopted). The branch now:mainand ports the re-admission ontoassertEffectCurrent;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);preserveOccurrenceOnRejection) only until some attempt has adopted the occurrence (autoreview P2);followup-turn-execution.tsnow asserts the event'sinternalEventExecution.assertCurrentbeforerecovery.admitUserTurn, so a stale-policy attempt never records theexec:<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;Production:
src/auto-reply/reply/session-event-handoff.ts(~+105/-9) and a 3-line pre-admission assertion infollowup-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 settlesfailedwith 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.tsdrives the real dispatcher, followup queue, durable restart-recovery admission and session store (onlyrunEmbeddedAgentis 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 withnotifyOnExit, the real exec-notify producer enqueues its completion (assertedsourceTurnId: 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).session-event-handoff.ts+followup-turn-execution.tsswapped in: fails (completion never runs).completed, executionStarted: true, the completion turn's prompt contains the child's output, and it bindsconfig.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.tsnow runs five scenarios on a channel-routed session withsourceTurnId: exec:<id>. In the re-admitted completion turn the synthetic model builds the real managed tool surface (createAgentHarnessHostCapabilities+buildEmbeddedAttemptToolRunContext+resolveEmbeddedAttemptToolConstructionPlan, same path assession-event-permissions) and calls the realwritetool against the workspace; the assertion is on the file on disk:published-denytools.deny: ["write"]retained-ceilingtools.deny: ["exec"](write allowed by current policy); captured targettoolsAllow: ["read"]allow-controltools.deny: ["exec"], no ceilingrevoked-producerassertCurrentthrows after publicationfailed, model never invoked, no filepublication-stormfailedafter the bounded budget, no fileAll 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 settlesfailed; the same test withoutsourceTurnIdpasses, isolating the durable source claim. Reverting either the pre-admission assertion or the abandonment classification fails the test.RED on main (
origin/mainproduction file, same test):storm: falsefails — 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 bindsconfig.tools.deny === ["write"]; no system events remain.Storm (
storm: true): every liveness check publishes a distinct policy; the completion settlesfailed, 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:coreclean; 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 siblingsession-event-permissionscases). Lives in its own file becausesession-event-permissions.test.tsis at the line-cap ratchet; registered in the database-worker core paths (needs the host SQLite broker).CI: the earlier
checks-node-changed-1red wassrc/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.denyrewrite, 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
execcompletion (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, anauth.orderrotation — 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
assertOwnerCurrentinsrc/auto-reply/reply/session-event-handoff.tscompared 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 atools.denythe 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 callsenqueueSessionEventForHostagain 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 liveassertCurrentrevocation callback, the explicitabortSignal, the durable producer'sonAdoptedcommit hook, and — while the original attempt never reached acceptance — the submitting invocation's liveassertAcceptanceCurrent, 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'scancel()forwards to the live re-admission attempt, and itssettledpromise 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:
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.No producer retry loops, validator, option, config value, or persistence policy are added.
Production LOC is
+137/-8across one file.Classification:
behavior-completingEvidence
Real shipped-Gateway proof (RED → GREEN)
Driver:
proof-169529.mjs(linked below) runs the packaged Gateway from this PR'sdist/with a stateful mock OpenAI Responses provider. Flow: an ordinary turn is held open by the provider gate → aPOST /hooks/wakeevent (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 awritetool call, so the tool result shows exactly which policy the executing turn bound.GREEN (dist rebuilt from the exact head; the current head
9cf97d1f275adds only test-file changes on top of2bfb02d057a, production code is byte-identical):The stale-policy adoption was rejected, the occurrence was re-admitted through a fresh dispatch, and the completion turn executed under the published policy:
writewas gone from the toolset (Tool write not found) and no filesystem I/O happened.RED (same tree with
session-event-handoff.tsat the PR-base version, dist rebuilt):and the base Gateway log shows the silent loss verbatim:
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: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:Driver script:
proof-169529.mjsat 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: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 theproducer retires before re-admissionunit. Either way the occurrence is consumed before any I/O, and a later ordinary turn does not inherit it:with the Gateway log showing the terminal settlement verbatim:
The delivery opt-out boundary is the same owner code on every attempt:
deliver()checksoptions.deliver === false || target?.deliver === falsebefore any transport send, the re-admission carries the captured target forward unchanged, and the capture-side invariant is pinned bycaptures the original store, route and producer restrictions across asynchronous lookup(deliver: falseretained 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 head1438fbb02e3: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 settlescancelledand nothing survives for a later turn. On1438fbb02e3the 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 settlesfailedwith the explicitreadmission attempts exhaustederror and consumes the occurrence. On1438fbb02e3it leaked into passive custody (same assertion diff).settles terminally when the producer retires before re-admission— the producer'sassertCurrentstarts throwing between the policy rejection and settlement; the synchronous re-dispatch rejection consumes the occurrence and logsreadmission rejected. On1438fbb02e3it was retained passively (same assertion diff).carries submitting authority into a pre-acceptance re-admission and settles on revocation— the hook'sassertAcceptanceCurrentis invoked again by the re-dispatch and, once revoked, rejects it before any new turn admission; the occurrence settlesfailedand consumed. On1438fbb02e3the retry proceeded without the ingress assertion, so the expected terminal revocation settlement never happened (test timed out).Exact-head unit proof receipt
9cf97d1f275(full SHA in the commit list above)8f8a68d434a62d5977a8e7d8e51d368448a780c6^(PR base; the silent-loss scenario) and the previous reviewed head1438fbb02e322f4cc8bc1cfd38653b3f4ecd6391(the four terminal-path regressions)node node_modules/vitest/vitest.mjs run --config test/vitest/vitest.config.ts src/auto-reply/reply/session-event-handoff.test.ts --maxWorkers=1enqueueSessionEventForHostinsrc/auto-reply/reply/session-event-handoff.tsownership.release()vsownership.cancel()), the policy snapshot the re-admitted dispatch binds, and the ingress assertion carried across the pre-acceptance retryreceipt.settledstatus, dispatch invocation count and its capturedcfg, thesession-eventserror log, pluspeekSystemEventEntries(sessionKey)re-admits an accepted deferred occurrence under the current policy after a config publicationfails — the receipt settles withexecutionStarted: falseand no second dispatch happens, i.e. the occurrence was consumed, which is the silent loss1438fbb02e3): 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 assertionTests 29 passed (29), including all seven re-admission casesconsumes a deferred occurrence the queue owner abandons, even after a config publicationstill drives the realonAbandoned→onSettledpair after a publication and asserts no re-admission and a consumed occurrence — abandoned work cannot be resurrected by a publicationwithOpenClawTestStateisolated state/config; no production Gateway, session, token, or configuration was touchedInspectable RED -> GREEN (unit)
RED (production file at round-2 head
1438fbb02e3, final test text, no timers or sleeps):GREEN (exact head, whole file):
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 pollingsession-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)tsgotypecheck on the changed production file and the test file: clean (the dispatch mock is now typed with the real async dispatch contract, so Vitest 5mockImplementationOncesignature checking passes)oxfmt --checkandoxlint -c .oxlintrc.jsonon the two changed files: clean (0 warnings, 0 errors)/stopcontrol (B), double-publication collapse (C), retained producer ceiling after the denial is lifted (D), destination replacement with no drain (E) — plus base RED — all ondist/rebuilt from the exact headReview responses (fourth pass)
collectDeferredAdoptionsreturnswhenDispatchCalled(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. Novi.waitForremains in the file.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.Review responses (third pass)
preserveOccurrenceOnRejectionfrom 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'scancel()still forwards to the live attempt, and the canceled retry settlescancelledwith the occurrence consumed (unit:consumes a canceled re-admission…, RED on1438fbb02e3).…budget is exhausted,…producer retires before re-admission, both RED on1438fbb02e3).assertAcceptanceCurrentis 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 on1438fbb02e3— the retry previously proceeded without the assertion).vi.fn<typeof dispatchInboundMessageWithRoutedChannelDispatcher>with the throwing default retained; implementations use the real parameter type and return a well-formedDispatchFromConfigResultvia a tinydispatchResult()helper. Scopedtsgoover the production file and the test file is clean.preserveOccurrenceOnRejectionremains exclusive to pre-existing passive notices (the existingreleases an occurrence when Gateway restart admission refuses the producerand 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