Skip to content

fix(plugins): supply the admitted request to before_prompt_build on embedded and CLI runs - #161773

Open
xydigitLybnnnn wants to merge 17 commits into
openclaw:mainfrom
xydigitLybnnnn:fix/160232-embedded-prompt-current-input
Open

xydigitLybnnnn wants to merge 17 commits into
openclaw:mainfrom
xydigitLybnnnn:fix/160232-embedded-prompt-current-input

Conversation

@xydigitLybnnnn

@xydigitLybnnnn xydigitLybnnnn commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Related: #160232

What Problem This Solves

Fixes: a plugin registered on before_prompt_build cannot tell which admitted request a turn belongs to when that turn runs on the embedded runner or the CLI backend. The event carried only prompt and messages, although currentUserMessage and currentUserMessageId are part of the documented event contract and are already supplied by the Codex, Copilot, and ACPX harness runtimes.

User Impact

Plugins that scope their work to the current request now receive the request text and its stable admission identity on the default runtimes, exactly as they already did on the harness runtimes. The bundled active-memory plugin is the concrete consumer: without the fields it fell back to the assembled prompt for intent detection and to the query text for its deterministic-recall reuse key, so two independent turns with identical text could share one recall result.

Compatibility: the two fields are added only for turns whose admitted request is owned by a transcript recorder. A run with no recorder keeps the previous identity-free event, so a plugin that branches on field omission — including active-memory's legacy path — sees no change for those runs. No config, schema, storage, migration, or default changes.

Maintainer decision requested. This makes currentUserMessage / currentUserMessageId informational on recorder-backed embedded and CLI turns, matching the contract the harness runtimes already implement. Requesting the plugin API owner's acceptance of that additive, omission-preserving event contract (the previous review's Decision needed); nothing else is pending on the contributor side.

Why This Change Was Made

currentUserMessage / currentUserMessageId were introduced for the harness prompt path in #149180. The embedded runner assembles its prompt through a different function and never passed them, and the CLI backend reuses that same helper, so both producers were affected. Both now read the fields from the recorder-owned admitted request — the representation Codex uses — and share one event builder with the harness path instead of copying the text/identity derivation.

currentUserMessageId is the recorder's idempotencyKey: stable across retries and rebuilds of one admission and different between admissions. An admitted request without text (for example image-only input) is reported as an explicit empty string rather than falling back to the assembled prompt, which may contain reconstructed history.

🤖 AI-assisted: This PR was developed with AI assistance.

Evidence

1. Real end-to-end turns on both changed runtimes

extensions/qa-lab/src/embedded-prompt-build-current-input.e2e.test.ts boots the repo Gateway from source, registers a probe plugin on before_prompt_build, sends a real qa-channel message, and asserts the event the plugin actually received — no injected assembly input:

  • embedded runtime (mock OpenAI provider), and
  • CLI backend process (bundled claude-cli backend with a fake claude on PATH implementing the stdio protocol), so a real CLI child process runs the turn.
$ pnpm test extensions/qa-lab/src/embedded-prompt-build-current-input.e2e.test.ts
CLI_PROCESS_TRACE {"turnStarted":true,"turnFinished":true,"reply":"fake-claude reply bb4caa70-f5cc-42e7-bc39-5a36a540fc1c"}
 ✓ binds the admitted request onto the embedded prompt boundary event 150470ms
 ✓ binds the admitted request onto the CLI backend prompt boundary event 147520ms
 Test Files  1 passed (1)
      Tests  2 passed (2)
E2E_EXIT=0
WALL_SECONDS=1922
# leftover fake-CLI temp directories after teardown:
0

CLI process observation (redacted). The CLI case asserts that the child process actually ran the turn — turn-started.json and turn-finished.json written by the fake CLI, and its reply delivered to the channel — as well as the hook event:

{ "turnStarted": true, "turnFinished": true, "reply": "fake-claude reply <uuid>" }

Raw hook event captured by the probe on the embedded harness (synthetic text, synthetic session, id truncated):

