Skip to content

refactor(harness): share prompt preparation and context policies - #159779

Merged
sjf-oa merged 4 commits into
mainfrom
sjf/harness-prompt-inputs
Sep 27, 2026
Merged

sjf-oa merged 4 commits into
mainfrom
sjf/harness-prompt-inputs

Conversation

@sjf-oa

@sjf-oa sjf-oa commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Why This Change Was Made

Codex and AgentsAPI need the same backend-neutral prompt preparation. Centralize the existing admitted-message normalization, hook tool-policy classification, lightweight-cron context exclusion, and workspace-memory routing decisions before adding the AgentsAPI prompt-hook caller.

What Problem This Solves

The shared prompt builder accepts an admitted message, extracts its text and identity, and tells its instruction builder whether the hook restricted tools. Both backends also use shared helpers for runtime-context inclusion and deciding whether admitted memory tools reach the selected prompt workspace.

The context helpers use the existing private harness SDK entrypoint. Backend workspace selection, tool-name normalization, prompt wording, failure handling, native restriction enforcement, and lifecycle ownership remain with their current owners. Copilot is unchanged. No new interface, class, configuration option, or public SDK contract.

User Impact

No intended behavior change. This is the first PR in the stack; #159375 adds the AgentsAPI implementation on top.

Evidence

  • Moved multipart message-normalization coverage and the isolated cron-policy assertion to colocated shared harness tests. Added shared routing eligibility cases while retaining backend tests for sandbox/inherited workspace selection, recorder and refresh handling, native prompt delivery, restrictions, and cleanup.
  • Published both refactor commits and restacked the child before review and validation, as requested.
  • The latest extraction adds 10 net production lines, 51 net test lines, and 6 documentation lines.
  • git diff --check passed. GitHub confirms the refactor is based on main and the child remains based on this branch. git range-diff confirms the child implementation patch is unchanged by the restack.
  • Independent source review of extraction commit eea2ffc416153cc6dcfd91350eafc2b7ded4a577 completed with no P0-P2 findings. The earlier prompt-input refactor and feature implementation also received source review with no P0-P2 findings.
  • Tests, formatting, type checks, builds, and live runs remain paused at the maintainer's request. Test runtime is unmeasured; runtime validation remains pending.

@clawsweeper

clawsweeper Bot commented Sep 27, 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 extensions: codex size: S labels Sep 27, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Sep 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 27, 2026, 1:08 PM ET / 17:08 UTC (Revision 2).

ClawSweeper review

What this changes

The branch moves admitted-message preparation, hook restriction classification, cron context exclusion, and workspace-memory routing into shared harness helpers used by Codex and AgentsAPI, with accompanying tests and documentation.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open. Current main and the latest release lack the shared preparation path, and the open stacked AgentsAPI PR depends on it. Source review found no discrete patch defect; focused validation and the repository-required test-cost measurements remain outstanding.

Priority: P3
Reviewed head: 9b6c6e95b54bfe8ac90418e3157814db631cd76d

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The refactor is coherent and has focused source-level coverage; executed caller validation and test-cost evidence remain pending.
Proof confidence 🌊 off-meta tidepool Not applicable: The provided repository state classifies the author as MEMBER, so the external-contributor proof gate does not apply. Source review covered the shared prompt owner and both adapters; no after-change runtime run is claimed, and no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The provided repository state classifies the author as MEMBER, so the external-contributor proof gate does not apply. Source review covered the shared prompt owner and both adapters; no after-change runtime run is claimed, and no stored-data contract changes.
Evidence reviewed 11 items Introduced prompt preparation: The shared helper accepts an admitted message object while retaining string and separate-ID inputs, and supplies a restriction flag to the instruction builder.
Shared context policy: The new owner excludes runtime additions for lightweight cron turns and routes memory tools only when the prompt workspace matches the configured agent workspace.
Codex caller: Codex passes its admitted message to the shared helper and still rejects restrictive hook tool lists before proceeding with prompt preparation.
Findings None None.
Security None None.

How this fits together

The agent harness takes admitted user messages, plugin hook results, workspace configuration, and available tools to prepare prompt context. Codex and AgentsAPI adapters then pass that context to their respective agent runtimes.

flowchart LR
  A[Admitted user message] --> C[Shared harness preparation]
  B[Plugin hooks and available tools] --> C
  C --> D{Runtime context allowed?}
  D --> E[Workspace memory routing]
  E --> F[Backend prompt adapter]
  F --> G[Native agent turn]
Loading

