Skip to content

refactor(agents): share workspace context preparation - #158389

Merged
sjf-oa merged 6 commits into
mainfrom
sjf/shared-agent-workspace-context
Sep 26, 2026
Merged

sjf-oa merged 6 commits into
mainfrom
sjf/shared-agent-workspace-context

Conversation

@sjf-oa

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

Copy link
Copy Markdown
Contributor

Why This Change Was Made

OpenClaw workspace instructions, persona, and memory guidance should have one preparation owner that native harnesses can consume. Keeping that policy inside the Codex adapter makes another harness duplicate it or omit it. This MVP extraction provides shared preparation while preserving Codex's native delivery behavior.

This standalone extraction is explicitly maintainer-directed as the prerequisite for #158328. The two new functions in openclaw/plugin-sdk/agent-harness-runtime are the intended shared contract; Codex keeps its native delivery and lifecycle decisions. The maintainer has explicitly approved merging without attaching a live Codex trace. The source comparison and native request-boundary tests below are the accepted evidence for this refactor; no live session proof is claimed.

What Problem This Solves

Makes bounded Gateway workspace context reusable by native harnesses without copying Codex-specific protocol or filesystem behavior.

User Impact

Preserves Codex instruction bytes, context refresh, memory routing, warning logging, and saved snapshots. Agents API integration remains a separate stacked change.

What Changed

  • Move bootstrap loading, budgeting, context partitioning, persona framing, root instruction snapshots, and active memory-plugin guidance into the shared harness owner.
  • Provide full-context and instructions-only preparation. Instructions-only selection happens before budgeting so unsupported context cannot consume the agent-rule budget.
  • Reuse the existing context-file ordering and personal-overlay wording owner. Preserve Codex's ordering, path projection, native project-document exclusions, restriction gates, and snapshot selection timing.
  • Keep native instruction carriers, deferred-tool guidance, fork preparation, filesystem placement, and recovery policy in Codex.
  • Move generic persona and memory-context tests beside the shared owner; retain native payload, restriction, snapshot, and fallback coverage in Codex.

MVP Gaps

The current Agents API client supports creation instructions, reasoning updates, and user messages. It does not implement a per-turn developer instruction carrier, instruction refresh, native fork preparation, or Gateway-to-hosted-workspace path projection. Persona and personal-overlay refresh, other turn-scoped workspace context, and memory prompt guidance remain unimplemented in that adapter. This PR supplies preparation, without claiming those client operations are available or freezing turn-scoped context into session instructions. No filesystem transfer, new API operation, configuration, or persistence migration is added.

Full-context preparation preserves the existing Codex selection timing: projecting the root instruction path away from its source workspace produces an empty root snapshot. The Agents API instructions-only caller does not project paths. Cross-workspace snapshot selection is outside this MVP.

Evidence

Fresh independent source review found no remaining actionable P0-P2 findings, including SDK accounting and strict Codex parity follow-ups. The autoreview CLI was unavailable for the signed-in account; independent source review supplied the review instead.

  • Focused shared and Codex snapshot/context run: 34 tests passed across four files, 107.25 seconds wall time.
  • Canonical SDK surface guard passes at 4,579 public exports and 2,687 callable exports, exactly two above the base. Other surface budgets and guard logic are unchanged.
  • Strict base/head comparison: the original base passed 212 Codex tests in 387.38 seconds wall time; the refactor at 38ac4ae5dfdaaa161ef8b4a7f1d6968297a4969e passed 206 in 332.69 seconds. Six generic cases moved to core, and all thirteen core preparation/snapshot cases pass. The existing full native attempt file is unchanged and passes on both versions, covering real mocked app-server request payloads, workspace context, routing, lifetimes, recovery, hooks, persistence and delivery.
  • Parity review caught and repaired two extraction differences before completion: leading whitespace inside hook-supplied filenames now retains Codex's original ordering, and optional memory preparation retains the original warning text and structured error. Regressions protect both. The refactor retains the existing Codex behavior; the shared instructions-only mode is an additional capability used by the separate Agents API PR.
  • Canonical SDK API comparison: exactly two added functions, no removals, no entrypoint changes, and no existing export declaration changes. There are 126 reachable declaration-closure changes; these are not existing export-signature changes. Digest: 5f22fe850b2a1d75f61c2a83b7e8ffb38c289f9716a645b412127b91db803dc5.
  • Single-worker measured file costs under concurrent cold verification: shared context 99.27 seconds wall (nine cases); snapshot 2.82 seconds (four cases); existing USER owner 45.91 seconds (three cases); SDK guard 13.05 seconds (eleven cases). Core preparation test bodies totalled under one second; the cold costs are dominated by transformations and worker preparation. Warm shared-context measurement passes in 20.30 seconds wall, including cached worker preparation; nine test bodies remain under one second. Per-file CI cost is not available.
  • The PR merge containing final head ebea171d02e89881ee7a479a6654da7aa145fb80 passed the canonical pnpm build:ci-artifacts build, including runtime bundles, SDK declarations, SDK export validation, generated assets and UI. Build command cost: 217 seconds; the separate Control UI build took 16 seconds. Passing build job. The earlier full local build was interrupted and is not claimed as passing.
  • The only later source delta after the full parity run replaces an object spread with Object.assign into a newly created temporary object to satisfy lint. It does not mutate bootstrap inputs. Fresh independent review found no observable change. All nine shared-context tests and three native memory-routing tests pass on final head, in 26.17 and 32.83 seconds wall respectively. Formatting and whitespace checks pass. All selected changed-file checks pass: formatting, core/source/test, extension/source/test and script types, SDK exports and surface, plugin ownership/boundaries, dependency/ratchet, deprecation/coercion, dead exports, core/extension/script lint, native schema, legacy-store/media/sidecar/import-cycle and webhook/pairing guards. The lint rule rejected a map-spread allocation; the temporary-object correction described above passed fresh review, affected tests and all remaining lint/guard checks.

