Skip to content

fix(plugins): preserve mutable hook context - #89002

Closed
wyf027 wants to merge 2 commits into
openclaw:mainfrom
wyf027:leno23/fix-register-hook-context-75245
Closed

wyf027 wants to merge 2 commits into
openclaw:mainfrom
wyf027:leno23/fix-register-hook-context-75245

Conversation

@wyf027

@wyf027 wyf027 commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Preserve the original mutable hook context object when plugin registerHook handlers run.
  • Temporarily expose pluginConfig to each handler and restore/remove it afterward so config does not leak onto the shared event context.
  • Add regression coverage for both bootstrap context replacement and back-to-back hook handlers: the first handler mutates the shared context with config present, and the second handler sees that mutation without seeing the first handler's pluginConfig.

Test Plan

  • RED: temporarily restored src/plugins/registry.ts to upstream/main, then ran node scripts/run-vitest.mjs src/plugins/loader.test.ts --testNamePattern "runs consecutive plugin hook handlers" --reporter dot → failed as expected because the second handler saw AGENTS.md / missing-note instead of the first handler's context mutation.
  • GREEN: node scripts/run-vitest.mjs src/plugins/loader.test.ts --testNamePattern "runs consecutive plugin hook handlers|preserves plugin hook context mutations|injects plugin config" --reporter dot → 1 test file passed; 3 tests passed, 148 skipped.
  • GREEN: node_modules/.bin/tsx /tmp/proof-pr89002-hook-context.ts → real plugin-loader proof passed.
  • GREEN: node_modules/.bin/oxfmt --write src/plugins/loader.test.ts and git diff --staged --check → passed before commit.
  • BLOCKED: pnpm check:changed --staged could not complete locally because pnpm attempted dependency hydration/removal in this worktree and aborted in non-TTY mode with ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY. Earlier direct pnpm install --frozen-lockfile also failed on the known lockfile/dependency hydration issue for @lydell/node-pty-darwin-arm64.

Real behavior proof

Behavior addressed: plugin hook handlers could mutate the context object they received, but current main's registry wrapper shallow-copied evt.context, so later core code and later handlers did not observe context replacements such as bootstrapFiles; pluginConfig still needs to be visible only to the owning handler and cleaned before the next handler.

Real environment tested: local PR worktree on macOS 15.5; Node v22.22.1 via tsx; two temporary real plugin directories each containing openclaw.plugin.json and a CJS entrypoint were loaded through loadOpenClawPlugins with the normal plugin loader path, then agent:bootstrap was triggered through triggerInternalHook.

Exact steps or command run after this patch: node_modules/.bin/tsx /tmp/proof-pr89002-hook-context.ts

Evidence after fix:

PR #89002 real plugin-loader proof
tempRoot=/var/folders/xk/3knfjhwn1yb6hf9jw4853pmc0000gn/T/openclaw-pr89002-real-plugin-KCTpCx
messages=["firstConfig=visible-to-first-real-plugin","secondConfig=none","bootstrapFile=REAL-FIRST.md","note=mutation-from-first-real-plugin"]
context={"bootstrapFiles":[{"name":"REAL-FIRST.md","content":"from-first-real-plugin"}],"note":"mutation-from-first-real-plugin"}
pluginConfigPresent=false
PASS: real plugin hooks loaded through loadOpenClawPlugins share context mutations while pluginConfig is cleaned before the next handler.

Observed result after fix: the first real plugin saw its own config and replaced event.context.bootstrapFiles; the second real plugin saw no pluginConfig leakage but did see REAL-FIRST.md and mutation-from-first-real-plugin; the final shared event context retained the mutation and had pluginConfigPresent=false.

What was not tested: the full pnpm check:changed --staged gate was not completed locally because pnpm attempted dependency hydration/removal and aborted in non-TTY mode; focused Vitest coverage, formatter/check-diff sanity, and the real plugin-loader proof above were run instead.

Risk/Notes

  • The wrapper restores/removes pluginConfig in a finally block, so existing context config state is preserved even if a handler throws.
  • Scope is limited to plugin internal hook handler invocation; hook registration/unregistration logic is unchanged.
  • This intentionally preserves the shared mutable context contract used by agent:bootstrap while keeping per-handler config isolated.

Closes #75245

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 1, 2026
@clawsweeper

clawsweeper Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 15, 2026, 6:57 AM ET / 10:57 UTC.

Summary
The PR changes the plugin registry hook wrapper to reuse the incoming event context while temporarily injecting/restoring pluginConfig, and adds loader regression tests for context mutation propagation and config cleanup.

PR surface: Source +11, Tests +162. Total +173 across 2 files.

Reproducibility: yes. Source inspection gives a high-confidence path: current main clones evt.context, while applyBootstrapHookOverrides reads bootstrapFiles from the original event after sequential hook dispatch.

Review metrics: 1 noteworthy metric.

  • Plugin hook contract behavior: 1 observable behavior changed. The PR changes whether external api.registerHook handlers receive the original mutable context object or a clone, which is compatibility-relevant before merge.

Stored data model
Persistent data-model change detected: persistent cache schema: src/plugins/loader.test.ts, serialized state: src/plugins/loader.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] The PR intentionally changes the observable context object identity and mutation propagation seen by external api.registerHook handlers; maintainers should accept that mutable-context compatibility direction before merge.
  • [P1] The PR is currently draft, so it should not land until the contributor marks it ready for review or maintainers explicitly adopt the branch.

Maintainer options:

  1. Accept mutable context with cleanup (recommended)
    Merge after maintainers accept that registered hook handlers may mutate the shared event context while pluginConfig remains per-handler and restored in finally.
  2. Pause for an immutable hook API
    If maintainers want immutable internal hook contexts long term, pause this PR and design a return-value or context-patch API with an external-plugin migration path.

Next step before merge

  • [P2] Maintainer review is needed for the mutable registerHook context compatibility direction and draft readiness; there is no narrow automated repair left to queue.

Security
Cleared: The diff is limited to in-process plugin registry behavior and tests; it adds no dependency, workflow, permission, secret, install, package, or downloaded-code surface.

Review details

Best possible solution:

Land this focused registry-boundary repair after maintainer acceptance of the mutable registerHook context contract and a ready-for-review signal; otherwise pause for an explicit immutable hook API redesign with migration guidance.

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

Yes. Source inspection gives a high-confidence path: current main clones evt.context, while applyBootstrapHookOverrides reads bootstrapFiles from the original event after sequential hook dispatch.

Is this the best way to solve the issue?

Yes, pending maintainer compatibility acceptance. Fixing the generic registry wrapper is narrower and more maintainable than a bootstrap-only workaround or field-by-field merge, and the finally cleanup addresses the leakage concern that caused the clone.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e7ee1c55b433.

Label changes

Label justifications:

  • P2: The PR fixes a source-reproducible plugin hook context regression with meaningful agent-bootstrap impact but a bounded plugin registry surface.
  • merge-risk: 🚨 compatibility: The diff intentionally changes context object identity and mutation propagation observed by external api.registerHook handlers.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies after-fix live output from two temporary real plugins loaded through loadOpenClawPlugins, showing context mutation propagation and no pluginConfig leakage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix live output from two temporary real plugins loaded through loadOpenClawPlugins, showing context mutation propagation and no pluginConfig leakage.
Evidence reviewed

PR surface:

Source +11, Tests +162. Total +173 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 14 3 +11
Tests 1 162 0 +162
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 176 3 +173

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/plugins/loader.test.ts --testNamePattern "runs consecutive plugin hook handlers|preserves plugin hook context mutations|injects plugin config" --reporter dot.
  • [P1] node_modules/.bin/tsx /tmp/proof-pr89002-hook-context.ts.
  • [P1] pnpm check:changed after the PR is ready and dependency hydration is healthy.

