Repository navigation
Conversation
Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in #197990. Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@clawsweeper re-review Please review final head |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR gives subagent completion hooks fresh plugin admission after the originating turn ends. Example: A completion hook selects Discord channel:777 and thread 777 after the requester turn closes.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR: it repairs a current subagent hook admission failure in the shared dispatcher, and no introduced correctness or security defect was found. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherSubagent lifecycle and announcement code send completion events through the shared hook runner, which invokes registered plugin handlers and returns completion processing or delivery overrides. flowchart TD
A[Subagent completes] --> B[Lifecycle or announcement owner]
B --> C[Shared hook dispatcher]
C --> D[Leave originating invocation scope]
D --> E[Exact plugin instance admission]
E --> F[Completion handler and delivery override]
Technical reviewBest possible solution: Keep the narrow shared-dispatch repair, reusing ordinary exact-instance admission and preserving explicit closed-callback rejection. Do we have a high-confidence way to reproduce the issue? Current source establishes the closed-scope admission path and routing fallback, supported by the matching reporter logs and supplied base-red/head-green regressions; this read-only review ran no target code. Is this the best way to solve the issue? The patch fixes the shared admission boundary with a reused scope-exit helper rather than weakening guards or adding consumer catches, and each added regression protects a distinct lifecycle or routing failure. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2e77b6be8b67. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +8, Tests +162, Docs +3, Other +144. Total +317 across 7 files. Added test files: 2. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
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 Reviewed November 14, 2026, 3:12 AM ET / 08:12 UTC. |
|
Merged via squash.
|
…penclaw#198732) * fix(subagents): preserve completion hooks after the requester turn ends Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in openclaw#197990. Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation. * fix(plugins): share post-turn scope exit below the agent layer
… refusing late calls (#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example #196700, #196750, #197658, #197990, #198652, #198732 and #198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - #198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - #198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - #197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - #196700: activity recap scope exit in `session-activity-summaries.ts` - #196750: session-event delivery scope exit - #197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - #198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5d5ca9d2ba8c`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the #197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
… refusing late calls (openclaw#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example openclaw#196700, openclaw#196750, openclaw#197658, openclaw#197990, openclaw#198652, openclaw#198732 and openclaw#198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - openclaw#198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - openclaw#198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - openclaw#197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - openclaw#196700: activity recap scope exit in `session-activity-summaries.ts` - openclaw#196750: session-event delivery scope exit - openclaw#197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - openclaw#198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (openclaw#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5a640d63290f`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the openclaw#197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
What Problem This Solves
Fixes subagent completion hooks failing with “Plugin invocation scope is closed” after the requester turn finishes. If
subagent_delivery_targetfails, completion routing can fall back to the requester channel instead of honoring the hook-selected Discord thread.User Impact
Completion hooks can finish their work and preserve the selected delivery target after a turn ends. This routing loss is reproduced synthetically; no production misdelivery is asserted. No configuration or migration is needed. Removed or replaced plugin instances and callbacks explicitly bound to a finished turn remain unavailable.
Why This Change Was Made
The shared hook dispatcher now leaves the originating turn's plugin invocation scope before invoking
subagent_endedorsubagent_delivery_target. It shares the existing two plugin-context exits with the prepared-runtime detach helper and uses ordinary plugin-instance admission, which checks the exact instance and releases its call lease on settlement. There are no consumer catches or changes to the closed-scope guard.The separate
agent_endrepair in #197990 stays intact: it hydrates and admits the hook before closing the turn. Existing managed context-engine cleanup already acquires independent custody and its closed-caller regression passes unchanged. Runtime production growth is eight lines for the shared selector and extracted plugin-layer scope exit; no additional scope implementation, cache, or registry scan is introduced.Evidence
The two hook regressions and completion-origin regression fail on main parent
662a2e2a743bad9e2aac2c51aa1763247791cd23. The latter expectschannel:777/thread777and instead receiveschannel:123without the thread. The candidate passes both and rejects removed/quiesced instances and explicitly closed callbacks.51 focused tests passed after the dependency correction (177.26s wrapper, including compilation); 16 unchanged sibling tests cover hook replacement, invocation scopes, and existing subagent hook behavior. This is owner-boundary proof with synthetic registrations and fixed storage results, not a live Discord send or model/Gateway run.
Rerunnable owner workload:
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/hook-post-turn-measure.ts <synthetic-fixture-root> <label> timing(repeat withallocation). Acceptance was successful post-turn dispatch with healthy-path cost compared against A/A controls. Baseline A/A controls use the exact main parent. The final candidate B/B repeats use the same typed fixture after the architecture correction. The initial runs were interleaved B/A/B/A; final B/B runs reuse those baseline controls. Final host load was higher (48–50 versus 15–21), so the sub-microsecond cost comparison is approximate. Each run uses 40 managed plugins, 10,000 session keys, 10,000 warmups, then five samples of 20,000 hooks. Allocation is sampled separately at 1,024-byte intervals.Closed-turn success changes from 0/20,000 to 20,000/20,000 hooks, with errors falling to zero. Fresh independent admission costs about 0.7–0.8 µs and 1.2 KB per healthy open-turn hook; the closed baseline did no handler work, so its lower allocation is not equivalent useful work. A CPU profile attributes dispatch work to existing scope/registry binding, lease diagnostics, and promise settlement.
The synthetic fixture has a 35.13 GiB database, 10,000 populated sessions, one million events, and 62,000 workspace files / 1.116 GB. The dispatch owner performs zero storage I/O; only fixture metadata/stat are read during setup. These are local APFS dispatch measurements, not btrfs or database-throughput evidence.
Codex autoreview on the corrected, staged candidate is scoped-clean at P0–P2 with zero findings. The first
pnpm check:changedrun found fixture type errors (corrected; both affected typechecks now pass) and two unrelated production dead exports. Both remaining dead exports reproduce on the exact main parent662a2e2a743bad9e2aac2c51aa1763247791cd23:normalizeDiscoveredAgentModellost its consumer in730ce41827c4/ #198591;MEMBER_ROLE_PRESETSwas introduced unused in4fc7acf90a73/ #197739. These are main regressions, not ignored noise. All other changed checks pass. The parent replay initially lacked UI dependency links; the corrected replay reached the scan and reproduced exactly those two findings. The final 51-test rerun includes all nine new regressions. Exact-head CI run 43573345069 is green; final-head ClawSweeper review has zero findings and no before-merge items.The first CI head failed the Madge architecture check: importing the full prepared-runtime helper closed a type dependency cycle through the loader and hooks. Commit
6436fb1b8054moves the shared two-context exit into the plugin layer and delegates from both callers. Madge now reports zero cycles locally; all 51 focused tests pass. The secondpnpm check:changedcompleted: all gates pass except the two inherited production exports and the formatting finding whose correction replay passes. Both script and full-tree dead-export scans are clean. Native preparation completed at6436fb1b8054, and exact-head CI is green. Final-head ClawSweeper review has zero findings and no before-merge items. Landed via nativescripts/pras1c1814a0bf7808b046d6170f6feaa6c540830408; ancestry onorigin/mainverified.