A native payload test invocation failed before executing tests because it overlapped the build: Error: Boundary configuration or resolution topology changed during compilation. An owner-guard invocation had the same compile-time topology failure. The build created package outputs while each compiler was sealing its input snapshot. The lanes passed after package emission stopped; no product fix or weakened compiler guard was used for that scheduling failure. The first build was interrupted to apply the two parity corrections and is not success evidence. The passing canonical CI artifact build above supplies final packaging evidence.

No local Docker Gateway or live hosted API session is part of this source refactor validation. Live Codex trace attachment is explicitly waived by the maintainer.

Current required CI is blocked by the existing chat reset/yield failure in src/gateway/server-methods/chat.reset-visible-yield.test.ts (run 36197770240, job 108278733146). The same failure is recorded outside this refactor, and the lifecycle owner repair is tracked in #158524. This extraction does not modify those lifecycle owners. The maintainer explicitly accepted this unrelated failure and directed merging the refactor. No tests related to this refactor are failing. The failed group has one failing test case with two assertion failures and 400 passing tests; 43 other checks were cancelled, so this is not a claim that all CI passed.

Base: 1667391dc4676e731efe1c5c3a49065e1f4bebb0

@clawsweeper

clawsweeper Bot commented Sep 25, 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: XL labels Sep 25, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Sep 25, 2026
@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Sep 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 25, 2026, 9:26 PM ET / September 26, 2026, 01:26 UTC (Revision 2).

ClawSweeper review

What this changes

The branch moves workspace instruction, persona, project-context, and memory preparation into shared harness helpers exposed through the Plugin SDK, then updates the Codex adapter, documentation, and tests to use them.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open. Current main still prepares Codex workspace context locally, and the linked Agents API fix depends on this branch. The source review found no actionable correctness defect, but the public SDK refactor needs maintainer sponsorship and after-change native behavior proof.

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

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🌊 off-meta tidepool Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 12 items Introduced preparation owner: The new helper composes the existing bootstrap loader and budgeter, selects instructions before budgeting in instructions-only mode, and separates persona, project context, and memory guidance in full mode.
Native Codex boundary: The Codex adapter calls the shared helper while retaining native path projection, project-document exclusion, memory-tool selection, and thread/turn delivery decisions.
Current-main necessity: Current main still invokes the Codex-local bootstrap loader and has neither new shared workspace helper; this branch is not implemented there.
Findings None None.
Security None None.

How this fits together

OpenClaw reads workspace files, applies session filters and character budgets, then prepares context for an agent harness. The Codex adapter places that context into native thread and turn requests and retains instruction snapshots for resumed sessions.

flowchart LR
A[Workspace files] --> B[Session filters and budgets]
B --> C[Shared context preparation]
C --> D[Instruction snapshot]
C --> E[Persona and memory guidance]
D --> F[Codex adapter]
E --> F
F --> G[Native thread and turn requests]
Loading

Decision needed

Question Recommendation
Should this shared public SDK extraction be sponsored as the prerequisite for the open Agents API instructions fix? Sponsor the coupled stack: Approve this narrow shared seam as part of the linked Agents API fix, subject to real Codex proof and normal merge gates.

Why: OpenClaw's contribution policy requires explicit maintainer direction for a refactor-only PR, and accepting a public SDK contract is a lasting ownership choice.

Before merge

  • Resolve merge risk (P1) - The two new public Plugin SDK functions would ship before their linked Agents API consumer; the owner has not yet confirmed that this standalone refactor is the intended supported contract.
  • Resolve merge risk (P1) - A native Codex session has not shown that existing thread and turn instructions, memory guidance, and saved snapshot behavior survive the extraction unchanged.
  • Complete next step (P2) - Get agent and SDK owner direction on the coupled stack, and add redacted after-change native Codex behavior proof before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +12, Tests +107, Docs +31, Other +2. Total +152 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 334 322 +12
Tests 4 279 172 +107
Docs 1 31 0 +31
Config 0 0 0 0
Generated 0 0 0 0
Other 1 4 2 +2
Total 11 648 496 +152

Review metrics

Metric Value Why it matters
Public SDK calls 2 added, 0 removed The new callable contract has a long-term compatibility cost even though existing exports remain intact.
Code and test balance production +12 lines, tests +107 lines The modest net production growth is explained by replacing Codex-local preparation with one shared owner.

Merge-risk options

Maintainer options:

  1. Approve and prove the coupled contract (recommended)
    Obtain agent and SDK owner sponsorship plus a redacted native Codex session trace before merging this branch with its dependent fix.
  2. Fold the extraction into the fix
    If a standalone SDK contract is premature, consolidate the two branches and retire this branch after a viable replacement exists.

Technical review

Best possible solution:

Use one approved preparation owner for Codex and the Agents API consumer, while preserving Codex's existing prompt and snapshot behavior and exposing only the SDK operations both harnesses need.

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

Not applicable: this is a refactor rather than a report of a failing current-main behavior. The old and proposed Codex preparation paths are available for source comparison.

Is this the best way to solve the issue?

Unclear pending maintainer direction: the extraction is coherent and has a concrete stacked consumer, but the owner must decide whether this public SDK seam should land separately or within that fix.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This bounded harness improvement supports an open Agents API fix but has limited immediate user impact by itself.
  • merge-risk: 🚨 compatibility: The patch moves existing Codex prompt preparation and adds public SDK calls; native-session parity and the final public contract remain unresolved.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Sarah Fortune: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RoboClaw: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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-25T23:56:34.662Z sha ebea171 :: blocked before merge. :: none

@sjf-oa

sjf-oa commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please reassess the current head ebea171d02e89881ee7a479a6654da7aa145fb80. The latest review reports no actionable correctness or security findings but leaves a review-confidence blocker. The PR description records the strict base/head comparison, unchanged native attempt coverage, final memory-routing regressions, canonical SDK comparison, and final-head artifact build. Please identify any concrete remaining source or evidence gap needed to resolve that confidence blocker. This is a request for review only.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 26, 2026
@sjf-oa

sjf-oa commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Maintainer direction for the current head ebea171d02e89881ee7a479a6654da7aa145fb80: this standalone shared SDK extraction is explicitly requested as the prerequisite for #158328. The two shared preparation functions are the intended supported contract, with Codex-specific delivery and lifecycle decisions retained in the adapter.

The maintainer has now explicitly directed merging without attaching live Codex proof. Accept the documented source parity comparison and existing native request-boundary regressions for this refactor. No live Codex session is claimed. The PR description records this waiver and the remaining CI issue.

Please reassess the owner-decision and live-trace blockers in the latest review using that direction. This requests review only; normal CI gates still apply. No production logic changes are requested or authorized by this comment.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@sjf-oa
sjf-oa merged commit dc8bfda into main Sep 26, 2026
198 of 244 checks passed
@sjf-oa
sjf-oa deleted the sjf/shared-agent-workspace-context branch September 26, 2026 01:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
Share workspace instruction, persona, and memory preparation through the existing agent harness SDK so native harnesses can reuse the same owner. Keep Codex protocol delivery, path projection, restriction gates, and saved snapshot behavior in its adapter. Move generic coverage alongside the shared code.

Validation: source parity review, unchanged native request-boundary tests on base and refactor, shared preparation regressions, selected type/lint/SDK checks, and the canonical artifact build passed. ClawSweeper found no actionable correctness or security findings.

Maintainer-directed merge accepts the known unrelated chat reset/yield CI failure tracked in openclaw#158524 and waives live Codex trace attachment. Other cancelled CI checks are not claimed as passing.
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: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts size: XL 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