[
  {
    "keys": ["currentUserMessage", "currentUserMessageId", "messages", "prompt"],
    "hasCurrentUserMessage": true,
    "currentUserMessage": "PROBE_TRACE_MARKER",
    "hasCurrentUserMessageId": true,
    "currentUserMessageId": "channel-user:v1:ec6ff72264a1a0e1…",
    "promptHead": "PROBE_TRACE_MARKER",
    "messageCount": 0,
    "trigger": "user",
    "inputProvenanceKind": null
  }
]

Before this change the same producers emitted only { prompt, messages } — the shape reported in #160232.

2. Before / after on the embedded prompt-assembly entry point

# AFTER
$ pnpm test src/agents/embedded-agent-runner/run/attempt-prompt-build.provenance.test.ts
 ✓ binds the recorder-owned admitted request to the hook event
 ✓ keeps an admitted request without text instead of reusing the projected prompt
 ✓ keeps the legacy identity-free event when no request was admitted
 Test Files  1 passed (1)
      Tests  7 passed (7)
PROVENANCE_EXIT=0
# BEFORE: production change removed, test kept in place
$ pnpm test src/agents/embedded-agent-runner/run/attempt-prompt-build.provenance.test.ts
AssertionError: expected { prompt: 'Handoff payload', …(1) } to match object { …(2) }
  {
-   "currentUserMessage": "Handoff payload",
-   "currentUserMessageId": "run-admitted:user",
+   "messages": [],
+   "prompt": "Handoff payload",
  }
 Test Files  1 failed (1)
      Tests  3 failed | 4 passed (7)
TEST_EXIT=1

3. CLI backend producer — recorder-backed hook event at its preparation entry

src/agents/cli-runner/prepare.ts resolves the recorder message and passes it to both the ordinary and the authorized prompt-build dispatch. src/agents/cli-runner/prepare.test.ts prepares a real claude-cli turn whose admitted request is owned by a transcript recorder and asserts the event the hook runner received:

$ pnpm test src/agents/cli-runner/prepare.test.ts
 ✓ prepareCliRunContext > binds the recorder-owned admitted request to the CLI prompt-build event 1516ms
 Test Files  1 passed (1)
      Tests  118 passed (118)
CLI_PREPARE_EXIT=0
$ node scripts/run-oxlint.mjs src/agents/cli-runner/prepare.test.ts
Found 0 warnings and 0 errors.
OXLINT_EXIT=0

Observed dispatch (asserted in the test):

runBeforePromptBuild(expect.objectContaining({
  currentUserMessage: "latest ask",
  currentUserMessageId: "cli-admitted-request",
}), ctx)

The recorder-less fixture already in that file keeps its previous assertion with no fields, which is the compatibility case above.

4. Harness runtimes unchanged by the shared-builder extraction

$ pnpm test src/agents/harness/prompt-compaction-hook-helpers.test.ts
 Test Files  1 passed (1)
      Tests  25 passed (25)

5. Static gates

$ pnpm exec oxfmt --check --threads=1 <changed files>   # FMT_EXIT=0
$ node scripts/run-oxlint.mjs <changed files>           # Found 0 warnings and 0 errors. OXLINT_EXIT=0
$ NODE_OPTIONS=--max-old-space-size=8192 pnpm tsgo:core  # EXIT=0
$ NODE_OPTIONS=--max-old-space-size=8192 node scripts/run-tsgo.mjs \
    -p test/tsconfig/tsconfig.extensions.test.json --incremental \
    --tsBuildInfoFile .artifacts/tsgo-cache/extensions-test.tsbuildinfo   # EXIT=0

The extensions test typecheck is the lane that caught the earlier synchronous cleanup callback; it is green with the async callback.

Cost of the tests added

  • extensions/qa-lab/src/embedded-prompt-build-current-input.e2e.test.ts: 298.0 s of test time (1922 s wall including the E2E runtime preparation build) for two Gateway boots on the QA-lab product-proof tier; one file, 300 s per-test timeout, no sleeps.
  • src/agents/cli-runner/prepare.test.ts: +1 case, 1.5 s.

What was not tested

  • active-memory recall behaviour itself was not re-measured end to end; only the event contract it consumes is covered.
  • macOS/Windows were not exercised.
  • pnpm check:changed did not complete on this host: it aborted with FATAL ERROR: Ineffective mark-compacts near heap limit - JavaScript heap out of memory, and a retry with --max-old-space-size=12288 produced no output after ~25 minutes. The gates in section 5 cover the same changed-scope lanes for these files.

…uild

The embedded runner and the CLI backend emitted only `prompt` and
`messages` on the `before_prompt_build` event, so a plugin could not bind
a turn to its original request. `active-memory` then fell back to the
assembled prompt for intent detection and to the query text for its
deterministic-recall reuse key, letting independent same-text submissions
share one recall result.

Both producers now read `currentUserMessage` and `currentUserMessageId`
from the recorder-owned admitted request, matching the harness contract,
and share one event builder with the harness path.
@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Sep 30, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Sep 30, 2026
@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

The PR supplies recorder-owned request text and admission identity to embedded and CLI before_prompt_build hooks through a shared event builder.

Example: A recorder-backed CLI turn admits "latest ask" with identity "cli-admitted-request".

  • Before: The plugin receives prompt and messages without the original request fields.
  • After: The plugin also receives currentUserMessage="latest ask" and currentUserMessageId="cli-admitted-request".

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The changed event behavior has strong production-entry-point proof and no actionable patch finding; unresolved product acceptance and partial linked-issue scope cap overall readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied terminal and captured-event output exercises source Gateway turns through embedded execution and a real CLI child process, showing recorder-owned fields reaching the plugin and the CLI reply reaching the channel; the latest changes preserve that wiring.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Plugins on embedded and CLI runs cannot reliably scope intent and recall reuse to the admitted request instead of an assembled prompt.
Reason: The producer gap and consumer value are concrete, but the linked issue is broader and acceptance of the additive public event behavior remains unresolved.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR fills a verified gap on current main and has sufficient proof for its changed event behavior, but acceptance of the additive plugin contract remains an owner decision.

Priority: P2
Reviewed head: f9789a92341f0c11dfd193ffe3c9f5c6720a89d9
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should recorder-backed embedded and CLI before_prompt_build events supply currentUserMessage and currentUserMessageId as informational request facts while recorder-less runs retain omission?
  • Recommendation: Accept the bounded producer expansion: Approve recorder-owned request facts on embedded and CLI runs without making identity an authorization primitive or promising origin classification.
  • Why: The existing contract permits these fields but previously supplied them on harness paths; producer expansion changes plugin behavior, and no written owner acceptance settles that choice.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

Prompt preparation combines admitted input with conversation context, dispatches plugin hooks, and passes the resulting prompt toward model execution.

flowchart TD
  A[Admitted input] --> B[Transcript recorder]
  B --> C[Embedded prompt preparation]
  B --> D[CLI prompt preparation]
  C --> E[Shared event builder]
  D --> E
  E --> F[Plugin prompt hooks]
  F --> G[Model prompt]
Loading

Technical review

Best possible solution:

Accept the recorder-backed informational contract while preserving recorder-less omission and keeping broader origin and continuation guarantees separately scoped.

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

Current-main embedded and CLI producers visibly omit the fields, and the contributor supplies an embedded before/after failure plus Gateway traces; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Using the existing recorder and one shared event builder is a focused solution that preserves empty-input and legacy semantics, subject to acceptance of the producer contract.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Embedded and CLI event payload changes intended behavior with a stated reason (29cfd19: The authorized enrichment integration supplied prompt and messages while enforcing finalized tool policy; the earlier helper extraction does not establish when omission originally began.)
  • Harness normalization extraction keeps the original intent (71bd3de: Centralize backend-neutral admitted-message normalization and context policy without intended behavior changes.)
  • Request identity and omission semantics changes intended behavior with a stated reason (5d7f669: Keep recall tied to the admitted Codex request across rebuilds while preserving legacy producers and no-recorder behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4431033 adds src/agents/embedded-agent-runner/run/attempt-prompt-build.ts:182 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4431033e086e; files: src/agents/embedded-agent-runner/run/attempt-prompt-build.ts)
  • Sarah Fortune: Raw commit 71bd3de adds src/agents/harness/prompt-compaction-hook-helpers.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 71bd3ded986b; files: src/agents/harness/prompt-compaction-hook-helpers.ts)
  • lordratner: Raw commit 5d7f669 adds docs/plugins/hooks/prompt-and-session.md:41 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5d7f6690c5a6; files: docs/plugins/hooks/prompt-and-session.md)
  • Josh Avant: Raw commit 29cfd19 adds src/agents/embedded-agent-runner/run/attempt-prompt-build.ts:188 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 29cfd195d19d; files: src/agents/embedded-agent-runner/run/attempt-prompt-build.ts)

