Skip to content

fix: recover Codex chats after oversized requests - #206475

Merged
roboclaw-bot merged 2 commits into
mainfrom
openclaw/fix-provider-message-size-recovery
Nov 27, 2026
Merged

roboclaw-bot merged 2 commits into
mainfrom
openclaw/fix-provider-message-size-recovery

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Long-running Codex conversations can exceed the local inference relay’s 32 MiB request limit. Even a short follow-up then fails again because it reuses the same oversized native history.

User Impact

After a relay-size failure, the next message in a managed conversation can start with bounded history from that same conversation instead of remaining stuck. The original transcript and native thread are preserved; the failed turn and its tools are not automatically replayed. Historical pixels may be omitted from the bounded model view under the existing omission notice, while the saved attachments remain available. Native-owned, supervised, and provider-review acknowledgment threads retain their original binding. A current request that is too large on its own still needs to be reduced.

Why This Change Was Made

Reuse the existing guarded thread-binding recovery owner for the exact local relay rejection, including the default native context route without an authored cap or bounded-seed capability. Keep the relay limit and existing authority checks unchanged. Charge restored historical image payloads against their encoded delivery size as well as the existing image-token floor so a replacement seed does not immediately refill the oversized request. Context-engine-selected attachments must fit their finite rendered allowance before native injection.

No new settings, storage, retry loop, or transcript reset. The change extends the existing recovery and seed-selection owners rather than adding another recovery manager.

Evidence

  • Two next-turn recovery regressions fail on base 946f085c64f1c because the oversized binding remains reusable, then pass with the fix. They cover default/native and external context-engine routes, preserve transcript bytes, and verify no automatic replay.
  • Added restored-media byte regressions at the host seed and Codex serialization boundaries; both fail before the byte-accounting repair and pass after it. Existing small-image and prepared-snapshot reuse checks remain green. The unconfigured SQLite-history recovery case also passes with no authored cap or bounded-seed capability, omitting byte-heavy historical pixels while preserving the stored prefix and current request.
  • Focused suites passed: host seed (26), Codex history seed (23), context projection (31), context overflow (7), HTTP relay (18), reviewed-turn startup recovery (3), and prompt-prefix stability (16).
  • A real pinned Codex 0.172.0 process with 34,000,000 bytes of synthetic native history reaches the production relay’s terminal size rejection without an upstream model request. A bounded replacement answers and the original native thread remains readable.
  • Qualified live relay probe: the real relay rejects that oversized native history; a bounded replacement using the configured real OpenAI model returns BOUNDED_OK, with the original thread retained. Native traffic stays on loopback and the relay retains the configured protected egress and trust settings. Automatic binding rotation is covered separately by the production-attempt regression.
  • Actual Chromium → isolated Gateway → native Codex → real-model chat returned the requested marker. This shell’s custom trust configuration intentionally disables automatic managed-relay activation, so that browser run is Gateway/model integration proof, not a claim of end-to-end relay-failure recovery.
  • The full build, core production, core harness test, extension production, and extension test typechecks passed; touched-file lint, formatting, and git diff --check passed.
  • Independent fresh read-only P0–P2 review covered the complete 13-file candidate against 946f085c64f1ccb912cc61838249d6d6ad26877e; both reported historical-media gaps were repaired and the final follow-up found no remaining actionable P0–P2 findings. The reviewed snapshot is code-identical to commit 103082658f3af9fcf982058fbcbdbf9b333d5851. Local ClawSweeper was unavailable because its checkout was dirty. Canonical autoreview refused before execution because the required temporary directory is inside the reviewed repository; neither setup limitation is reported as a clean review. A hosted exact-head re-review was requested; that request is not reported as a completed review.
  • Exact-head CI run 45958084526, attempt 1 completed with one failing test job and its downstream aggregate. The two session-history-control.test.ts cases (from file and from sqlite) expect obsolete compaction-summary wording. An independent clean worktree at exact PR base a2fe72e97139a9ef373d784c7d51d4f363d1d460 reproduces both failures without this PR; producer and test blobs are identical at that baseline, the inspected CI merge, and this head. This is retained failed-CI evidence for the supported inherited-failure landing route, not a claim that CI passed.

Reported by and co-authored with @vincentkoc.

Work sessions

Linked for team reference; these sessions aren’t public.

Worked on by

roboclaw-bot and others added 2 commits November 27, 2026 07:21
Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 6d2cb13b-89e2-4099-b6d0-57990a518de2
@clawsweeper

clawsweeper Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: codex size: M labels Nov 27, 2026
@roboclaw-bot
roboclaw-bot marked this pull request as ready for review November 27, 2026 07:23
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 27, 2026
@clawsweeper

clawsweeper Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR retires oversized Codex thread bindings for next-message recovery and includes encoded historical image sizes in seed budgets.

Example: A managed Codex conversation accumulates 34,000,000 bytes of native history, then receives “Continue.”

  • Before: The relay rejects the request, and subsequent short messages reuse the oversized history.
  • After: The failed turn remains recorded, and the next message starts a replacement thread with bounded conversation history.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused implementation and distinct boundary regressions support correctness, but the supplied real runs do not exercise automatic recovery or stable-state upgrade compatibility.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A long Codex conversation can remain unusable because every short follow-up resubmits the same oversized native history.
Reason: Recovering the affected conversation has clear value, and maintainer authorship establishes direction for the explicitly described bounded-history tradeoff.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: current main still lacks recovery for the exact local relay size rejection, and this PR makes a focused repair through existing owners with no definite introduced code defect found.

Reviewed head: ebfbc3631e7e028dc4b43460d8717596f999883d

Before merge

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Provide a sanitized managed-Gateway trace showing a real relay-size failure followed by automatic bounded recovery on the next message, including a latest-stable upgrade with the original binding, settings, transcript, and attachments preserved.
Agent review details

How this fits together

The Codex plugin translates OpenClaw conversations into native threads and routes inference through a size-limited local relay; recovery reconnects subsequent messages to bounded host history while preserving saved records.

flowchart LR
  A[Chat message] --> B[Codex attempt]
  B --> C[Native thread]
  C --> D[Local inference relay]
  D --> E[Model provider]
  D --> F[Size rejection]
  F --> G[Existing binding recovery]
  G --> H[Bounded history for next message]
  H --> B
Loading

Technical review

Best possible solution:

Retain the focused recovery and byte-accounting changes, then demonstrate automatic next-message recovery through the managed Gateway route using an existing stable-release conversation.

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

Source establishes that main preserves the oversized binding after the relay's terminal size error; the body reports a real native rejection, but this read-only review ran no target code.

Is this the best way to solve the issue?

The implementation addresses the stuck-binding cause through existing recovery and seed-selection owners, preserves the relay limit, and avoids replaying failed work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 009566554a35.

Provenance checked

  • Context-overflow binding recovery keeps the original intent (e8290c6: This commit moved the existing recovery helper during a behavior-preserving split; its pre-split introduction is unknown because git show of the parent run-attempt.ts blob failed.)
  • Terminal relay size errors keeps the original intent (1108a99: Return a nonretryable 400 instead of repeatedly sending unchanged oversized history as a transport retry.)
  • Bounded seed image accounting changes intended behavior with a stated reason (6db8577: Charge restored media against fresh-thread delivery allowances while leaving healthy native reuse alone; this PR explains why the fixed token floor must also account for encoded bytes.)
  • Selected-history serialization keeps the original intent (fix: selected Codex history is shortened before native delivery #171707: Deliver the selected history without silently applying another cutoff; this PR preserves that contract by rejecting attachments exceeding the finite allowance.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 283d5e6 adds extensions/codex/src/app-server/run-attempt-state.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 283d5e6fe371; files: extensions/codex/src/app-server/run-attempt-state.ts)
  • Ayaan Zaidi: Raw commit 6db8577 adds src/agents/harness/host-seed.ts:144 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6db8577c783c; files: src/agents/harness/host-seed.ts)
  • wtfichigo: Raw commit 8650e94 adds extensions/codex/src/app-server/run-attempt-state.ts:39 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8650e947681f; files: extensions/codex/src/app-server/run-attempt-state.ts)
  • Patrick Erichsen: Raw commit 1032118 adds extensions/codex/src/app-server/context-engine-projection.ts:149 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1032118cede1; files: extensions/codex/src/app-server/context-engine-projection.ts)