What I checked:

  • Current main still drops context replacement: Current main wraps plugin hook handlers with a shallow-copied context, so assignments like event.context.bootstrapFiles = ... happen on a clone rather than the event object later consumed by core. (src/plugins/registry.ts:743, e7ee1c55b433)
  • Bootstrap path expects mutable context: applyBootstrapHookOverrides creates one hook event, awaits triggerInternalHook(event), then reads event.context.bootstrapFiles, which establishes the failing source path for registered plugin handlers that receive a cloned context. (src/agents/bootstrap-hooks.ts:31, e7ee1c55b433)
  • Hook runner dispatches the same event sequentially: triggerInternalHook awaits each registered handler in order against the same event object, so a correct wrapper must both preserve intended context mutations and prevent per-handler pluginConfig leakage. (src/hooks/internal-hooks.ts:294, e7ee1c55b433)
  • Public hook docs define bootstrap context as mutable: The public automation hook documentation describes agent:bootstrap context.bootstrapFiles as a mutable array, supporting this as a bug fix rather than a new feature. Public docs: docs/automation/hooks.md. (docs/automation/hooks.md:142, e7ee1c55b433)
  • PR patch preserves context and cleans pluginConfig: The PR head reuses evt.context, assigns context.pluginConfig for the handler call, and restores or deletes it in a finally block. (src/plugins/registry.ts:738, 10bfe43293c5)
  • PR tests cover mutation and leakage: The PR adds loader-backed tests where a registered plugin mutates bootstrapFiles, consecutive handlers share the mutation, and pluginConfig does not leak into the final event context or the next handler. (src/plugins/loader.test.ts:2732, 10bfe43293c5)

Likely related people:

  • Ayumi Server: Authored the commits that added pluginConfig injection and then changed the wrapper to shallow-copy hook context for per-handler isolation. (role: introduced wrapper behavior; confidence: high; commits: ed0b098d7596, c1187109c8fb; files: src/plugins/registry.ts)
  • steipete: Introduced the agent:bootstrap hook path and committed the pluginConfig/shallow-copy wrapper commits, making this a likely routing point for the contract decision. (role: feature-history owner and committer; confidence: high; commits: ad3c12a43a70, ed0b098d7596, c1187109c8fb; files: src/agents/bootstrap-hooks.ts, src/hooks/internal-hooks.ts, src/plugins/registry.ts)
  • 100yenadmin: Authored merged generic plugin host-hook contract work and supplied the linked source issue with detailed real-run evidence for this exact behavior. (role: adjacent plugin hook contract contributor; confidence: medium; commits: 1adaa28dc86b; files: src/plugins/registry.ts, src/plugins/types.ts, docs/plugins/hooks.md)
  • Dallin Romney: Current-line blame shows recent plugin registry and bootstrap files were carried through fix(reply): avoid bundled channel load in dedupe, so this is useful recent-area provenance but not the root cause by itself. (role: recent area contributor; confidence: low; commits: cae64ee360a8; files: src/plugins/registry.ts, src/agents/bootstrap-hooks.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jun 1, 2026
@byungskers

Copy link
Copy Markdown

I like this direction. Reusing the same context object fixes the lost-mutation problem cleanly, and the finally block restoring/removing pluginConfig keeps the config from leaking into later handlers. A small follow-up test that runs two hook handlers back-to-back (first mutates context with pluginConfig present, second asserts pluginConfig is gone but the mutation remains) would give really strong confidence in the cleanup contract.

@wyf027
wyf027 marked this pull request as draft June 2, 2026 13:25
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 2, 2026
@wyf027

wyf027 commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — I added the back-to-back handler regression you suggested and pushed it in 10bfe43.

I also updated the PR body with a real plugin-loader proof: two temporary plugins with openclaw.plugin.json + CJS entrypoints are loaded through loadOpenClawPlugins; the first handler sees its config and mutates the shared context, the second handler sees the mutation with pluginConfig cleaned, and the final event context has no leaked pluginConfig.

Focused verification run:

node scripts/run-vitest.mjs src/plugins/loader.test.ts --testNamePattern "runs consecutive plugin hook handlers|preserves plugin hook context mutations|injects plugin config" --reporter dot
# 1 test file passed; 3 tests passed, 148 skipped

node_modules/.bin/tsx /tmp/proof-pr89002-hook-context.ts
# PASS: real plugin hooks loaded through loadOpenClawPlugins share context mutations while pluginConfig is cleaned before the next handler.

@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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 2, 2026
@wyf027
wyf027 marked this pull request as ready for review June 5, 2026 09:49
@wyf027
wyf027 marked this pull request as draft June 12, 2026 13:18
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 12, 2026
@wyf027

wyf027 commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Closing this stale draft PR because it has been open for a long time without merge. I can reopen or resubmit if needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

registerHook wrapper drops mutable context changes for agent:bootstrap hooks

2 participants