Repository navigation
fix(plugins): tell hooks which turn started the command a completion run reports - #201503
Conversation
…run reports
A background exec's completion runs as its own turn (trigger "event",
sourceTool "exec"). Its hook context said nothing about the turn that
started the command, and when the session was busy the completion ran
inside another turn's trace, so a plugin could not tell who asked for
the work it was about to continue.
The host already keeps that ownership: the completion run inherits the
starting request's exec owners. Hooks now get it as
ctx.execRequestOwners, one frozen { runId, sessionKey, sessionId,
ownerDeviceId } entry per inherited owner, on agent hooks (embedded,
CLI and Codex harness) and on before_tool_call. runId is the run that
called the tool, never a later continuation. Owners a run made for its
own request are left out, and the field is absent when the run
continues no other request.
|
🦞👀 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: blocked before merge. What this changesExpose the original background command’s request owners to agent hooks and before-tool-call hooks on completion turns. Example: Run A starts
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep open for the plugin contract decision. The previous correctness finding is resolved, and no new blocking defect was found. Priority: P2 Decision needed
Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherExec request custody retains the command’s starting request through completion scheduling; shared context builders project that custody into plugin hook metadata. flowchart LR
A[Starting user turn] --> B[Exec request owner]
B --> C[Background command]
C --> D[Completion event custody]
D --> E[Completion agent turn]
E --> F[Shared hook context builders]
F --> G[Plugin hooks]
Technical reviewBest possible solution: Adopt the narrow ancestry projection through existing custody and shared hook owners if maintainers approve the public contract. Do we have a high-confidence way to reproduce the issue? Current-main source retains exec request custody but exposes no corresponding hook field; the supplied busy-session logs demonstrate why trace identity cannot substitute for it. Is this the best way to solve the issue? The revised patch uses the existing custody owner and shared context builders without adding bookkeeping or changing requester identity; only the public contract choice remains unresolved. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9dc69b2b017b. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +74, Tests +98. Total +172 across 8 files. Added test files: 0. 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. LabelsLabel changes: No label 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 HistoryReview history (1 earlier review cycle)
Reviewed November 18, 2026, 7:02 PM ET / November 19, 2026, 00:02 UTC (Revision 2). |
The Codex harness already reaches buildAgentHookContext, which adds the owners through buildAgentHookContextIdentityFields, so its separate projection and the new plugin SDK export were unused. Drop both. Tests now go through buildAgentHookContextIdentityFields, which exists on main, so the base run fails on the missing field rather than on a missing helper. The type doc says the field is ancestry only and grants no authority.
|
Thanks. I pushed 30f0284 with these changes:
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…ed its run Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
The owner read compared run ids, which the session identity ratchet forbids. A turn now records whether its owners came from another request's events. Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
Run re-entry with its own captured owners also passes owners, so the presence of owners cannot mean a continuation. The event-run owner now says so. Co-authored-by: Garry Tan <[email protected]> Co-authored-by: obviyus <[email protected]>
|
Thanks @garrytan, merged in d541d8c. Hooks on a completion run now name the turn that started the command. Before landing I made three changes, all described in the PR body:
I checked it on an isolated Gateway with two paired devices; the scenario table is in the body. |
…run reports (openclaw#201503) Related: openclaw#200664, openclaw#152204 ## What Problem This Solves When an `exec` call goes to the background (`yieldMs`), its completion later runs as its own agent turn, with `trigger: "event"` and `inputProvenance: { kind: "internal_system", sourceTool: "exec" }`. Plugin hooks on that run have no field naming the turn that started the command. `senderId`, `chatId` and `requesterDeviceId` (openclaw#200664) are set only for `trigger: "user"`, so they're absent here. The trace can't be used to recover the starter either. When the session is busy, the completion runs after the turn that was running when the command finished, and its trace is that turn's trace. A plugin that follows the trace gets the wrong turn. ## User Impact A plugin that applies a rule per requester, such as gating a tool call on who asked for it, has two bad options on a completion run today. It can treat every completion as unknown, which blocks legitimate follow-up work, or it can guess, which can attribute the work to whoever happened to be talking at the time. With this change, hooks on that run get `ctx.execRequestOwners`, which names the turn that started the command. Nothing changes for plugins that don't read the field. ## Why This Change Was Made The host already keeps this ownership. The completion run inherits the starting request's exec owners in `src/infra/exec-request-context.ts`. This change exposes a read-only copy of those records on the hook context and adds no new bookkeeping: - `readInheritedExecRequestOwners(runId)` returns one frozen `{ runId, sessionKey?, sessionId?, ownerDeviceId? }` entry per inherited owner. `runId` is the run that called the tool, not a later continuation. Owners the run created for its own request are left out. The function returns `undefined`, never an empty array, when the run continues no other request or the run id isn't the current run. - `buildAgentHookContextIdentityFields` takes `runId` and always adds the field, whatever the trigger. So every agent hook context built through it gets the field without per-builder edits. The CLI runner's prepared hook context passes it along. - The Codex harness needs no change of its own: its prompt, lifecycle and compaction hooks go through the shared `buildAgentHookContext`, which calls the same identity builder, and its dynamic tools go through the shared `before_tool_call` wrapper. No plugin SDK export is added. - `before_tool_call` gets the same field through `PluginHookToolContext`. - The field comes only from the host's exec records, and the array and its entries are frozen. It is ancestry metadata only: the type doc says it grants the run none of the starter's authority or approvals. ## Evidence Head: 30f0284. The first commit adds the field. The second follows the first review: it removes the Codex projection and the SDK export, and routes the tests through the shared builder. **Real model, real exec, busy session.** I built this head's package with `node scripts/package-openclaw-for-docker.mjs` (`OpenClaw 2026.11.5 (30f0284)`) and ran a loopback gateway with `openai/gpt-5.4-mini`. A small plugin logs each hook's `ctx`, and a paired-device operator client sends `chat.send`. Device ids are masked to their last 4 characters. 1. Run A: "Use the exec tool to run exactly: sleep 30; echo a-done -- set yieldMs to 1000 so it keeps running in the background…". The model called `exec`, the command yielded, and run A ended. 2. Run B, sent once A had ended: "Use the exec tool to run exactly: sleep 40; echo b-done -- in the foreground…". This kept the session busy while A's command finished. 3. When B ended, the completion ran as its own turn (`trigger: "event"`, `sourceTool: "exec"`): ``` 23:50:03 before_agent_run real-b-… user owners=ABSENT 23:50:47 agent_end real-b-… user owners=ABSENT 23:50:48 before_prompt_build 528f2655… event exec owners=[{"runId":"real-a-…","sessionKey":"agent:main:real-busy2","sessionId":"70c717a4","ownerDeviceId":"..73f0"}] 23:50:48 before_agent_run 528f2655… event exec owners=[same] 23:50:52 before_agent_finalize 528f2655… event owners=[same] 23:50:52 agent_end 528f2655… event owners=[same] trace ids: run A …595ca, run B …bbb48, completion …bbb48 ``` The completion's trace is run B's, and `execRequestOwners` names run A, the run that started the command. The field is absent on A's and B's own hooks. **Mock model, more cases** (first head 318096f; the agent hook path is the same at this head). With an OpenAI-shaped mock that calls `exec` with `yieldMs: 1000`: - idle: the completion names its starter on before_prompt_build, before_agent_run, before_tool_call, before_agent_finalize and agent_end; - busy: same result as the real-model run; - two overlapping execs: two completion runs, each naming its own starter. **Unit tests** (`src/plugins/hook-agent-context.test.ts`, 5 new). They cover idle, two overlapping execs, the busy-session case, before_tool_call matching the agent hooks, and absence outside a run. - On base fc26a47 with the source changes reverted, 5 fail. The idle, overlap and busy tests fail on the missing field through the existing `buildAgentHookContextIdentityFields` (for example `expected {} to deeply equal { execRequestOwners: [ … ] }`). The other two fail because the tool-context helper is missing. - On this head, 11 pass. **Checks on this head:** - `pnpm tsgo:core` and `pnpm tsgo:extensions` pass. - `oxlint` and `oxfmt --check` are clean on the changed files. - `check:test-lines-ratchet`, `check:max-lines-ratchet`, `check:assertion-safety`, `lint:tmp:export-name-collisions` and `lint:tmp:tsgo-core-boundary` pass. - `pnpm plugin-sdk:api:diff --base fc26a47 --head HEAD` exits 0 (digest `efb88881`). The change is one optional context field, with no new function export. - On the first head, every other `lint:tmp:*` script passed, along with `lint:kysely`, `check:database-worker-ratchet`, `check:test-timeout-race-ratchet`, `check:temp-path-guardrails`, `check:database-first-legacy-stores` and `git diff --check`. The second commit touches only the four files above. ## Accepted edge cases - `after_tool_call` and hooks outside agent runs (`reply_payload_sending`, `message_sending`, `before_dispatch`) don't carry the field. The real run shows this. - `ownerDeviceId` is left out when the starting connection had no verified paired device, for example a shared-token client with no device identity. - One completion run that drains two owners returns two entries. The unit test covers this, but in the real run the two overlapping execs completed as two separate runs. - The subagent-session heartbeat wake (trigger `heartbeat`, `sourceTool: "exec"`), the CLI runner and the Codex harness reach the same shared builders and are covered by types and unit tests. I didn't run them end to end. ## Maintainer fix Three repairs before landing: 1. **Wrong device after steering.** If device B steered the run that started a command, the completion still reported `ownerDeviceId: A`. The existing openclaw#200664 projection in `src/plugins/hook-requester-device.ts` now covers `execRequestOwners` too: an owner's device is dropped once its run held input from another source. One owner, no second store. Regression test: `message-injection-requester-device.test.ts` fails at `30f0284` and passes after. 2. **Run-id comparisons.** `readInheritedExecRequestOwners` compared run ids, which the session-identity ratchet forbids (`exec-request-context.ts` 28 > 24). The turn now records `continues`, which the event-run owner (`runAgentTurnWithOutcome`) sets. 3. **Own owners reported as ancestry.** A run that re-enters with its own captured owners also passes owners. With the flag tied to the presence of owners, every user run named itself. The flag is now set only at the event-run call site. Regression test in `hook-agent-context.test.ts`: fails at `fa32ed0` and passes after. **Gateway E2E** (dist build at `fb2cbaf`, two paired devices A and B, probe plugin logging `ctx.execRequestOwners`, real `openai/gpt-5.4-mini` turns): | Scenario | Completion run sees | |---|---| | A starts `sleep 15` in the background, session idle | `[{runId: A's run, ownerDeviceId: A}]` | | A starts `sleep 30` in the background, B runs a 25 s turn, completion lands after B | `[{runId: A's run, ownerDeviceId: A}]` (not B's run) | | B steers A's run, and that run starts the background command | `[{runId: A's run}]`, device withheld | | Ordinary user runs (A and B) | no `execRequestOwners` | Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #200664, #152204
What Problem This Solves
When an
execcall goes to the background (yieldMs), its completion later runs as its own agent turn, withtrigger: "event"andinputProvenance: { kind: "internal_system", sourceTool: "exec" }. Plugin hooks on that run have no field naming the turn that started the command.senderId,chatIdandrequesterDeviceId(#200664) are set only fortrigger: "user", so they're absent here.The trace can't be used to recover the starter either. When the session is busy, the completion runs after the turn that was running when the command finished, and its trace is that turn's trace. A plugin that follows the trace gets the wrong turn.
User Impact
A plugin that applies a rule per requester, such as gating a tool call on who asked for it, has two bad options on a completion run today. It can treat every completion as unknown, which blocks legitimate follow-up work, or it can guess, which can attribute the work to whoever happened to be talking at the time.
With this change, hooks on that run get
ctx.execRequestOwners, which names the turn that started the command. Nothing changes for plugins that don't read the field.Why This Change Was Made
The host already keeps this ownership. The completion run inherits the starting request's exec owners in
src/infra/exec-request-context.ts. This change exposes a read-only copy of those records on the hook context and adds no new bookkeeping:readInheritedExecRequestOwners(runId)returns one frozen{ runId, sessionKey?, sessionId?, ownerDeviceId? }entry per inherited owner.runIdis the run that called the tool, not a later continuation. Owners the run created for its own request are left out. The function returnsundefined, never an empty array, when the run continues no other request or the run id isn't the current run.buildAgentHookContextIdentityFieldstakesrunIdand always adds the field, whatever the trigger. So every agent hook context built through it gets the field without per-builder edits. The CLI runner's prepared hook context passes it along.buildAgentHookContext, which calls the same identity builder, and its dynamic tools go through the sharedbefore_tool_callwrapper. No plugin SDK export is added.before_tool_callgets the same field throughPluginHookToolContext.Evidence
Head: 30f0284. The first commit adds the field. The second follows the first review: it removes the Codex projection and the SDK export, and routes the tests through the shared builder.
Real model, real exec, busy session. I built this head's package with
node scripts/package-openclaw-for-docker.mjs(OpenClaw 2026.11.5 (30f0284)) and ran a loopback gateway withopenai/gpt-5.4-mini. A small plugin logs each hook'sctx, and a paired-device operator client sendschat.send. Device ids are masked to their last 4 characters.exec, the command yielded, and run A ended.trigger: "event",sourceTool: "exec"):The completion's trace is run B's, and
execRequestOwnersnames run A, the run that started the command. The field is absent on A's and B's own hooks.Mock model, more cases (first head 318096f; the agent hook path is the same at this head). With an OpenAI-shaped mock that calls
execwithyieldMs: 1000:Unit tests (
src/plugins/hook-agent-context.test.ts, 5 new). They cover idle, two overlapping execs, the busy-session case, before_tool_call matching the agent hooks, and absence outside a run.buildAgentHookContextIdentityFields(for exampleexpected {} to deeply equal { execRequestOwners: [ … ] }). The other two fail because the tool-context helper is missing.Checks on this head:
pnpm tsgo:coreandpnpm tsgo:extensionspass.oxlintandoxfmt --checkare clean on the changed files.check:test-lines-ratchet,check:max-lines-ratchet,check:assertion-safety,lint:tmp:export-name-collisionsandlint:tmp:tsgo-core-boundarypass.pnpm plugin-sdk:api:diff --base a4be1ae09e3 --head HEADexits 0 (digestefb88881). The change is one optional context field, with no new function export.lint:tmp:*script passed, along withlint:kysely,check:database-worker-ratchet,check:test-timeout-race-ratchet,check:temp-path-guardrails,check:database-first-legacy-storesandgit diff --check. The second commit touches only the four files above.Accepted edge cases
after_tool_calland hooks outside agent runs (reply_payload_sending,message_sending,before_dispatch) don't carry the field. The real run shows this.ownerDeviceIdis left out when the starting connection had no verified paired device, for example a shared-token client with no device identity.heartbeat,sourceTool: "exec"), the CLI runner and the Codex harness reach the same shared builders and are covered by types and unit tests. I didn't run them end to end.Maintainer fix
Three repairs before landing:
ownerDeviceId: A. The existing fix(plugins): let hooks see the verified paired device that sent a turn #200664 projection insrc/plugins/hook-requester-device.tsnow coversexecRequestOwnerstoo: an owner's device is dropped once its run held input from another source. One owner, no second store. Regression test:message-injection-requester-device.test.tsfails at30f0284and passes after.readInheritedExecRequestOwnerscompared run ids, which the session-identity ratchet forbids (exec-request-context.ts28 > 24). The turn now recordscontinues, which the event-run owner (runAgentTurnWithOutcome) sets.hook-agent-context.test.ts: fails atfa32ed0and passes after.Gateway E2E (dist build at
fb2cbaf, two paired devices A and B, probe plugin loggingctx.execRequestOwners, realopenai/gpt-5.4-miniturns):sleep 15in the background, session idle[{runId: A's run, ownerDeviceId: A}]sleep 30in the background, B runs a 25 s turn, completion lands after B[{runId: A's run, ownerDeviceId: A}](not B's run)[{runId: A's run}], device withheldexecRequestOwners