Before merge

  • Resolve merge risk (P1) - The expanded Plugin SDK helper and both backend callers have not had focused validation on this head, and the changed test files still lack the measured cost required by repository policy.
  • Complete next step (P2) - When validation resumes, run focused shared-harness, Codex, and AgentsAPI caller checks; confirm legacy string, separate-ID, and toolsAllow callback behavior; and record the required test wall and CI times.
Agent review details

Security

None.

PR surface

Source +13, Tests +94, Docs +18. Total +125 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 7 96 83 +13
Tests 4 156 62 +94
Docs 1 18 0 +18
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 270 145 +125

Review metrics

Metric Value Why it matters
SDK helper contract 1 admitted-message object input and 1 callback field added Existing plugin consumers of the exported helper are the relevant compatibility boundary.

Merge-risk options

Maintainer options:

  1. Validate the shared helper (recommended)
    When validation resumes, exercise the existing string and ID callers and the Codex and AgentsAPI prompt paths, then record the new tests' wall time and CI cost.

Technical review

Best possible solution:

Keep one harness owner for admitted input and shared context policy while the adapters retain backend-specific workspace selection, native prompt delivery, and tool enforcement.

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

Not applicable: this PR is a refactor and reports no failing current-main behavior. Source comparison establishes the separate preparation paths it consolidates.

Is this the best way to solve the issue?

Yes: the existing harness is the narrow owner for shared prompt policy, while the adapters retain their distinct native behavior. Focused caller validation is still needed.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is an internal harness refactor with no intended user-visible behavior change.
  • merge-risk: 🚨 compatibility: The branch expands an exported prompt-helper contract used by harness plugins, and focused caller validation remains outstanding.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The provided repository state classifies the author as MEMBER, so the external-contributor proof gate does not apply. Source review covered the shared prompt owner and both adapters; no after-change runtime run is claimed, and no stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • sjf-oa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record focused helper and backend caller validation plus measured wall and CI time for the new or materially changed test files.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-27T16:33:06.962Z sha af65c4e :: blocked before merge. :: none

@sjf-oa sjf-oa changed the title refactor(agents): share harness prompt input preparation refactor(harness): share prompt preparation and context policies Sep 27, 2026
@sjf-oa
sjf-oa force-pushed the sjf/harness-prompt-inputs branch from eea2ffc to 3a253f5 Compare September 27, 2026 16:45
@sjf-oa

sjf-oa commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review the current head after the main-branch conflict resolution and formatting repair. The maintainer explicitly authorizes merging this refactor without a live test or attached live proof; do not treat live runtime evidence as a merge requirement.

The existing string currentUserMessage and separate currentUserMessageId inputs remain supported. Existing instruction-builder callbacks that consume toolsAllow remain valid; hasToolRestrictions is an additional supplied field. Existing caller tests remain alongside the shared normalization and policy tests. The new context policy helpers are exposed only through the existing production-private harness entrypoint. Backend workspace selection, tool-name normalization, prompt wording, and failure behavior are preserved.

The child prompt-hook implementation remains separate. Please identify any concrete remaining compatibility defect rather than requiring live proof for the additive shared contract.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@sjf-oa
sjf-oa force-pushed the sjf/harness-prompt-inputs branch from 72e8fdf to 9b6c6e9 Compare September 27, 2026 17:01
@sjf-oa

sjf-oa commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The previous exact-review workflow completed but did not update the durable PR verdict. The current head additionally fixes the CI no-shadow errors in the shared memory-routing test; the focused lint check passes. That latest repair changes only test parameter names and formatting, with no production changes.

Please review the current head with the existing maintainer decision: merge this refactor without live tests or attached live proof. Existing string/currentUserMessageId inputs and toolsAllow callback consumers remain supported, and the backend-specific prompt behavior is preserved. CI is running on the repaired head.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@sjf-oa
sjf-oa merged commit 71bd3de into main Sep 27, 2026
123 checks passed
@sjf-oa
sjf-oa deleted the sjf/harness-prompt-inputs branch September 27, 2026 17:15
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
…nclaw#159779)

* refactor(agents): share harness prompt input preparation

* refactor(harness): share runtime context and memory routing policy

* style(harness): format shared prompt preparation

* test(harness): avoid shadowed memory routing fixtures

---------

Co-authored-by: Sarah Fortune <[email protected]>
obviyus added a commit that referenced this pull request Oct 13, 2026
…ess runtimes (#169558)

## What Problem This Solves

Fixes: context a plugin queues for a conversation's next turn (`api.session.workflow.enqueueNextTurnInjection`) is silently dropped when that turn runs on a harness runtime (Codex app-server, ACPX, Agents API, Copilot). OpenAI models use the Codex runtime by default, so most installs never receive these injections.

## User Impact

Plugins that queue next-turn context now reach the agent on every runtime, not only the built-in one. Turns with nothing queued produce byte-identical prompts, so prompt caching is unchanged.

## Why This Change Was Made

Only the built-in runner drained the durable injection queue and ran `agent_turn_prepare`. The harness prompt builder skipped both, and returned early when no prompt hooks were registered. One module now owns queue draining, the per-run retry cache, and `agent_turn_prepare`. The built-in runner and the harness prompt builder both use it, in the existing order: queued injections, `agent_turn_prepare`, heartbeat contribution, `before_prompt_build`. Harness runs release the retry cache when the run ends. History is still loaded only when a prompt hook needs it.

## Evidence

- **Live, real OpenAI API, isolated Gateway, Codex runtime (default for `openai/gpt-6.1-sol`):** a plugin queued a correction after a turn, and the next turn was asked to quote any note it received.
  - Before (current `main`): the agent answered "No, my context for this turn does not include a note starting with 'Progress review (OpenClaw Labs)'."
  - After: the agent quoted the queued note verbatim.
- **Regression test:** `src/agents/harness/prompt-compaction-hook-helpers.test.ts` "delivers queued injections". With a real enqueued injection and no prompt hooks registered, the prompt contains the text once, a same-run retry reuses it, and the queue is drained. It fails on `main` (`prompt.match(...)` is null) and passes with this change.
- **Focused tests:** harness helper 12/12, embedded prompt helpers 6/6, host-hook contract injection cases 7/7.
- Maintainer-intent check: #159779 and #159375 shaped this helper and the Agents API hooks. This change keeps their contract: no-hook and heartbeat-only attempts still do not read history, and the Agents API `config` move only places it in the shared host-side context (`buildAgentHookContext` does not forward `config` to plugins).
- Not run locally: full lint (the plugin-SDK boundary declaration prep timed out on a loaded host). Left to hosted CI.

**Merge danger:** two-way door; a revert restores the old behavior. Blast radius: harness runtimes now drain the injection queue, so plugins that already queue next-turn context (for example on Codex) will start seeing it delivered.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…ess runtimes (openclaw#169558)

## What Problem This Solves

Fixes: context a plugin queues for a conversation's next turn (`api.session.workflow.enqueueNextTurnInjection`) is silently dropped when that turn runs on a harness runtime (Codex app-server, ACPX, Agents API, Copilot). OpenAI models use the Codex runtime by default, so most installs never receive these injections.

## User Impact

Plugins that queue next-turn context now reach the agent on every runtime, not only the built-in one. Turns with nothing queued produce byte-identical prompts, so prompt caching is unchanged.

## Why This Change Was Made

Only the built-in runner drained the durable injection queue and ran `agent_turn_prepare`. The harness prompt builder skipped both, and returned early when no prompt hooks were registered. One module now owns queue draining, the per-run retry cache, and `agent_turn_prepare`. The built-in runner and the harness prompt builder both use it, in the existing order: queued injections, `agent_turn_prepare`, heartbeat contribution, `before_prompt_build`. Harness runs release the retry cache when the run ends. History is still loaded only when a prompt hook needs it.

## Evidence

- **Live, real OpenAI API, isolated Gateway, Codex runtime (default for `openai/gpt-6.1-sol`):** a plugin queued a correction after a turn, and the next turn was asked to quote any note it received.
  - Before (current `main`): the agent answered "No, my context for this turn does not include a note starting with 'Progress review (OpenClaw Labs)'."
  - After: the agent quoted the queued note verbatim.
- **Regression test:** `src/agents/harness/prompt-compaction-hook-helpers.test.ts` "delivers queued injections". With a real enqueued injection and no prompt hooks registered, the prompt contains the text once, a same-run retry reuses it, and the queue is drained. It fails on `main` (`prompt.match(...)` is null) and passes with this change.
- **Focused tests:** harness helper 12/12, embedded prompt helpers 6/6, host-hook contract injection cases 7/7.
- Maintainer-intent check: openclaw#159779 and openclaw#159375 shaped this helper and the Agents API hooks. This change keeps their contract: no-hook and heartbeat-only attempts still do not read history, and the Agents API `config` move only places it in the shared host-side context (`buildAgentHookContext` does not forward `config` to plugins).
- Not run locally: full lint (the plugin-SDK boundary declaration prep timed out on a loaded host). Left to hosted CI.

**Merge danger:** two-way door; a revert restores the old behavior. Blast radius: harness runtimes now drain the injection queue, so plugins that already queue next-turn context (for example on Codex) will start seeing it delivered.

Co-authored-by: Ayaan Zaidi <[email protected]>
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: agentsapi extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

2 participants