PR surface

Source +98, Tests +433, Docs +2. Total +533 across 13 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 7 135 37 +98
Tests 5 436 3 +433
Docs 1 8 6 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 579 46 +533

Root-cause cluster

Relationship: partial_overlap
Canonical: #160232
Summary: This PR implements recorder-backed request text and identity for two producers, while the canonical issue also requests origin classification and native continuation semantics.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The gap affects plugin request scoping on default runtimes with a limited, concrete consumer impact.
  • merge-risk: 🚨 compatibility: Supplying previously omitted optional fields changes request handling for plugins that branch on their presence, requiring plugin API owner acceptance.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-01T02:23:18.222Z sha fc13cc0 :: blocked before merge. :: [P3] Clean up the fake CLI directory
  • reviewed 2026-10-01T03:09:28.990Z sha f53e66f :: blocked before merge. :: [P2] Return a promise from the directory cleanup callback
  • reviewed 2026-10-01T03:31:40.633Z sha 786c070 :: blocked before merge. :: none
  • reviewed 2026-10-02T04:34:29.587Z sha d17cf62 :: blocked before merge. :: none
  • reviewed 2026-10-09T02:07:15.882Z sha 1ac0f9a :: blocked before merge. :: none
  • reviewed 2026-10-10T09:37:57.642Z sha c510b95 :: blocked before merge. :: none
  • reviewed 2026-10-12T01:16:10.788Z sha 5920a98 :: blocked before merge. :: none
  • reviewed 2026-10-12T03:41:57.900Z sha 3559a8c :: blocked before merge. :: none

Reviewed October 13, 2026, 8:50 PM ET / October 14, 2026, 00:50 UTC (Revision 15).

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 30, 2026
…uild

The embedded runner and the CLI backend emitted only `prompt` and
`messages` on the `before_prompt_build` event, so a plugin could not bind
a turn to its original request. `active-memory` then fell back to the
assembled prompt for intent detection and to the query text for its
deterministic-recall reuse key, letting independent same-text submissions
share one recall result.

Both producers now read `currentUserMessage` and `currentUserMessageId`
from the recorder-owned admitted request, matching the harness contract,
and share one event builder with the harness path. Runs without a
recorder keep the legacy identity-free event, so only admitted requests
gain the new fields.
@xydigitLybnnnn

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 1, 2026
Assert the CLI producer delivers the admitted request identity on
before_prompt_build when a transcript recorder owns the turn, next to the
existing recorder-less legacy assertion.
@xydigitLybnnnn

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…rent input

Boot the repo Gateway on the bundled Claude CLI backend with a fake CLI on
PATH and assert a registered before_prompt_build plugin receives the
admitted request text and identity on that process turn.
@xydigitLybnnnn

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…ld proof

Assert the fake CLI wrote its turn markers and its reply reached the
channel, so the CLI backend case proves a real child process ran the turn
rather than only echoing the shared hook event.
…-prompt-current-input

Resolve prompt-compaction-hook-helpers.ts by keeping the shared
buildPromptBuildHookEvent builder and upstream's agent_turn_prepare
message resolution.
@xydigitLybnnnn

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@igs-rogenlo

Copy link
Copy Markdown
Contributor

A data point for the decision above, from a plugin consumer on the embedded runtime.

On the published 2026.11.10 package the gap is unchanged, with the same shape reported on 2026.11.3 in #199547. With a plugin that records only field names in before_prompt_build, three turns on the embedded runtime (two through Gateway chat.send, one through openclaw agent) each delivered exactly ["messages", "prompt"]; currentUserMessage and currentUserMessageId were undefined.

The consumer is a memory plugin that checks a write against the request admitted for the current turn. The hook docs say to use the explicit request for intent detection and not to parse envelope markers to recover request boundaries, so on embedded runs there is no supported way to do that today. Omitting the fields on recorder-less runs, as proposed here, works for this use: a missing field can be treated as unknown and the write skipped.

This branch has not been deployed

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: qa-lab 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants