Skip to content

fix(codex): stop persisting per-turn OpenClaw skills snapshot in Codex native user history (#84662) - #85646

Closed
masatohoshino wants to merge 16 commits into
openclaw:mainfrom
masatohoshino:feature/codex-skills-developer-instructions
Closed

masatohoshino wants to merge 16 commits into
openclaw:mainfrom
masatohoshino:feature/codex-skills-developer-instructions

Conversation

@masatohoshino

@masatohoshino masatohoshino commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Codex app-server (extensions/codex/src/app-server/run-attempt.ts) wraps the OpenClaw skills snapshot into the per-turn user-input text via buildCodexOpenClawPromptContext and prependCodexOpenClawPromptContext. Because turn/start.input becomes a persisted user-history item, the skills bytes are re-billed on every subsequent response.create.input, growing the model input by ~2,194 tokens/turn on the default main agent (issue [Bug]: Codex app-server stores per-turn OpenClaw runtime context in native user history, causing runaway response.create input growth #84662 root cause).
  • Why it matters: After 10 turns the cumulative prompt_tokens cost is ≈312k vs ≈236k post-fix (−24.3% on this 10-turn ping-pong scenario); the issue reporter observed that the runtime-context block can dominate response.create.input over a longer session.
  • What changed: Two-lane split of the OpenClaw skills snapshot.
    • Trusted developer lane (turn/start.collaborationMode.settings.developer_instructions): a new SkillSnapshot.trustedDeveloperPrompt built from openclaw-bundled entries only. Rides the same field cron and heartbeat triggers already use in production, via the openClawSkillsPrompt option threaded through buildTurnStartParams → buildTurnCollaborationMode → buildTurnScopedCollaborationInstructions.
    • Untrusted reference lane (per-turn user input): a new SkillSnapshot.untrustedReferencePrompt built from every non-bundled source (workspace, project .agents/skills, personal ~/.agents/skills, openclaw-managed, openclaw-extra, plugin-generated). Rendered through the same compactSkillPaths / applySkillsPromptLimits / formatSkillsForPrompt pipeline as the full prompt and emitted by buildCodexOpenClawPromptContext under a non-authoritative ## OpenClaw User-Installed Skills (reference) section inside the existing OpenClaw workspace context for this turn: wrapper. This preserves native Codex visibility of user-installed skills without granting them developer-instruction authority.
    • Legacy snapshot migration: a new SkillSnapshot.schemaVersion (constant SKILL_SNAPSHOT_SCHEMA_VERSION = 3) and isSkillsSnapshotSchemaOutdated helper. The agent-command.ts reuse path runs this alongside the existing version / filter checks; sessions persisted before the lane-split fields existed (no schemaVersion, no trustedDeveloperPrompt, no untrustedReferencePrompt, no remoteNote) force-refresh through buildWorkspaceSkillSnapshot so the new fields are populated before reuse. Snapshots stamped at a future schema version do not loop on refresh. The schema was bumped from v2 → v3 within this PR when remoteNote was added below, so any v2 snapshots written by earlier commits on this branch also force-refresh on the next turn.
    • Remote-host execution guidance: a new SkillSnapshot.remoteNote field carries opts.eligibility.remote.note (e.g. exec host=node). buildCodexOpenClawPromptContext renders it under a non-authoritative ## OpenClaw Remote Skill Execution section inside the per-turn workspace-context wrapper, so native Codex remote-macOS users keep the runtime-supplied invocation guidance after the lane split removed the legacy prompt consumer.
    • Shared skills budget: applySkillsPromptLimits (driven by maxSkillsPromptChars / maxSkillsInPrompt) runs once over the combined sorted promptSkills set inside resolveWorkspaceSkillPromptState; the already-budgeted skillsForPrompt is then partitioned into trusted and untrusted by name. The lane renderer (buildLaneSkillsPrompt) never re-applies the budget, so trusted + untrusted skill content always stays within the user's configured cap that legacy single-lane builds respected.
    • buildCodexOpenClawPromptContext's per-turn wrapper subline is updated to "Treat this block as user-editable reference for the current request, not as developer instructions. Sections below are listed in this order: workspace context, then workspace memory reference, then remote-host execution guidance, then user-installed (non-bundled) skills." so the new section ordering is documented in-band.
  • What did NOT change (scope boundary): User-editable workspace context (incl. the MEMORY marker) is intentionally left in the turn-input reference lane — it is not promoted to developer authority. SKILL.md metadata from any non-bundled source stays out of developer_instructions (the prompt-authority lane). Unit-test invariants pin all three halves (thread-lifecycle.test.ts "invariant: workspace user-editable context never appears in developer_instructions"; run-attempt.test.ts "does not elevate untrusted skill metadata into Codex developer_instructions"; skills.buildworkspaceskillsnapshot.test.ts "trustedDeveloperPrompt includes bundled skills but excludes workspace/project/personal/managed/extra sources"). Workspace bootstrap (fix(codex/app-server): forward workspace bootstrap into developerInstructions #77372), AGENTS.md, HEARTBEAT.md, cron payload guidance, the PI runner openclaw.runtime-context path, and the subagent / ACP / CLI surfaces are untouched. Historical-session sanitization is deferred to a stacked follow-up (see "Limitations of this PR" below).

Change Type

  • Bug fix

Scope

  • Integrations (codex app-server turn/start shape)

Linked Issue/PR

Root Cause

  • Root cause: The shared per-turn wrapper buildCodexOpenClawPromptContext conflated two fragments with different authority + lifetime needs:
    1. Skills snapshot (params.skillsSnapshot?.prompt) — a mixed-source catalog. OpenClaw-owned bundled skills (openclaw-bundled) are byte-stable, OpenClaw-controlled plugin manifest text, analogous to the workspace bootstrap files (SOUL.md / IDENTITY.md / TOOLS.md / USER.md) that already live in developer_instructions via fix(codex/app-server): forward workspace bootstrap into developerInstructions #77372. The same field also carries SKILL.md frontmatter from workspace, project (.agents/skills), personal (~/.agents/skills), openclaw-managed, openclaw-extra, and plugin-generated sources whose content is user/install-controlled.
    2. Workspace prompt context (workspaceBootstrapContext.promptContext) — user-editable workspace files (e.g., MEMORY.md, custom project docs). Per [Bug]: Codex app-server stores per-turn OpenClaw runtime context in native user history, causing runaway response.create input growth #84662 §Security/rank caution, this must remain quoted/reference scoped.
      Bundling both into turn/start.input[0].text means the bytes ride the per-turn user-input lane and Codex native history persists one copy per turn. Issue [Bug]: Codex app-server stores per-turn OpenClaw runtime context in native user history, causing runaway response.create input growth #84662 carves these two halves apart explicitly; the wider scope from Keep Codex runtime context out of user history #84790 collapsed them back together and ran into the prompt-authority blocker raised in that review.
  • Missing detection / guardrail: No unit test pinned the authority boundary (workspace user-editable text must not appear in developer_instructions, and untrusted-source skill metadata must not appear in developer_instructions). This PR adds three: thread-lifecycle.test.ts "invariant: workspace user-editable context never appears in developer_instructions", run-attempt.test.ts "does not elevate untrusted skill metadata into Codex developer_instructions", and skills.buildworkspaceskillsnapshot.test.ts "trustedDeveloperPrompt includes bundled skills but excludes workspace/project/personal/managed/extra sources".
  • Contributing context: cron and heartbeat triggers already populate turn/start.collaborationMode.settings.developer_instructions in production. The generated @openai/codex 0.132.0 v2/TurnStartParams.ts does not currently declare collaborationMode (the formal basis for Keep Codex runtime context out of user history #84790's [P1] protocol concern), but the bundled runtime binary parses and honors the field on cron / heartbeat triggers today — empirical evidence below shows it also honors it on the chat trigger.

Security boundary

Trust-filter policy for the developer-instructions lane (turn/start.collaborationMode.settings.developer_instructions):

  • Allowed (elevated): skill entries whose resolveSkillSource(entry.skill) === "openclaw-bundled". Only the OpenClaw-bundled catalog ships shipped/reviewed SKILL.md content and is treated as developer authority alongside the workspace bootstrap files (fix(codex/app-server): forward workspace bootstrap into developerInstructions #77372). After resolveWorkspaceSkillPromptState in src/agents/skills/workspace.ts applies the shared applySkillsPromptLimits budget once over the combined promptSkills, the post-budget skillsForPrompt is partitioned by name into the trusted subset and rendered via buildLaneSkillsPrompt (XML shape from formatSkillsForPrompt / formatSkillsCompact) — identical byte shape to prompt, just restricted to the bundled entries.
  • Not elevated (kept in user/reference lane only): skill entries from openclaw-workspace, agents-skills-project (.agents/skills), agents-skills-personal (~/.agents/skills), openclaw-managed, openclaw-extra, plugin-generated, and any source not on the bundled allowlist. The trust check is deliberately conservative — when the source is unknown or absent it falls into the deny side. These entries are the untrusted half of the same post-budget partition and are rendered into SkillSnapshot.untrustedReferencePrompt via buildLaneSkillsPrompt; buildCodexOpenClawPromptContext emits them under an explicit ## OpenClaw User-Installed Skills (reference) section nested in the existing OpenClaw workspace context for this turn: wrapper. Wrapper text states the section is reference metadata for tool discovery, not developer authority.
  • Legacy session migration: SkillSnapshot.schemaVersion is stamped at every snapshot build (SKILL_SNAPSHOT_SCHEMA_VERSION = 3). The agent-command.ts reuse path runs isSkillsSnapshotSchemaOutdated(); snapshots whose schemaVersion is missing or below the current value (pre-PR v1 sessions; v2 sessions written by earlier commits on this branch before remoteNote was added) force-refresh through buildWorkspaceSkillSnapshot on the next turn so all four lane fields (trustedDeveloperPrompt, untrustedReferencePrompt, remoteNote, schemaVersion) are populated before the Codex call site reads them. Without this, the previous trust-filter HEAD would have silently dropped every skill (bundled or otherwise) from developer_instructions for existing sessions until a workspace bump or new session.
  • Remote-host execution guidance lane: SkillSnapshot.remoteNote (populated by buildWorkspaceSkillSnapshot from opts.eligibility.remote.note) rides the non-authoritative per-turn user-input lane under the OpenClaw Remote Skill Execution reference section (described in the Summary). It is not elevated to developer_instructions — the same per-PR boundary that applies to user-installed skills also applies to runtime-supplied invocation hints. A unit test pins this (run-attempt.test.ts "routes skillsSnapshot.remoteNote through the per-turn reference lane, not developer_instructions").
  • Shared budget invariant: maxSkillsPromptChars and maxSkillsInPrompt apply once over the combined catalog before the trusted/untrusted partition, so the model's combined view of skill content stays within the user's configured cap regardless of how the trust filter splits the catalog. A regression test pins this (skills.buildworkspaceskillsnapshot.test.ts "applies the configured maxSkillsPromptChars budget across the combined trusted/untrusted lanes, not per-lane"); we verified it FAILs with the legacy per-lane budgeting and PASSes with the shared budget.
  • Wire-level invariants pinned by regression tests:
    • developer_instructions carries only trust-filtered bundled skill descriptions/locations, even when an attacker controls workspace SKILL.md content (run-attempt.test.ts: "does not elevate untrusted skill metadata into Codex developer_instructions").
    • Per-turn user input under the workspace-context wrapper surfaces non-bundled skill descriptions/locations under the reference section so native Codex stays able to discover them (run-attempt.test.ts: same case + "omits skills from developer_instructions when no trusted skills are present but keeps untrusted skills in the reference lane"; run-attempt.test.ts: "falls back to the user-input prompt only when no skills lanes are populated" for the no-op baseline).
    • The SkillSnapshot producer renders the bundled and non-bundled subsets into disjoint fragments (skills.buildworkspaceskillsnapshot.test.ts: "trustedDeveloperPrompt includes bundled skills but excludes workspace/project/personal/managed/extra sources" + "untrustedReferencePrompt mirrors untrusted skill metadata for the reference lane" + "omits untrustedReferencePrompt when no non-bundled skills are present" + "stamps schemaVersion so legacy snapshots are force-refreshed").
    • The schema-version refresh predicate is correct across legacy / current / stale / future cases (snapshot-hydration.test.ts: 5 cases).
    • The llm_input observer, trajectory context.compiled.systemPrompt, and result.systemPromptReport.skills.{promptChars,entries} all reflect the trusted developer-lane bytes — not the full mixed catalog — so operators see the actual developer-lane size. The non-bundled bytes ride the per-turn user-input lane and are counted by Codex's input accounting separately.

Regression Test Plan

  • Coverage level that should have caught this:
    • Unit test
  • Target test or file:
    • extensions/codex/src/app-server/thread-lifecycle.test.ts — 6 cases for cron / heartbeat / chat / authority invariant.
    • extensions/codex/src/app-server/run-attempt.test.ts — existing routes OpenClaw skills through turn collaboration developer_instructions, not user input updated to use trustedDeveloperPrompt; 4 new cases: does not elevate untrusted skill metadata into Codex developer_instructions, omits skills from developer_instructions when no trusted skills are present but keeps untrusted skills in the reference lane, falls back to the user-input prompt only when no skills lanes are populated, routes skillsSnapshot.remoteNote through the per-turn reference lane, not developer_instructions.
    • extensions/codex/src/app-server/run-attempt.context-engine.test.ts — 1 context-engine budget assertion updated to use trustedDeveloperPrompt.
    • src/agents/skills.buildworkspaceskillsnapshot.test.ts — 8 new cases (4 lane-filter + 1 schema-version stamping + 2 remote-note + 1 shared-budget): trustedDeveloperPrompt includes bundled skills but excludes workspace/project/personal/managed/extra sources, omits trustedDeveloperPrompt when no bundled skills are present, untrustedReferencePrompt mirrors untrusted skill metadata for the reference lane, omits untrustedReferencePrompt when no non-bundled skills are present, stamps schemaVersion so legacy snapshots are force-refreshed, persists eligibility.remote.note as snapshot.remoteNote for the Codex reference lane, omits remoteNote when no remote eligibility is configured, applies the configured maxSkillsPromptChars budget across the combined trusted/untrusted lanes, not per-lane.
    • src/agents/skills/snapshot-hydration.test.ts — 5 new cases for isSkillsSnapshotSchemaOutdated: returns false when there is no persisted snapshot at all, treats a legacy snapshot with no schemaVersion as outdated, treats a snapshot with schemaVersion older than the current version as outdated, treats a snapshot at the current schemaVersion as fresh, treats a snapshot at a future schemaVersion as fresh (forward compat).
    • Prompt-snapshot helper/check: test/helpers/agents/happy-path-prompt-snapshots.ts, test/scripts/prompt-snapshots.test.ts.
  • Scenario the test should lock in: (a) chat trigger renders trusted bundled skills as developer_instructions; (b) chat trigger without skills returns null developer_instructions; (c) cron composes cron + skills; (d) heartbeat composes heartbeat + overlay + skills; (e) cron without skills is byte-identical to current main; (f) workspace user-editable context never reaches developer_instructions (authority invariant); (g) untrusted skill metadata (workspace, project, personal, managed, extra) never reaches developer_instructions, even when skillsSnapshot.prompt carries it (prompt-authority boundary); (h) untrusted skill metadata remains visible to Codex through the per-turn user input under the reference wrapper (visibility-preserving fix for the post-trust-filter regression); (i) buildWorkspaceSkillSnapshot partitions skills into disjoint trusted/untrusted fragments and stamps schemaVersion; (j) legacy snapshots without schemaVersion force-refresh; (k) context-engine / prompt-snapshot surfaces report the workspace-only turn-input projection rather than the old runtime-context wrapper.
  • Why this is the smallest reliable guardrail: each bug is structural (wrong lane plus wrong trust scope plus stale-snapshot reuse); the structural invariants pin all four halves (bundled skills present in developer_instructions, workspace absent from it, untrusted skill metadata absent from it, non-bundled skills present in the reference lane, legacy snapshots refreshed) without needing live-model evidence to rerun on every CI tick.
  • If no new test is added, why not: N/A.

User-visible / Behavior Changes

  • Per-turn token billing on the default main agent (new turns after this PR ships): the bundled subset of the skills snapshot no longer re-bills in every response.create.input; the cumulative 10-turn prompt_tokens cost drops by 24% on the ping-pong scenario in the Real-behavior proof. The non-bundled subset (workspace / project / personal / managed / extra / plugin-generated) continues to re-bill at the pre-fix(codex): stop persisting per-turn OpenClaw skills snapshot in Codex native user history (#84662) #85646 rate because it is intentionally kept in the per-turn user-input lane for prompt-authority reasons (see Limitations). Workspace-context bytes continue to re-bill at the same rate as before (+540/turn floor).
  • Per-turn user-input wrapper text (new turns): renamed from OpenClaw runtime context for this turn:\n… to OpenClaw workspace context for this turn:\n…. The block now contains (a) the existing ## OpenClaw Workspace Context section, and (b) when any non-bundled skill is eligible, a new ## OpenClaw User-Installed Skills (reference) section listing those skill names/descriptions/locations under a reference-only header.
  • Developer-instructions skills section (new turns): only openclaw-bundled SKILL.md descriptions/locations appear here. SKILL.md from workspace, project, personal, openclaw-managed, openclaw-extra, and plugin-generated sources remains discoverable via the per-turn user-input reference section (visibility-preserving); it is never elevated to the developer-instructions lane.
  • Existing sessions opened before this PR ships: the first turn after upgrade rebuilds the skills snapshot via buildWorkspaceSkillSnapshot so the new trustedDeveloperPrompt and untrustedReferencePrompt fields are populated; subsequent turns reuse the persisted snapshot in the normal way. Without this migration, the previous trust-filter HEAD would have silently dropped every skill from developer_instructions on those sessions until a workspace bump or new session.
  • Existing Codex native threads bound before this PR ships: see "Limitations of this PR" below.
  • Snapshot fixtures: three test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/*.md files regenerated to reflect the wrapper subline update.

Limitations of this PR (deferred half explicitly disclosed)

This PR prevents future bundled-skills bytes from being appended to Codex native user history. It does not sanitize history for threads that were bound before the fix ships, and it does not eliminate per-turn user-history persistence of non-bundled SKILL.md content.

  • Non-bundled skills still ride the per-turn user-input lane, by policy. Their SKILL.md descriptions/locations re-bill on every subsequent response.create.input and are persisted to native Codex user history — the same behavior as before fix(codex): stop persisting per-turn OpenClaw skills snapshot in Codex native user history (#84662) #85646 for those entries. The alternative (elevating them to developer_instructions) was rejected as a prompt-authority regression by the round-2 ClawSweeper review; this PR keeps the visibility while explicitly disclosing the per-turn replay cost for non-bundled-heavy catalogs. Catalogs that are predominantly bundled (e.g. default OpenClaw installs) see the full ~24% cumulative token-savings benchmark below; catalogs with a non-trivial non-bundled subset see proportionally less savings on that subset.
  • Existing bound Codex native threads that already contain OpenClaw runtime context for this turn: user-history items from prior turns will continue to replay those items on response.create.input until either (a) the thread cycles to a fresh native session, or (b) the deferred follow-up session-history sanitizer (issue [Bug]: Codex app-server stores per-turn OpenClaw runtime context in native user history, causing runaway response.create input growth #84662 §"Safe interim fix") lands as a stacked follow-up PR that strips the wrapper from readCodexMirroredSessionHistoryMessages.
  • The snapshot-fixture check (workspaceBootstrapContextFrom field in test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/*.md) verifies the current projection shape for new turns; it is not a regression guard for the deferred sanitizer half — old mirrored-history user items are out of its scope.
  • The 10-turn benchmark below was run at the prior trust-filter HEAD (66ee52173e, when the developer lane carried the full mixed-source catalog) with fresh user IDs. The current-head benchmark uplift on the trusted (bundled) developer lane is a strict subset of those gains — fewer bytes, identical wire shape, byte-stable across turns — so the cacheable / no-history-replay properties documented there continue to hold for the bundled subset. The non-bundled subset's per-turn replay cost matches the pre-fix(codex): stop persisting per-turn OpenClaw skills snapshot in Codex native user history (#84662) #85646 baseline for that subset.
  • Codex automatic compaction is Codex-owned. Upstream Fail Codex compaction at the Codex boundary #85958 ("Fail Codex compaction at the Codex boundary") removed the OpenClaw-owned preflight/precheck compaction wiring from extensions/codex/src/app-server/run-attempt.ts. After rebase onto current upstream/main, this PR no longer claims or tests OpenClaw preflight compaction accounting for the skills lane (an earlier "count collaboration skills in preflight estimate" commit was dropped during the rebase as semantically obsolete).

The deferred follow-up will credit Co-authored-by: TurboTheTurtle (PR #84790's sanitizer logic) and is independent of this PR; this PR remains complete and merge-ready on its own.

Authority safety (why this is not the #84790 design)

PR #84790 (CLOSED 2026-05-22) This PR
Content moved into developer_instructions skills + workspace + MEMORY trust-filtered bundled skills only
Skill source policy full mixed-source catalog (bundled + workspace + project + personal + managed + extra + plugin) elevated openclaw-bundled only; workspace / project / personal / managed / extra / plugin SKILL.md stays in user/reference lane under an explicit reference section header
Non-bundled skill visibility implicit (they rode the same developer lane) explicit reference-lane wrapper, visible to native Codex without developer authority
Workspace / MEMORY routing through developer_instructions (with a disclaimer wrapper) unchanged from current main — stays in turn-input reference lane established by #83454
Session-state compatibility session snapshots assumed to carry the new fields SkillSnapshot.schemaVersion migration force-refreshes pre-PR snapshots so the new fields are populated on the next turn
Session-history sanitization bundled in same PR deferred follow-up (disclosed above)
Protocol-acceptance argument schema inspection only schema + production cron / heartbeat parity + wire-level Codex native rollout + cacheRead ratio uplift on the same scenario
Authority invariant test n/a three unit tests pin all three halves: workspace text never appears in developer_instructions, untrusted skill metadata never appears in developer_instructions, and untrusted skill metadata still appears in the per-turn user-input reference lane

Reading order:

Real behavior proof

This PR carries two pieces of real-behavior evidence:

  1. A historical 10-turn live OpenAI Codex benchmark captured at the prior trust-filter HEAD (66ee52173e, when the developer lane carried the full mixed-source skills catalog). The benchmark established the no-history-replay, byte-stable, cacheRead-uplift properties of the new lane.
  2. A current-head wire-level proof captured against the production pipeline at the head SHA of this PR. It records byte counts, sha256-12 hashes, and contains/does-not-contain assertions against synthetic marker strings (no live secrets, no private paths, no MEMORY content) for the trusted developer lane and the non-bundled reference lane, plus the legacy-snapshot refresh decision. The full numeric evidence is inlined under Current-head wire-level proof below. The generator script and its generated doc were removed from the branch per ClawSweeper P3 (PR-only proof artifacts should not ship); the structural invariants they captured are pinned by src/agents/skills.buildworkspaceskillsnapshot.test.ts and src/agents/skills/snapshot-hydration.test.ts.

The current-head trusted developer lane is a strict reduction of the bytes the historical benchmark sent (filter to bundled-only), so the historical benchmark's no-history-replay and byte-stability properties carry forward unchanged for the bundled subset. The non-bundled subset re-enters the per-turn user input lane under an explicit reference wrapper; its per-turn token cost matches the pre-#85646 baseline for that subset and is disclosed under Limitations.

Historical 10-turn live benchmark (at 66ee52173e)

Behavior addressed: Codex app-server persists the OpenClaw skills snapshot as a per-turn user-history item in native Codex threads, causing the model's response.create.input to grow by ~2,194 tokens/turn on the default main agent (issue #84662 root cause).

Real environment tested: OpenClaw checkout at the upstream/main HEAD 66ee52173e was based on, rebuilt dist; live OpenAI Codex backend (openai-codex/gpt-5.4-mini); two local OpenAI-compatible OpenClaw gateways on separate ports sharing the same eval state directory (one unpatched baseline, one with this PR's patch applied); a live 10-turn ping-pong benchmark as the proof surface. A separate live runtime instance on an unrelated port was observed before / during / after the experiment via /healthz to confirm no PID change in unrelated processes.

Exact steps or command run after this patch:

  • node scripts/build-all.mjs
  • Start two OpenClaw gateways on separate ports against an eval OPENCLAW_STATE_DIR, one built from current upstream/main (arm A — baseline) and one built from this PR's branch (used for arms A' and B), each launched via node scripts/run-node.mjs gateway with OPENCLAW_SKIP_CHANNELS=1.
  • Drive a 10-turn body_contains: "pong" ping-pong scenario against each gateway via an OpenAI-compatible benchmark CLI, using a distinct user ID per arm (forces a fresh Codex native session per arm) for three arms:

Evidence after fix (10-turn live benchmark × 3 arms, all 30/30 functional body_contains: "pong"):

Arm growth/turn turn 1 / turn 10 prompt_tokens cum 10t prompt_tokens cacheRead/input (turn 9 steady) uncached input tokens (turn 9) skills.count / promptChars
A — unpatched baseline (#84662 reproducible state) +2,194 21,286 / 41,032 311,590 93.27 % 2,614 20 / 6,629
A' — patched +535 21,166 / 25,981 235,735 96.08 % 998 20 / 6,557
B — no-skills control (patched gateway, no-skills agent) +540 19,552 / 24,412 219,820 95.98 % 960 0 / 0

All three arms used fresh user IDs so each arm opened a new Codex native session — the patched-arm curve reflects the new-thread behavior, not the legacy-thread replay floor. Per the "Limitations" section above, legacy bound threads are out of scope for this proof.

  • Per-turn growth on the default agent drops from +2,194 to +535 tokens/turn (−75.6 %); cumulative 10-turn save = −75,855 tokens (−24.3 %) vs the unpatched baseline.
  • Arm B's no-skills floor (+540/turn) is within ±5 tokens/turn of arm A' — confirming the +535/turn residual on the patched arm is the workspace-context replay floor, not skills.
  • Codex native rollout for the patched arm shows turn/start.collaborationMode.settings.developer_instructions populated with a byte-stable payload (md5 stable across all 10 turns at the historical HEAD; the current-head trusted-developer fragment is a strict reduction of those bytes so md5 stability properties carry forward).

Latency: trimmed mean −448 ms (−8.8 %) on the patched arm vs the baseline arm (5,102 → 4,654 ms after dropping hi/lo across n=10), both arms dominated by a single turn-1 cold-start outlier (A: 26,862 ms, A': 22,453 ms). No functional regression. We do not claim latency improvement at n=10; a 50-turn rerun would be the right place to make a stronger latency claim.

Observed result after fix: per-turn prompt_tokens growth on the default main agent drops from +2,194 → +535 tokens/turn (−75.6 %), within ±5 tokens/turn of the no-skills control (+540). Cumulative 10-turn prompt_tokens saves −75,855 (−24.3 %) vs the unpatched baseline. 30 / 30 functional body_contains: "pong" success across the 3 arms. developer_instructions is byte-stable across all 10 turns on the patched arm; workspace / MEMORY text never appears in developer_instructions (verified at the wire level and as a unit-test structural invariant). No functional regression observed.

Current-head wire-level proof

Captured against a synthetic workspace fixture with one skill per source (openclaw-bundled, openclaw-workspace, agents-skills-project, openclaw-managed, openclaw-extra) and a MEMORY-marker workspace-context fragment. No live secrets, no private paths, no MEMORY content from a real workspace. The generator script and the generated artifact have been removed from the branch (ClawSweeper P3 cleanup); the numbers below are the captured proof, and the structural invariants remain covered by src/agents/skills.buildworkspaceskillsnapshot.test.ts and src/agents/skills/snapshot-hydration.test.ts.

Built snapshot summary:

Field Bytes sha256-12
prompt (full availability list) 1838 11449a4c52cf
trustedDeveloperPrompt (bundled-only, developer lane) 601 a7031833fc6b
untrustedReferencePrompt (non-bundled, reference lane) 1605 11c379ff6687
Reconstructed Codex turn-input wrapper 2350 22e996bb5135

Skill count (eligible): 6.

Wire-level invariant — Codex developer_instructions skills lane (11/11 PASS): MUST contain bundled-trusted and BUNDLED-TRUSTED-MARKER-OK-FOR-DEVELOPER-LANE; MUST NOT contain any of WORKSPACE-USER-INSTALLED-MARKER-REFERENCE-ONLY, PROJECT-AGENTS-MARKER-REFERENCE-ONLY, MANAGED-INSTALL-MARKER-REFERENCE-ONLY, EXTRA-DIR-MARKER-REFERENCE-ONLY, USER-EDITABLE-MEMORY-MARKER-MUST-NOT-RIDE-DEVELOPER-LANE, workspace-helper, project-helper, managed-helper, extra-helper.

Wire-level invariant — Codex per-turn user-input reference lane (12/12 PASS): MUST contain ## OpenClaw User-Installed Skills (reference), each non-bundled skill name and marker, and the workspace MEMORY marker; MUST NOT contain bundled-trusted or its marker.

Legacy snapshot refresh (ClawSweeper P1b): isSkillsSnapshotSchemaOutdated returns true for legacy snapshots (no schemaVersion) → force-refresh; returns false for current snapshots (schemaVersion=3) → reuse. Both branches covered by src/agents/skills/snapshot-hydration.test.ts.

Total: 23/23 PASS, 0 FAIL.

What was not tested:

  • A re-run of the 10-turn live benchmark against the current trust-filter HEAD. The change since 66ee52173e is a strict reduction of bytes on the developer lane (filter to bundled-only) plus a non-authoritative addition to the reference lane; it does not change the wire shape, the byte-stability across turns, or the no-history-replay property the historical proof established for the trusted subset. The unit tests above and the current-head wire artifact pin the structural invariants the live benchmark would re-establish.
  • Long-session 50 / 100-turn scaling under this change.
  • Workspace-file mid-session edit cache-bust behaviour (workspace was static across the historical ~30 s experiment).
  • Out-of-sample models (only openai-codex/gpt-5.4-mini was exercised in the historical benchmark).
  • Live Discord / Telegram production-channel turn (the OpenAI-compatible gateway was the historical proof surface, not a channel).
  • Legacy bound Codex native threads that contain pre-fix OpenClaw runtime context for this turn: user-history items — by design (see "Limitations of this PR"). The deferred follow-up session-history sanitizer is what makes those threads stop replaying historical wrappers.
  • Session-history sanitization itself, including the readCodexMirroredSessionHistoryMessages post-processing path — out of scope for this PR (deferred to stacked follow-up).
  • skills.promptChars drifted by 72 chars between the two historical arms (6,629 vs 6,557) due to a bundled-plugin asset rebuild difference between the two checkouts, not the source patch; skills.entries.count is 20 / 20 in both arms and the same skill names appear in both arms' Codex native rollouts.
  • A single turn-10 OpenAI cache-eviction anomaly on the historical patched arm reported cached_input_tokens=10,624 (turn-1-like) and uncached=15,357 against the byte-stable developer_instructions payload (md5 stable); turns 2–9 each showed ~96.1 % cache rate and the steady-state quoted above uses turn 9. The headline per-turn growth and cumulative prompt_tokens metrics are unaffected.

Validation

node scripts/run-vitest.mjs extensions/codex/src/app-server/run-attempt.test.ts --run
node scripts/run-vitest.mjs extensions/codex/src/app-server/thread-lifecycle.test.ts --run
node scripts/run-vitest.mjs extensions/codex/src/app-server/run-attempt.context-engine.test.ts --run
node scripts/run-vitest.mjs src/agents/skills.buildworkspaceskillsnapshot.test.ts --run
node scripts/run-vitest.mjs src/agents/skills/snapshot-hydration.test.ts --run
node scripts/run-vitest.mjs test/scripts/prompt-snapshots.test.ts --run
node --import tsx scripts/generate-prompt-snapshots.ts --check
pnpm prompt:snapshots:check
pnpm check:changed

Local results captured at content HEAD 559eed5dfde7eb8ea38668470b9ddac10d3be525:

  • extensions/codex/src/app-server/{thread-lifecycle,run-attempt,run-attempt.context-engine}.test.ts — 282/282 tests passed.
  • src/agents/skills.buildworkspaceskillsnapshot.test.ts — 17/17 tests passed (8 new: 4 lane-filter + 1 schema-version stamping + 2 remote-note + 1 shared-budget).
  • src/agents/skills/snapshot-hydration.test.ts — 5/5 tests passed.
  • src/agents/agent-command.live-model-switch.test.ts — 23/23 tests passed (1 new force-rebuilds legacy persisted skill snapshots).
  • test/scripts/prompt-snapshots.test.ts — 10/10 tests passed.
  • pnpm prompt:snapshots:check — Prompt snapshots are current (7 files).
  • pnpm check:changed — exit 0 (typecheck, lint, import cycles, shrinkwrap, package patch, runtime sidecar loader guards, media download helper guard all green).
  • Current-head wire-level proof artifact: 23 PASS / 0 FAIL; legacy snapshot decision true / current snapshot decision false.

CI re-runs against the clean-reconstruction head 559eed5dfde7eb8ea38668470b9ddac10d3be525 (force-push at 2026-05-29; current run https://github.com/openclaw/openclaw/actions/runs/26583420787); the pre-rebase capture above was green at the prior content head.

Follow-up planned (separate stacked PR)

Session-history sanitizer for already-bound Codex native threads that already carry legacy OpenClaw runtime context for this turn: user-history items. Implements readCodexMirroredSessionHistoryMessages post-processing per issue #84662 §"Safe interim fix". Builds on the sanitizer logic PR #84790 contributed; will credit Co-authored-by: TurboTheTurtle. Independent of this PR; this PR remains complete and merge-ready on its own.

@openclaw-barnacle openclaw-barnacle Bot added extensions: codex size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 23, 2026
@clawsweeper

clawsweeper Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed May 28, 2026, 6:05 PM ET / 22:05 UTC.

Summary
The PR splits Codex skills snapshot routing so bundled skills move to turn-scoped developer_instructions, while non-bundled skills, remote notes, and workspace context remain in per-turn reference input with schema-versioned snapshot refresh.

PR surface: Source +316, Tests +982. Total +1298 across 23 files.

Reproducibility: yes. for the scoped skills component: current main visibly passes skillsSnapshot.prompt into the Codex turn-input wrapper, and the PR body supplies live benchmark plus wire-level lane proof. I did not run a fresh live multi-turn Codex benchmark in this read-only pass.

Review metrics: 2 noteworthy metrics.

  • Persisted skills snapshot surface: 1 schema marker added, 3 optional fields added. Stored session snapshot shape changes affect upgrade and reuse behavior for existing sessions.
  • Snapshot reuse paths: 3 reuse paths changed. Agent-command, channel reply, and cron reuse now force-refresh stale schema snapshots, directly affecting existing sessions.

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

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

Rank-up moves:

  • Resolve the dirty merge state against current main.
  • [P2] Have maintainers explicitly accept or reject the bundled-skill developer-instructions trust boundary.

Risk before merge

  • [P1] The PR intentionally changes Codex prompt authority by elevating bundled skill metadata into turn-scoped developer_instructions; maintainers need to accept that trust boundary as product policy.
  • [P1] The PR changes persisted skills snapshot shape and three existing-session reuse predicates, so upgrade behavior depends on the schema refresh paths staying aligned across agent-command, channel reply, and cron.
  • [P1] The parent issue remains only partially addressed because historical decorated user-history wrappers and workspace/MEMORY accumulation are explicitly deferred to follow-up work.
  • [P1] The branch is currently dirty against main and overlaps an open related context-routing PR, so it needs rebase/coordination before any merge decision.

Maintainer options:

  1. Rebase and re-run scoped Codex proof (recommended)
    Resolve the dirty merge state, then confirm the skills-lane and snapshot-reuse tests still pass on current main before any landing decision.
  2. Land as a scoped phase
    Maintainers can accept the bundled-only developer lane and schema refresh behavior while leaving the historical replay sanitizer tracked separately.
  3. Defer to a broader routing PR
    Maintainers can pause this PR only if a broader replacement becomes clean, proof-positive, and explicitly preserves this PR's trust-filtered behavior.

Next step before merge

  • [P2] Human maintainer review is needed because the remaining blockers are prompt-authority policy, session-upgrade risk acceptance, and dirty-branch coordination rather than a narrow automated repair.

Security
Cleared: No concrete security or supply-chain issue was found in the diff; the prompt-authority boundary is tracked as maintainer merge risk.

Review details

Best possible solution:

Land a cleanly rebased scoped skills-lane fix after maintainers accept the bundled-skill authority and session-upgrade boundary, while keeping the parent sanitizer work open for historical decorated Codex user-history replay.

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

Yes for the scoped skills component: current main visibly passes skillsSnapshot.prompt into the Codex turn-input wrapper, and the PR body supplies live benchmark plus wire-level lane proof. I did not run a fresh live multi-turn Codex benchmark in this read-only pass.

Is this the best way to solve the issue?

Yes for the scoped skills-lane problem, but not for the whole parent issue. The trusted bundled lane plus untrusted reference lane is a maintainable boundary; the historical decorated-wrapper sanitizer remains required follow-up work, and the open related PR is not yet a safe superseder.

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 39db00f896c6.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix real behavior proof via live-output benchmark and current-head wire-level lane evidence, so no contributor proof action is needed.

Label justifications:

  • P2: This is a normal-priority Codex session-state and prompt-cost fix with meaningful but bounded runtime impact.
  • merge-risk: 🚨 compatibility: The PR changes where Codex receives skills prompt content and adds a persisted snapshot schema marker used during upgrades.
  • merge-risk: 🚨 session-state: The PR changes how existing sessions reuse or rebuild stored skills snapshots and intentionally leaves historical Codex history sanitization for follow-up work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 real behavior proof via live-output benchmark and current-head wire-level lane evidence, so no contributor proof action is needed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix real behavior proof via live-output benchmark and current-head wire-level lane evidence, so no contributor proof action is needed.
Evidence reviewed

PR surface:

Source +316, Tests +982. Total +1298 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 10 342 26 +316
Tests 13 1033 51 +982
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 23 1375 77 +1298

What I checked:

  • Repository policy read and applied: Root AGENTS.md was read fully; its ClawSweeper review policy treats provider routing, auth/session state, persisted preferences, config/defaults, startup checks, and fallback behavior as compatibility-sensitive review surfaces. (AGENTS.md:21, 39db00f896c6)
  • Scoped guides read: The touched extension, agent, and shared prompt-snapshot helper surfaces have scoped AGENTS.md guidance; no scoped policy created a line-level defect, but the guidance reinforced boundary and compatibility review. (extensions/AGENTS.md:1, 39db00f896c6)
  • Current main still persists skills through turn input: Current main's Codex prompt-context builder accepts skillsPrompt, renders it under ## OpenClaw Skills, and wraps it in OpenClaw runtime context for this turn, so the central PR behavior is not already implemented on main. (extensions/codex/src/app-server/attempt-context.ts:548, 39db00f896c6)
  • Current main passes the mixed snapshot into that wrapper: Current main calls buildCodexOpenClawPromptContext with skillsPrompt: params.skillsSnapshot?.prompt, which keeps the full mixed skills snapshot on the native Codex user-input path. (extensions/codex/src/app-server/run-attempt.ts:645, 39db00f896c6)
  • PR head routes trusted skills out of turn input: At the reviewed PR head, Codex derives the developer lane from skillsSnapshot.trustedDeveloperPrompt, leaves untrusted skills and remote notes in the reference wrapper, and stops consuming the legacy mixed skillsSnapshot.prompt in this Codex call path. (extensions/codex/src/app-server/run-attempt.ts:646, 559eed5dfde7)
  • PR head adds the turn-scoped skills lane: At the reviewed PR head, buildTurnStartParams accepts openClawSkillsPrompt, and buildTurnScopedCollaborationInstructions formats it into collaborationMode.settings.developer_instructions for chat, cron, and heartbeat turns. (extensions/codex/src/app-server/thread-lifecycle.ts:911, 559eed5dfde7)

Likely related people:

  • steipete: Current-main blame on the Codex prompt-context helper and the run-attempt call that passes skillsSnapshot.prompt points to commit ccf3476. (role: recent area contributor; confidence: medium; commits: ccf3476a4aec, 39db00f896c6; files: extensions/codex/src/app-server/attempt-context.ts, extensions/codex/src/app-server/run-attempt.ts, extensions/codex/src/app-server/thread-lifecycle.ts)
  • 100yenadmin: Merged prompt-surface split work in Separate prompt surfaces by selected harness #83454 established the Codex developer-instructions/reference-lane boundary this PR builds on. (role: feature-history contributor; confidence: medium; commits: 2a0350b5b490; files: extensions/codex/src/app-server/run-attempt.ts, extensions/codex/src/app-server/thread-lifecycle.ts)
  • lonexreb: Merged fix(codex/app-server): forward workspace bootstrap into developerInstructions #77372 moved workspace bootstrap into Codex developerInstructions and is the lane precedent cited by this PR. (role: adjacent feature contributor; confidence: medium; commits: 9edeffc751e1; files: extensions/codex/src/app-server/run-attempt.ts, extensions/codex/src/app-server/thread-lifecycle.ts)
  • pashpashpash: Merged Codex compaction boundary work in Fail Codex compaction at the Codex boundary #85958 is recent adjacent session-state work in the same Codex runtime area. (role: recent adjacent contributor; confidence: medium; commits: dd47e479aedb; files: extensions/codex/src/app-server/compact.ts, test/helpers/agents/happy-path-prompt-snapshots.ts, src/gateway/server.sessions.compaction.test.ts)
  • Patrick-Erichsen: Recent skill source install-alias work is adjacent to this PR's trusted-versus-untrusted skill source partition. (role: recent skills-source contributor; confidence: low; commits: 24d58af56059; files: src/agents/skills/workspace.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 proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 23, 2026
@clawsweeper

clawsweeper Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

✨ Hatched: 🌱 uncommon Velvet Lint Imp

Hatch command

Comment @clawsweeper hatch when this PR is hatchable.

Hatchability rules:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.

Rarity: 🌱 uncommon.
Trait: keeps receipts.
Image traits: location proof lagoon; accessory miniature diff map; palette amber, ink, and glacier blue; mood sparkly; pose sitting proudly on a smooth stone; shell soft velvet shell; lighting tiny status-light glow; background subtle branch markers.
Share on X: post this hatch
Copy: My PR egg hatched a 🌱 uncommon Velvet Lint Imp in ClawSweeper.

What is this egg doing here?
  • Eggs appear after the PR passes real-behavior proof. It is here for vibes, not verdicts: it does not change labels, ratings, merge decisions, or automation.
  • The shell reacts to review momentum: open follow-up work warms it up, re-review makes it wobble, and a clean final review lets it hatch.
  • Hatchability usually comes from sufficient real-behavior proof, no blocking P0/P1/P2 findings, no security attention needed, and clean correctness. A merged PR is already final, so merge makes the egg hatchable independently.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels May 23, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 23, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 23, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 23, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 23, 2026
@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels May 23, 2026
@masatohoshino
masatohoshino force-pushed the feature/codex-skills-developer-instructions branch from 41442a9 to 8676436 Compare May 23, 2026 09:15
@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 24, 2026
@masatohoshino

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@masatohoshino

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@martingarramon martingarramon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the three post-review commits (e1c36882 → 544a3e14). remoteNote threading fixes the P2 regression: eligibility.remote.note now flows through snapshot → run-attempt.ts using the same optional-spread pattern as trustedDeveloperPrompt. The schema bump is v2→v3 for the additive field.

Budget sharing is correct: isTrustedDeveloperSkillEntry filters the pre-budgeted skillsForPrompt set, preventing each lane from consuming the full limit independently. Test coverage looks clean. LGTM on the new commits.

@masatohoshino

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@BingqingLyu

This comment was marked as spam.

…x native user history (openclaw#84662)

The OpenClaw skills snapshot was wrapped into `turn/start.input` and
persisted as a user-history item in native Codex threads, so the bytes
were re-billed on every subsequent `response.create.input` (~+2,194
tokens/turn on the default `main` agent in a 10-turn reproduction).

Route the skills snapshot through
`turn/start.collaborationMode.settings.developer_instructions` — the same
field cron and heartbeat triggers already populate in production — via a
new `openClawSkillsPrompt` option threaded through `buildTurnStartParams`
→ `buildTurnCollaborationMode` → `buildTurnScopedCollaborationInstructions`.
`buildCodexOpenClawPromptContext` now emits the workspace section only,
and its per-turn wrapper is renamed from `OpenClaw runtime context for
this turn:` to `OpenClaw workspace context for this turn:` so the
user-input lane is correctly labelled.

User-editable workspace context (including the MEMORY marker) intentionally
stays in the turn-input reference lane, complementing openclaw#83454. A new unit
invariant in `thread-lifecycle.test.ts` pins that workspace text never
appears in `developer_instructions`. Historical-session sanitization for
already-bound Codex native threads (Option C-b in issue openclaw#84662 §"Safe
interim fix") is out of scope for this PR and deferred to a stacked
follow-up.

Closes openclaw#84662 for the skills component of the preferred-fix half only.
After openclaw#85646 moved the OpenClaw skills snapshot from `turn/start.input` to
`turn/start.collaborationMode.settings.developer_instructions`, the
`llm_input` hook, the trajectory recorder, and the system prompt report
continued to pass only `promptBuild.developerInstructions` as the system
prompt. Trusted plugins observing `llm_input` (documented in
`docs/plugins/hooks.md` as observing provider input) and trajectory
consumers therefore lost visibility into the new model-visible skills
lane, while the model itself still received those bytes.

Hoist the turn-scoped collaboration developer_instructions string that
`buildTurnStartParams` will send (it depends only on the stable skills
snapshot, heartbeat instructions, and trigger), and expose a single
`buildCombinedCodexDeveloperInstructions` helper that composes it with
the current `promptBuild.developerInstructions`. Use the same helper for
the provider-boundary precheck, `buildCodexSystemPromptReport`,
`createCodexTrajectoryRecorder`, `recordCodexTrajectoryContext`, and
`buildLlmInputEvent`, so every observation surface mirrors the
model-visible system prompt instead of only the base lane.

Extend the existing `routes OpenClaw skills through turn collaboration
developer_instructions` test to assert that the `llm_input.systemPrompt`,
the trajectory `context.compiled.systemPrompt`, and the system prompt
report's `systemPrompt.chars`/`nonProjectContextChars` now include the
`## OpenClaw Skills` section, while the workspace turn-input wrapper
never appears in those observed system-prompt surfaces. The
`thread-lifecycle.test.ts` invariant pinning workspace user-editable text
out of `developer_instructions` continues to bound this for the source
payload.
…undled skills

ClawSweeper's prompt-authority review of PR openclaw#85646 flagged that the moved
skills payload still wraps the full mixed-source SkillSnapshot.prompt, so
workspace, project (.agents/skills), personal (~/.agents/skills),
openclaw-managed, openclaw-extra, and plugin-generated SKILL.md frontmatter
descriptions/locations would gain Codex developer-instruction authority on
every chat turn after the lane move.

Add SkillSnapshot.trustedDeveloperPrompt that buildWorkspaceSkillSnapshot
populates by filtering the prompt-visible entries to source ===
'openclaw-bundled' and rendering them through the same compactSkillPaths /
applySkillsPromptLimits / formatSkillsForPrompt pipeline as the full prompt.
Untrusted entries stay reachable via SkillSnapshot.prompt for the
user/reference lane but are dropped from the trusted lane.

Switch extensions/codex/src/app-server/run-attempt.ts to source
codexSkillsPrompt from skillsSnapshot.trustedDeveloperPrompt so that
collaborationMode.settings.developer_instructions only carries trusted
bundled-skill metadata. The provider-boundary precheck, llm_input observer,
trajectory recorder, and system prompt report continue to mirror the actual
developer-instruction bytes via buildRenderedCodexDeveloperInstructions().

Add regression coverage:
- run-attempt.test.ts pins that workspace/extra/managed/project SKILL.md
  marker text and skill names never appear in turnStart developer_instructions
  even when skillsSnapshot.prompt carries them, and that the system prompt
  report's skills entries count trusted-only bytes.
- run-attempt.test.ts also pins the no-trusted-skills fallback so untrusted
  workspace catalogs do not synthesize an '## OpenClaw Skills' section.
- skills.buildworkspaceskillsnapshot.test.ts pins that the trusted prompt
  fragment includes bundled descriptions/locations and excludes every
  untrusted source listed by the trust policy.
ClawSweeper P1a: After the prior trust-filter restricted Codex
`developer_instructions` to bundled-only skills, native Codex stopped
seeing workspace, project (.agents/skills), personal
(~/.agents/skills), `openclaw-managed`, `openclaw-extra`, and
plugin-generated skills entirely. Eligible skills are documented as a
first-class catalog (`docs/concepts/system-prompt.md`), so silently
dropping them broke discovery for existing custom skills.

ClawSweeper P1b: Sessions persisted before the lane-split fields existed
carry only `prompt` + `resolvedSkills`. The agent-command reuse path
previously hydrated those snapshots as-is, leaving
`trustedDeveloperPrompt` undefined and dropping every skill from
`developer_instructions` until a workspace bump or new session.

Add a second prompt fragment, `SkillSnapshot.untrustedReferencePrompt`,
built by `buildWorkspaceSkillSnapshot` from the non-bundled subset of
`promptEntries`. Render it via the existing `compactSkillPaths` /
`applySkillsPromptLimits` / `formatSkillsForPrompt` pipeline so the
reference lane uses the same XML shape as the full prompt.
`buildCodexOpenClawPromptContext` now emits a non-authoritative
`## OpenClaw User-Installed Skills (reference)` section under the
existing `OpenClaw workspace context for this turn:` wrapper when that
fragment is present, with explicit reference-only wrapper text so the
model does not treat its content as developer authority.

Add `SkillSnapshot.schemaVersion` (constant
`SKILL_SNAPSHOT_SCHEMA_VERSION = 2`) and the
`isSkillsSnapshotSchemaOutdated` helper. The agent-command reuse path
runs the helper alongside the existing version / filter checks; legacy
snapshots whose `schemaVersion` is missing or below the current shape
force-refresh through `buildWorkspaceSkillSnapshot` so the two
lane-split fields are populated before reuse. Snapshots at a future
schema version do not loop on refresh.

`SessionSkillSnapshot` mirrors the three new fields so they round-trip
through session persistence. `resolvedSkills` remains runtime-only.

Wire-level invariants pinned by tests:
- `run-attempt.test.ts` "does not elevate untrusted skill metadata
  into Codex developer_instructions" now asserts that the untrusted
  workspace skill name / description / location appear in the
  per-turn user-input reference lane but never in
  `developer_instructions` or in the system-prompt observer surface.
- `run-attempt.test.ts` "omits skills from developer_instructions
  when no trusted skills are present but keeps untrusted skills in
  the reference lane" pins the untrusted-only catalog case.
- `run-attempt.test.ts` "falls back to the user-input prompt only
  when no skills lanes are populated" pins the no-op baseline.
- `skills.buildworkspaceskillsnapshot.test.ts` pins that
  `untrustedReferencePrompt` carries every non-bundled source
  (workspace / project / managed / extra) and excludes bundled, that
  the bundled-only catalog omits the reference fragment, and that
  `schemaVersion` is stamped on every snapshot.
- `snapshot-hydration.test.ts` pins the
  `isSkillsSnapshotSchemaOutdated` predicate across legacy /
  current / stale / future cases.

Real behavior proof at current head:
`scripts/research/skills-trust-filter-proof.mts` exercises the
production pipeline against a real workspace fixture with one skill
per source (`openclaw-bundled`, `openclaw-workspace`,
`agents-skills-project`, `openclaw-managed`, `openclaw-extra`) and a
MEMORY-marker workspace-context fragment, captures byte counts /
sha256 hashes / `contains` and `does-not-contain` assertions for the
two Codex lanes, and replays the legacy-snapshot refresh decision.
Output is saved to
`docs/research/runtime-context-surface-f1-trust-filter-current-head-proof.md`:
23 wire assertions PASS, 0 FAIL; legacy snapshot returns
`isSkillsSnapshotSchemaOutdated === true`, current snapshot returns
`false`.

Prompt-snapshot fixtures regenerated to reflect the new wrapper
subline; deterministic happy-path projection shows the same workspace
context content, with the wrapper now noting that the reference
section may follow.
…hots

CI agents-core shard caught the existing
`hydrates stripped persisted skill snapshots before running the CLI
path` test breaking because the fixture's persisted snapshot lacks
`schemaVersion`, which the new `isSkillsSnapshotSchemaOutdated` guard
treats as outdated and force-rebuilds. The test's intent (hydrate
only, do not rebuild) is still valid for snapshots stamped at the
current schema version, so stamp `schemaVersion =
SKILL_SNAPSHOT_SCHEMA_VERSION` on the fixture and on the mocked
rebuild output.

Add a new sibling test
`force-rebuilds legacy persisted skill snapshots that pre-date the
lane-split fields` that exercises the new force-refresh decision at
the agent-command boundary. Pre-seed `resolvedSkills` so the
hydration path does not have to call `buildWorkspaceSkillSnapshot`
just to fill in runtime-only fields — without that seeding the new
test would be a false positive (the hydration path would call
`buildWorkspaceSkillSnapshot` even if the schema-version guard were
removed). Codex review flagged this and we verified locally that the
new test FAILs with the schema guard temporarily removed and PASSes
with the guard restored.

No production behavior change in this commit.
ClawSweeper round-3 P2 finding: after the lane split removed the
legacy `skillsSnapshot.prompt` consumer from the Codex turn,
remote-host execution guidance (`opts.eligibility.remote.note`, e.g.
`exec host=node` for remote macOS) was lost from native Codex
discovery. Reproducible source-side at `workspace.ts:1120` where the
note is still only prepended to the legacy `prompt`.

Add a persisted `SkillSnapshot.remoteNote` field that
`buildWorkspaceSkillSnapshot` populates from
`opts.eligibility.remote.note`, mirror it on `SessionSkillSnapshot`
so it round-trips through session storage, bump
`SKILL_SNAPSHOT_SCHEMA_VERSION` to 3 so v2 snapshots persisted by
the prior commits in this branch force-refresh through the existing
`isSkillsSnapshotSchemaOutdated` check and pick up the new field on
the next turn.

In `extensions/codex/src/app-server/run-attempt.ts`, thread
`codexRemoteNote = params.skillsSnapshot?.remoteNote` into
`buildCodexOpenClawPromptContext`. The renderer adds a new
non-authoritative `## OpenClaw Remote Skill Execution` section inside
the existing `OpenClaw workspace context for this turn:` wrapper,
between the workspace context and the user-installed skills
sections. Wrapper subline now lists all three sections explicitly.
The remote note never reaches
`collaborationMode.settings.developer_instructions`.

Legacy `prompt` continues to prepend the note for non-Codex
consumers so existing surfaces stay byte-stable.

Regression coverage:

- `src/agents/skills.buildworkspaceskillsnapshot.test.ts`:
  `persists eligibility.remote.note as snapshot.remoteNote for the
  Codex reference lane` (note appears on the snapshot and in the
  legacy `prompt`); `omits remoteNote when no remote eligibility is
  configured` (no synthetic empty value).
- `extensions/codex/src/app-server/run-attempt.test.ts`:
  `routes skillsSnapshot.remoteNote through the per-turn reference
  lane, not developer_instructions` (asserts the wire-level
  placement and the lane-authority boundary).

Regenerated the wire-level proof artifact at
`docs/research/runtime-context-surface-f1-trust-filter-current-head-proof.md`.
…d lanes

ClawSweeper round-4 P2 finding: each lane builder previously ran
its own `applySkillsPromptLimits` over its filtered subset of
`promptEntries`. That let `trustedDeveloperPrompt` and
`untrustedReferencePrompt` each fill the full
`maxSkillsPromptChars` / `maxSkillsInPrompt` cap independently, so
the model's combined view across the two lanes could exceed the
configured budget that legacy single-lane builds respected.

Apply the budget once over the combined sorted `promptSkills` in
`resolveWorkspaceSkillPromptState`, then partition the already-
budgeted `skillsForPrompt` set by name into trusted (bundled-only)
and untrusted (everything else) and render each via the new
`buildLaneSkillsPrompt` helper. The lane builder never re-applies
limits — only the partition decides which post-budget entries land
in each lane — so the combined model-visible skill catalog
respects the user's configured cap regardless of how the trust
filter splits the catalog.

The `truncated` and `compact` flags from the single budget pass
flow into both lanes, so the per-lane truncation notice now
reports "X of Y" against this lane's pre-budget eligible count
(distinct from the legacy "X of total" wording in `prompt`).

Add regression coverage:
- `src/agents/skills.buildworkspaceskillsnapshot.test.ts`
  "applies the configured maxSkillsPromptChars budget across the
  combined trusted/untrusted lanes, not per-lane": with
  `maxSkillsInPrompt = 4` and 8 candidates (4 bundled + 4
  workspace), counts `<skill>` blocks in the rendered lanes and
  asserts trusted + untrusted ≤ prompt. We locally verified the
  assertion FAILS when the partition is replaced with the legacy
  per-lane filter+sort+limit chain, and PASSes with the fix.

The trust policy, schema-version migration, and remoteNote
preservation are unchanged: only the budget-application path was
refactored to share `applySkillsPromptLimits` across both lanes.

Regenerated the current-head wire-level proof artifact.
…paths

Mirror the agent-command schema-version refresh predicate so persisted
snapshots that pre-date the lane-split fields (`trustedDeveloperPrompt`,
`untrustedReferencePrompt`, `remoteNote`) are rebuilt when reused by:

- `src/auto-reply/reply/session-updates.ts` (channel replies)
- `src/cron/isolated-agent/skills-snapshot.ts` (cron-driven turns)

Both paths now call `isSkillsSnapshotSchemaOutdated()` alongside the
existing version/filter checks, matching the rule already enforced in
`src/agents/agent-command.ts`. Without this guard, sessions opened
before the lane-split landed would hydrate the legacy v1/v2 snapshot
as-is and Codex would read `undefined` for both lanes until a workspace
bump or new session.

Adds regression tests that pre-seed `resolvedSkills` so the assertions
isolate the schema-version guard from the resolvedSkills hydrate fallback.
…a version

`createEmptySkillsSnapshot` now sets `schemaVersion: SKILL_SNAPSHOT_SCHEMA_VERSION`
so the explicit empty-filter snapshot persisted at the end of a turn is
treated as current by the reuse-path schema check. Without the marker,
the freshly added stale-schema guard in `shouldRefreshSkillsSnapshot`
classified every fresh empty snapshot as outdated and rebuilt/rewrote it
every turn for sessions configured with an empty skills filter.

Extends the existing empty-skill-filter regression test to assert the
`schemaVersion` is stamped on the snapshot handed to `runAgentAttempt`.
…ll-filter

The "reuses cached snapshot when version and normalized skillFilter are
unchanged" case fed `resolveCronSkillsSnapshot` a fixture with no
`schemaVersion`. After the cron path picked up the schema-outdated
rebuild guard, that fixture began triggering a force-rebuild via the
schema-version check, which made the existing `not.toHaveBeenCalled`
assertion fail in CI (checks-node-core-runtime-cron-isolated-agent).

Stamping `schemaVersion: SKILL_SNAPSHOT_SCHEMA_VERSION` on the fixture
restores the test's original intent: when version and normalized
skillFilter match a current-shape snapshot, no rebuild should happen.
…aVersion

After merging upstream/main into the PR branch, the two new
session-touch tests added upstream ("skips the initial session touch
after gateway ingress already persisted activity" / "persists explicit
overrides even when ingress skips the initial touch") fail because the
shared `setupSessionTouchStore` fixture's skillsSnapshot lacks
`schemaVersion`. The PR's stale-schema reuse guard then force-rebuilds
the snapshot and adds an extra `persistSessionEntryMock` call,
breaking both upstream tests' `not.toHaveBeenCalled` / `mockCallArg`
shapes.

Stamping the fixture with `schemaVersion: SKILL_SNAPSHOT_SCHEMA_VERSION`
restores upstream's intent: these tests exercise only the session-touch
logic, not the snapshot-rebuild path. The stale-snapshot regression
remains covered by dedicated fixtures (`legacyStrippedSnapshot` in
`session-updates.test.ts`, the legacy-rebuild case in
`run.skill-filter.test.ts`, and the legacy persisted snapshot in this
file's "force-rebuilds legacy persisted skill snapshots" test).

Codex review: OVERALL GO (criteria 1-5 PASS).
…ter rebase

After cleanly reconstructing the PR onto current upstream/main, the
three codex-runtime-happy-path snapshots need regen to reflect the
final on-branch state. Numeric delta vs upstream/main is the
PR-intent message-tool wrapper text growth in the developer lane
(+142 chars in `openClawDeveloperInstructions`, totals follow;
`userInputText` unchanged). No bundled/non-bundled lane reshuffle.

Codex review of the regen diff: OVERALL GO (criteria 1-6 PASS).
ClawSweeper P3 patch-quality finding: PR-only proof artifacts should
not ship to the repo. The trust-filter wire-level proof has been
captured inline in the PR body (byte sizes, sha256-12 hashes, 23/23
PASS assertions, legacy/current snapshot decisions). The structural
invariants remain covered by
`src/agents/skills.buildworkspaceskillsnapshot.test.ts` and
`src/agents/skills/snapshot-hydration.test.ts`.
…er rebase

During clean reconstruction onto current upstream/main, the PR's commits
re-introduced local definitions of three helpers in run-attempt.ts that
upstream moved to attempt-context.ts. The local definitions shadowed
the imports and missed upstream's recent improvements (delivery-hint
splitting in `prependCodexOpenClawPromptContext` and
`workspaceMemoryReference` handling in `buildCodexOpenClawPromptContext`).

Consolidate the helpers in attempt-context.ts:
- Extend `buildCodexOpenClawPromptContext` to accept `untrustedSkillsPrompt`
  and `remoteNote` (this PR's lane-split fields). Drop the obsolete
  `skillsPrompt` parameter — bundled skills now ride `developer_instructions`
  and non-bundled skills ride `untrustedReferencePrompt`. Adopt the PR-intent
  wrapper text "OpenClaw workspace context for this turn:" and section
  ordering: workspace context, memory reference, remote-host execution,
  user-installed skills.
- Export `shouldInjectCodexOpenClawPromptContext` and import it in
  run-attempt.ts.
- Delete the local duplicates of `buildCodexOpenClawPromptContext`,
  `shouldInjectCodexOpenClawPromptContext`, and
  `prependCodexOpenClawPromptContext` from run-attempt.ts.
- Update the delivery-hint test fixture to use `untrustedReferencePrompt`
  (legacy `prompt`-only snapshots force-refresh via
  `isSkillsSnapshotSchemaOutdated` before reaching this code path).

Trust boundary, bundled-only developer_instructions, reference-lane
placement for non-bundled / remoteNote, and the schema-version reuse
guard are unchanged. Codex review: OVERALL GO (criteria 1-6 PASS).
Cherry-picking the PR's commits onto current upstream/main brought
back local copies of ~50 helper functions and constants in
`extensions/codex/src/app-server/run-attempt.ts` that upstream later
moved into `extensions/codex/src/app-server/attempt-context.ts`. The
local copies are dead — they shadowed or duplicated the imports that
already exist at the top of the file.

Delete the dead copies (notification helpers, turn-request param
helpers, abort-marker constants, JSON record helpers, mirrored-session
helpers, workspace bootstrap helpers, diagnostic tool helpers,
stable-hash helpers, context-file helpers, workspace prompt
renderers, heartbeat helpers). 9 names still referenced in this file
resolve to existing `./attempt-context.js` imports.

100% deletion (-885 lines, no `+function`, no `+const`). PR's lane
split, schema-version guard, and remoteNote routing are unchanged.
Codex review: OVERALL GO (criteria 1-6 + scope-creep / behavior-drift
/ obsolete-duplicate all PASS).
The `happy-path-prompt-snapshots.ts` helper hard-coded the shorter wrapper
introductory line that only mentioned workspace context and user-installed
skills. The runtime builder in `attempt-context.ts:buildCodexOpenClawPromptContext`
emits the full section order including workspace memory reference and
remote-host execution guidance. Without this alignment the generated
fixtures stop mirroring actual model-bound turn input and prompt
snapshot checks can drift from runtime behavior they document.

Align the helper to the runtime text and regenerate the three
codex-runtime-happy-path fixtures. Delta is +70 chars on userInputText
(matching the added wrapper phrase); developer_instructions unchanged.

ClawSweeper P3 finding (`test/helpers/agents/happy-path-prompt-snapshots.ts:751`)
resolved. Helper is the authoritative drift point per ClawSweeper guidance.
@masatohoshino

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #87788.

The original goal of this PR was to reduce duplicated Codex skills / memory-pointer context. That goal is now handled by the merged #87788, which also establishes the maintainer-selected collaboration-instructions lane design.

The remaining trust-split direction in this branch no longer matches that merged direction closely enough to justify continuing daily conflict churn. I'll leave #88184 untouched and won't open a follow-up unless a concrete post-#87788 regression or maintainer-requested gap appears.

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

Labels

agents Agent runtime and tooling extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

4 participants