PR surface

Source +30, Tests +276, Docs +12. Total +318 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 51 21 +30
Tests 4 277 1 +276
Docs 1 12 0 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 340 22 +318

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.

Label justifications:

  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.

Rank-up moves

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

  • Capture automatic next-message recovery through the managed Gateway and real Codex relay using a conversation upgraded from the latest stable release.

Rating scale

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

Workflow

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

Reviewed November 27, 2026, 2:28 AM ET / 07:28 UTC.

@roboclaw-bot
roboclaw-bot merged commit e0aaec7 into main Nov 27, 2026
228 of 231 checks passed
@roboclaw-bot
roboclaw-bot deleted the openclaw/fix-provider-message-size-recovery branch November 27, 2026 07:53
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

vincentkoc added a commit that referenced this pull request Nov 27, 2026
…restoration-ci-189390-20261127

* commit '6feeb50a3f14fbf0aa5167d342f186dc4d67fc18': (9846 commits)
  fix: stop 2026-11-17 main Git checkouts from half-switching on a schema update (#206341)
  refactor(codex): centralize native completion delivery (#206447)
  fix(subagents): finish claimed stops after session rotation (#206405)
  fix: let owners fork a chat with exec after a subagent or exec completion (#206483)
  test(cli): gate agent --local cold-start processes and workers (#206466)
  perf(ci): skip baseline inventory when line-cap debt is empty (#189909)
  refactor(test): share core process-result fixtures (#174149)
  refactor(ci): reuse canonical budget flag parsing (#189480)
  fix: recover Codex chats after oversized requests (#206475)
  fix(agents): skip the bootstrap ritual in one-shot runs (#206477)
  fix(test): preserve stack coordinates in redacted failure reports (#152384)
  fix(gateway): return consistent unavailable response guidance (#191933)
  fix: preserve emphasis in Markdown table row labels (#205349)
  fix(nextcloud-talk): keep webhook spool helpers private (#206470)
  perf(plugins): overlay native receipts once per visible root (#206464)
  fix: keep GitHub comment approvals alive and skip repeat approval on the session PR (#206129)
  perf(config): retain one snapshot for unchanged validation results (#206465)
  refactor(test): reuse canonical secret fixture cleanup (#189492)
  refactor(subagents): own descendant Stop cancellation (#206444)
  refactor(subagents): keep announce cleanup action type private (#206407)
  ...
vincentkoc added a commit that referenced this pull request Nov 27, 2026
* commit 'fd681ab8786e062045fa5ec6261b1b06f60832eb': (2115 commits)
  fix: keep doctor --fix pending checks from creating SQLite sidecars (#206485)
  fix(ci): update iOS screenshot reducer gate (#206497)
  fix: keep chat photo previews sharp within their byte limits (#206461)
  fix: let agents use short Workboard card IDs
  fix(tui): run provider sign-in in the local TUI (#200605)
  improve(config): reduce repeated directory checks for larger agent rosters (#206494)
  perf(test): reuse the Periphery producer workflow snapshot (#189681)
  fix(ci): keep locale assets within the installed package budget (#206492)
  fix: preserve failed Apple chat messages across partial history pages (#205404)
  improve: avoid merging unrelated settings for agent directory lookups (#206489)
  fix: show typing while a queued follow-up turn runs (#201920)
  fix: stop 2026-11-17 main Git checkouts from half-switching on a schema update (#206341)
  refactor(codex): centralize native completion delivery (#206447)
  fix(subagents): finish claimed stops after session rotation (#206405)
  fix: let owners fork a chat with exec after a subagent or exec completion (#206483)
  test(cli): gate agent --local cold-start processes and workers (#206466)
  perf(ci): skip baseline inventory when line-cap debt is empty (#189909)
  refactor(test): share core process-result fixtures (#174149)
  refactor(ci): reuse canonical budget flag parsing (#189480)
  fix: recover Codex chats after oversized requests (#206475)
  ...
vincentkoc added a commit that referenced this pull request Nov 27, 2026
* commit 'fd681ab8786e062045fa5ec6261b1b06f60832eb': (923 commits)
  fix: keep doctor --fix pending checks from creating SQLite sidecars (#206485)
  fix(ci): update iOS screenshot reducer gate (#206497)
  fix: keep chat photo previews sharp within their byte limits (#206461)
  fix: let agents use short Workboard card IDs
  fix(tui): run provider sign-in in the local TUI (#200605)
  improve(config): reduce repeated directory checks for larger agent rosters (#206494)
  perf(test): reuse the Periphery producer workflow snapshot (#189681)
  fix(ci): keep locale assets within the installed package budget (#206492)
  fix: preserve failed Apple chat messages across partial history pages (#205404)
  improve: avoid merging unrelated settings for agent directory lookups (#206489)
  fix: show typing while a queued follow-up turn runs (#201920)
  fix: stop 2026-11-17 main Git checkouts from half-switching on a schema update (#206341)
  refactor(codex): centralize native completion delivery (#206447)
  fix(subagents): finish claimed stops after session rotation (#206405)
  fix: let owners fork a chat with exec after a subagent or exec completion (#206483)
  test(cli): gate agent --local cold-start processes and workers (#206466)
  perf(ci): skip baseline inventory when line-cap debt is empty (#189909)
  refactor(test): share core process-result fixtures (#174149)
  refactor(ci): reuse canonical budget flag parsing (#189480)
  fix: recover Codex chats after oversized requests (#206475)
  ...
obviyus added a commit that referenced this pull request Nov 27, 2026
Root cause: extensions/codex/src/app-server/thread-lifecycle-run.ts:154 dropped the native thread developer carrier whenever the managed inference relay existed, and extensions/codex/src/app-server/run-attempt-turn-request.ts:293 put skills, shared persona, memory and session project guidance into the relay text that inference-context.ts:271 adds to every request's top-level `instructions`. GPT-6.2 Sol and Astra never cache `instructions`, so every warm request in a turn re-paid that whole block.

Fixes #206421

Thanks @brandon-julio-t for the precise report (managed vs `appServer.command` A/B with per-request usage), and @NaturalMatchaKing for the A/B evidence in #204136.

## What changed

- Skills, shared persona (`SOUL.md`, `IDENTITY.md`, workspace-root `USER.md`), memory guidance and session project guidance now always ride the existing refreshable thread developer section, on managed connections too. Codex sends that as a `developer` input item, so it sits in the cached prefix, and later requests in a turn only append.
- The relay keeps only parent-only text: the selected personal `users/<id>/USER.md` overlay, cron policy, plugin `before_prompt_build` system context, and per-turn conversation instructions. Per-turn plugin context stays off the thread on relay connections (`turnRefreshableInstructions` split; still thread-carried when there is no relay, as before).
- `workspace-context.ts` renders the personal-only persona with the same renderer; the codex context plumbs `personalPersonaInstructions` instead of the full persona.
- Edits to that section no longer refuse a thread kept alive by background work. Before this, a skill, persona or memory edit made the next message cold-resume the thread, and a thread kept alive by a running background command refused with "still has background work… stop its running work and retry". `appServer.command` and other non-relay connections already failed this way on main; managed connections would have started to with the carrier move. Now the refreshable section is left out of the thread configuration fingerprint, and persistent live threads keep the same in-memory record incognito threads already had of the section the thread was natively given (`nativeRefreshableInstructions`) and the one last delivered. On reuse (`thread-lifecycle-warm.ts`):
  - Idle thread, section changed: cold resume, as on main, so native configuration carries the current section and compaction rebuilds from it. On managed connections this costs one uncached turn per edit.
  - Protected thread (running background command or child), section changed: the existing appended developer handoff instead of the refusal; the existing post-compaction restore re-delivers it.
  - Self-heal: the first later turn where the thread is no longer protected and its native section still differs from the current one cold-resumes.
  - Managed relay fallback: while a thread's native section differs from the current one (an edited incognito thread, or a protected persistent thread waiting for its cold resume), the relay also sends the current section in request `instructions`, as main did for every request, so a post-compaction continuation sees it. It stops when the native copy matches again (after the self-heal cold resume); unedited threads never pay for it. The section never holds the selected personal overlay, so that is still sent once (`renderCodexRelayRefreshableFallback`, thread-policy.ts).

  No new field, flag or persisted state: the comparison uses the in-memory record, and ephemeral lifetime is keyed off the generic policy that only ephemeral records carry.
- Remaining narrow gap, only on connections without a relay (`appServer.command`): an edit made while background work keeps the thread protected, followed by a native compaction before that work ends, can let one continuation request see the previous section. On main those threads refuse the next turn outright. Codex samples the continuation right after compaction, before injected developer messages are drained (`codex-rs/core/src/session/turn.rs` pending-input drain is deferred after auto-compaction; `session/inject.rs` queues injections into the active turn), and the host restore lands on the request after it. It heals on the first unprotected turn. Not taken: (B) carrying the section in turn-level `collaborationMode.settings.developer_instructions`, because a model catalog's default-mode override wins over caller text, it replaces the built-in Default-mode text and collides with OpenClaw's cron collaboration instructions, and native children do not inherit it; (D) asking Codex to drain injected developer messages before the post-compaction continuation, or to accept developer instructions in thread settings, needs a Codex dependency bump.
- Report estimate counts the stable section on the thread in both modes.
- No model-facing wording changed. Layout change: a user with a personal overlay gets two `## OpenClaw Agent Soul` blocks (shared in the thread, personal in the relay).
- `inference-dispatch.ts` untouched (#206475 size recovery kept).

## What remains: 97.2% vs 99.5%

Live gpt-6.2-sol against main `712db11dfc9e`, the reporter's five-tool-call turn. Two runs per arm on `2ca1ebe03be6` plus one per arm on `a286631217b9` (the stale-section cold resume does not touch an unedited turn; earlier heads had three runs per arm with the same results). Warm-request cache hit and per-request `input/cached` come from the Codex rollout:

| arm | warm hit | uncached input per warm request | previous request's input not cached | uncached input per turn |
|---|---|---|---|---|
| main, managed relay | 70.6–70.7% | ~6,150–6,200 tokens | 6,054–6,100 tokens | 51.5–51.8k |
| this PR, managed relay | 97.2–97.3% | ~570 tokens | 421 tokens | 23.9–24.0k |
| `appServer.command` (no relay) | 99.5% | ~100 tokens | 3 tokens | 20.5–20.6k |

The remaining ~420 tokens per warm request are the relay's per-turn conversation instructions and tool bindings, which still go in top-level `instructions` and are never cached on these models. They are per-turn facts, so moving them is a separate change (for example to turn `additionalContext`); this PR does not move them.

## Earlier attempt

#141270 (@mbelinky) aimed at the same carrier: workspace persona and memory on the thread developer instructions. This PR is a smaller change at the relay/lifecycle owners and does not build on it.

## Deliberate decision reversed

This reverses #142276's parent-only delivery for shared text: native Codex subagents now inherit shared persona, skills and memory guidance through `developer_instructions` (`codex-rs/core/src/agent/child_config.rs` `inherited_developer_instructions`). Reasoning: that is already the behavior of every connection without a relay (#162156 called it intentional); native delegation is off wherever session tools are denied; the original #142276 problem (catalog collaboration text replacing caller instructions) is solved by thread developer instructions; and keeping the split costs every managed user about 2.2x the uncached input on a five-tool-call turn (51.8k vs 24.0k tokens; about 11x per warm request). The personal overlay stays parent-only (#162156 privacy boundary kept). A child created after an in-place edit inherits the thread's creation-time section, the same limitation incognito threads already document.

## Evidence

Proof comments: #206554 (comment) (cache and request bodies), #206554 (comment) (background-work P1), #206554 (comment) (`2ca1ebe03be6`: scripted lane, live cache, live managed P1), #206554 (comment) (`a286631217b9`: stale-section cold resume, compaction and self-heal regressions, live P1 on both routes, cache), #206554 (comment) (`76341cb30f58`: managed relay fallback regression, live managed P1). Child-inheritance decision: #206554 (comment)

- Scripted lane (real managed bundled codex 0.172.0 app-server, real relay, synthetic Responses upstream recording bodies): `run-attempt.skills.native.test.ts` "keeps managed skills in the cached native prefix across a multi-request turn" is red on main (skills in `instructions` on every frame) and green here (marker once in a `developer` input item, each frame's input extends the previous one byte-for-byte).
- Background-work regression: `run-attempt.native-background-outcome.test.ts` "refreshes edited skills on a protected thread, then cold-resumes once it ends" (managed relay and `appServer.command`): the protected edit arrives as one handoff with no refusal, and after the listener ends the next turn unsubscribes and cold-resumes with the edited catalog. Red on `8fd3970192d6` (refusal) and on `2ca1ebe03be6` (no self-heal); green here.
- Compaction regression: `run-attempt.skills.native.test.ts` "keeps a withdrawn catalog withdrawn after native compaction rebuilds the persistent thread" (real Codex binary, pre-sampling auto-compaction): the continuation request after compaction no longer carries the withdrawn creation catalog. Red on `2ca1ebe03be6`, green here; the incognito case keeps its documented one-request reversion.
- Real Gateway + `openclaw agent`, gpt-6.2-sol, a native-shell `sleep` listener started on turn 1, a skill installed with `openclaw skills install`, then turn 2: previous head refuses on both routes; this PR answers with the new skill on both, through a warm refresh handoff, with turn 2's first request cached up to the previous input. After a Gateway restart, the cold resume carries the current section.

## Merge danger

Two-way door: no stored state, schema or config changes; a revert restores the previous layout. On first turn after upgrade each managed thread gets one cold resume (Gateway restart) that installs the section, as before. Restricted threads on connections without a relay rotate once after upgrade because their stored fingerprint included the section; afterwards edits cold-resume them instead of rotating them. Blast radius: Codex harness thread lifecycle and relay instructions.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
* fix: recover Codex chats after oversized requests

Co-authored-by: vincentkoc <[email protected]>

* fix: recover Codex chats after oversized requests

Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 6d2cb13b-89e2-4099-b6d0-57990a518de2

---------

Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit e0aaec7)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
* fix: recover Codex chats after oversized requests

Co-authored-by: vincentkoc <[email protected]>

* fix: recover Codex chats after oversized requests

Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 6d2cb13b-89e2-4099-b6d0-57990a518de2

---------

Co-authored-by: vincentkoc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…#206554)

Root cause: extensions/codex/src/app-server/thread-lifecycle-run.ts:154 dropped the native thread developer carrier whenever the managed inference relay existed, and extensions/codex/src/app-server/run-attempt-turn-request.ts:293 put skills, shared persona, memory and session project guidance into the relay text that inference-context.ts:271 adds to every request's top-level `instructions`. GPT-6.2 Sol and Astra never cache `instructions`, so every warm request in a turn re-paid that whole block.

Fixes openclaw#206421

Thanks @brandon-julio-t for the precise report (managed vs `appServer.command` A/B with per-request usage), and @NaturalMatchaKing for the A/B evidence in openclaw#204136.

## What changed

- Skills, shared persona (`SOUL.md`, `IDENTITY.md`, workspace-root `USER.md`), memory guidance and session project guidance now always ride the existing refreshable thread developer section, on managed connections too. Codex sends that as a `developer` input item, so it sits in the cached prefix, and later requests in a turn only append.
- The relay keeps only parent-only text: the selected personal `users/<id>/USER.md` overlay, cron policy, plugin `before_prompt_build` system context, and per-turn conversation instructions. Per-turn plugin context stays off the thread on relay connections (`turnRefreshableInstructions` split; still thread-carried when there is no relay, as before).
- `workspace-context.ts` renders the personal-only persona with the same renderer; the codex context plumbs `personalPersonaInstructions` instead of the full persona.
- Edits to that section no longer refuse a thread kept alive by background work. Before this, a skill, persona or memory edit made the next message cold-resume the thread, and a thread kept alive by a running background command refused with "still has background work… stop its running work and retry". `appServer.command` and other non-relay connections already failed this way on main; managed connections would have started to with the carrier move. Now the refreshable section is left out of the thread configuration fingerprint, and persistent live threads keep the same in-memory record incognito threads already had of the section the thread was natively given (`nativeRefreshableInstructions`) and the one last delivered. On reuse (`thread-lifecycle-warm.ts`):
  - Idle thread, section changed: cold resume, as on main, so native configuration carries the current section and compaction rebuilds from it. On managed connections this costs one uncached turn per edit.
  - Protected thread (running background command or child), section changed: the existing appended developer handoff instead of the refusal; the existing post-compaction restore re-delivers it.
  - Self-heal: the first later turn where the thread is no longer protected and its native section still differs from the current one cold-resumes.
  - Managed relay fallback: while a thread's native section differs from the current one (an edited incognito thread, or a protected persistent thread waiting for its cold resume), the relay also sends the current section in request `instructions`, as main did for every request, so a post-compaction continuation sees it. It stops when the native copy matches again (after the self-heal cold resume); unedited threads never pay for it. The section never holds the selected personal overlay, so that is still sent once (`renderCodexRelayRefreshableFallback`, thread-policy.ts).

  No new field, flag or persisted state: the comparison uses the in-memory record, and ephemeral lifetime is keyed off the generic policy that only ephemeral records carry.
- Remaining narrow gap, only on connections without a relay (`appServer.command`): an edit made while background work keeps the thread protected, followed by a native compaction before that work ends, can let one continuation request see the previous section. On main those threads refuse the next turn outright. Codex samples the continuation right after compaction, before injected developer messages are drained (`codex-rs/core/src/session/turn.rs` pending-input drain is deferred after auto-compaction; `session/inject.rs` queues injections into the active turn), and the host restore lands on the request after it. It heals on the first unprotected turn. Not taken: (B) carrying the section in turn-level `collaborationMode.settings.developer_instructions`, because a model catalog's default-mode override wins over caller text, it replaces the built-in Default-mode text and collides with OpenClaw's cron collaboration instructions, and native children do not inherit it; (D) asking Codex to drain injected developer messages before the post-compaction continuation, or to accept developer instructions in thread settings, needs a Codex dependency bump.
- Report estimate counts the stable section on the thread in both modes.
- No model-facing wording changed. Layout change: a user with a personal overlay gets two `## OpenClaw Agent Soul` blocks (shared in the thread, personal in the relay).
- `inference-dispatch.ts` untouched (openclaw#206475 size recovery kept).

## What remains: 97.2% vs 99.5%

Live gpt-6.2-sol against main `2553b7e25179`, the reporter's five-tool-call turn. Two runs per arm on `2ca1ebe03be6` plus one per arm on `a286631217b9` (the stale-section cold resume does not touch an unedited turn; earlier heads had three runs per arm with the same results). Warm-request cache hit and per-request `input/cached` come from the Codex rollout:

| arm | warm hit | uncached input per warm request | previous request's input not cached | uncached input per turn |
|---|---|---|---|---|
| main, managed relay | 70.6–70.7% | ~6,150–6,200 tokens | 6,054–6,100 tokens | 51.5–51.8k |
| this PR, managed relay | 97.2–97.3% | ~570 tokens | 421 tokens | 23.9–24.0k |
| `appServer.command` (no relay) | 99.5% | ~100 tokens | 3 tokens | 20.5–20.6k |

The remaining ~420 tokens per warm request are the relay's per-turn conversation instructions and tool bindings, which still go in top-level `instructions` and are never cached on these models. They are per-turn facts, so moving them is a separate change (for example to turn `additionalContext`); this PR does not move them.

## Earlier attempt

openclaw#141270 (@mbelinky) aimed at the same carrier: workspace persona and memory on the thread developer instructions. This PR is a smaller change at the relay/lifecycle owners and does not build on it.

## Deliberate decision reversed

This reverses openclaw#142276's parent-only delivery for shared text: native Codex subagents now inherit shared persona, skills and memory guidance through `developer_instructions` (`codex-rs/core/src/agent/child_config.rs` `inherited_developer_instructions`). Reasoning: that is already the behavior of every connection without a relay (openclaw#162156 called it intentional); native delegation is off wherever session tools are denied; the original openclaw#142276 problem (catalog collaboration text replacing caller instructions) is solved by thread developer instructions; and keeping the split costs every managed user about 2.2x the uncached input on a five-tool-call turn (51.8k vs 24.0k tokens; about 11x per warm request). The personal overlay stays parent-only (openclaw#162156 privacy boundary kept). A child created after an in-place edit inherits the thread's creation-time section, the same limitation incognito threads already document.

## Evidence

Proof comments: openclaw#206554 (comment) (cache and request bodies), openclaw#206554 (comment) (background-work P1), openclaw#206554 (comment) (`2ca1ebe03be6`: scripted lane, live cache, live managed P1), openclaw#206554 (comment) (`a286631217b9`: stale-section cold resume, compaction and self-heal regressions, live P1 on both routes, cache), openclaw#206554 (comment) (`76341cb30f58`: managed relay fallback regression, live managed P1). Child-inheritance decision: openclaw#206554 (comment)

- Scripted lane (real managed bundled codex 0.172.0 app-server, real relay, synthetic Responses upstream recording bodies): `run-attempt.skills.native.test.ts` "keeps managed skills in the cached native prefix across a multi-request turn" is red on main (skills in `instructions` on every frame) and green here (marker once in a `developer` input item, each frame's input extends the previous one byte-for-byte).
- Background-work regression: `run-attempt.native-background-outcome.test.ts` "refreshes edited skills on a protected thread, then cold-resumes once it ends" (managed relay and `appServer.command`): the protected edit arrives as one handoff with no refusal, and after the listener ends the next turn unsubscribes and cold-resumes with the edited catalog. Red on `8fd3970192d6` (refusal) and on `2ca1ebe03be6` (no self-heal); green here.
- Compaction regression: `run-attempt.skills.native.test.ts` "keeps a withdrawn catalog withdrawn after native compaction rebuilds the persistent thread" (real Codex binary, pre-sampling auto-compaction): the continuation request after compaction no longer carries the withdrawn creation catalog. Red on `2ca1ebe03be6`, green here; the incognito case keeps its documented one-request reversion.
- Real Gateway + `openclaw agent`, gpt-6.2-sol, a native-shell `sleep` listener started on turn 1, a skill installed with `openclaw skills install`, then turn 2: previous head refuses on both routes; this PR answers with the new skill on both, through a warm refresh handoff, with turn 2's first request cached up to the previous input. After a Gateway restart, the cold resume carries the current section.

## Merge danger

Two-way door: no stored state, schema or config changes; a revert restores the previous layout. On first turn after upgrade each managed thread gets one cold resume (Gateway restart) that installs the section, as before. Restricted threads on connections without a relay rotate once after upgrade because their stored fingerprint included the section; afterwards edits cold-resume them instead of rotating them. Blast radius: Codex harness thread lifecycle and relay instructions.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
* fix: recover Codex chats after oversized requests

Co-authored-by: vincentkoc <[email protected]>

* fix: recover Codex chats after oversized requests

Worked on by:
- @vincentkoc

Co-authored-by: vincentkoc <[email protected]>
OpenClaw-Publication: 6d2cb13b-89e2-4099-b6d0-57990a518de2

---------

Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit e0aaec7)

Release adaptation: Extract only serialized image byte accounting and its host seed regression; exclude all native Codex and documentation changes.

Companion audit: PR #206475 is the source; the host seed owns this independent byte bound.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant