Skip to content

fix(agents): route Codex budget compaction natively - #114182

Closed
HOYALIM wants to merge 3 commits into
openclaw:mainfrom
HOYALIM:codex/issue-114155-codex-budget-native-compaction
Closed

HOYALIM wants to merge 3 commits into
openclaw:mainfrom
HOYALIM:codex/issue-114155-codex-budget-native-compaction

Conversation

@HOYALIM

@HOYALIM HOYALIM commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #114155

What Problem This Solves

Budget-triggered compaction for Codex OAuth sessions called the ordinary native harness hook. Codex correctly reported that its app-server owns automatic compaction, but the CLI lifecycle then fell back to API-key-backed context-engine compaction. OAuth-only sessions could therefore fail with No API key found for provider "openai" after a successful turn.

Why This Change Was Made

Codex already exposes a private native compaction request that permits non-manual thread/compact/start on the authenticated app-server connection. The CLI budget path now selects that existing request only when the pinned harness is Codex. Post-run compaction resumes the persisted thread on the newly leased app-server client before starting compaction, then unsubscribes after terminal completion.

This restores the native OAuth compaction contract established by #95831 without adding configuration or changing public APIs. Codex retains its terminal-event watchdog and transcript ownership until native compaction settles; other harnesses retain the existing outer timeout and fallback behavior.

User Impact

Codex OAuth-only sessions can perform budget maintenance without requiring a separate OpenAI API key or turning a completed response into a failed run. The lifecycle removes the direct context-engine fallback for Codex-owned automatic compaction.

Evidence

Current-head real behavior proof used GitHub CI's dist-runtime-build artifact for merge commit 11f1bf65369dee35bde860f2932e1f271bf6a8a9, whose parents are current main (c66ca2fbb2b038f4796abfa76bd52dcc3b675b02) and branch head 850c9fa7b09216222b444f1d4aa104118e124e35.

A real loopback Gateway ran one Codex session with a deliberately small 4,000-token context budget and a dense prompt. OPENAI_API_KEY and OPENAI_BASE_URL were both unset; runtime logs confirmed external CLI OAuth bootstrap.

Redacted observed result:

artifact merge head: 11f1bf65369d
branch head:         850c9fa7b092
OpenAI API key:      absent
OpenAI base URL:     absent
agent status:        ok
completion marker:   matched
elapsed:             15s
one-shot cleanup:    observed before post-run compaction
native compact start:    1
native compact complete: 1
thread-not-found errors: 0
context-engine fallback: 0
native fallback warnings: 0

The completed answer remained successful while the persisted Codex thread was resumed and compacted natively after one-shot app-server cleanup.

Validation

  • node_modules/.bin/vitest run src/agents/command/cli-compaction.test.ts extensions/codex/src/app-server/compact.test.ts --maxWorkers=2 -> 3 loaded files, 85 tests passed.
  • Focused measurement -> 3/3 contracts passed; native compaction success 0 -> 1, context-engine compaction and maintenance calls 1 -> 0.
  • Changed-file oxfmt, oxlint, and git diff --check -> passed.
  • codex review --base upstream/main -> no actionable findings; independently confirmed thread/resume -> thread/compact/start -> thread/unsubscribe against the Codex protocol.
  • GitHub CI broad checks remain authoritative for repository-wide validation.

AI-assisted: yes. I traced the CLI budget lifecycle, reproduced the OAuth-only product path, found the one-shot app-server lifecycle gap, added focused lifecycle and stale-binding tests, and reviewed the final diff.

Signed-off-by: Ho Lim [email protected]

Copilot AI review requested due to automatic review settings July 26, 2026 22:07

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 26, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 26, 2026
@clawsweeper

clawsweeper Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 26, 2026, 7:32 PM ET / 23:32 UTC.

ClawSweeper review

What this changes

Routes Codex budget-triggered CLI compaction to the authenticated app-server request, resumes the persisted thread for post-run compaction, and adds lifecycle coverage that prevents API-key-backed context-engine fallback.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

The reported OAuth-only failure is concrete and this PR now includes credible after-fix runtime evidence, but a merge verdict needs a maintainer or reviewer who can inspect the exact current-main lifecycle and sibling ../codex app-server protocol source. The supplied context supports keeping this PR as the candidate fix for the open bug rather than closing either item.

Priority: P1
Reviewed head: 850c9fa7b09216222b444f1d4aa104118e124e35
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The real runtime proof is strong, while the patch remains pending direct protocol and current-main source review required for this Codex lifecycle.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.
Evidence reviewed 5 items Reported current failure: The linked open report describes a reproducible Codex OAuth-only budget-compaction path where a completed answer is followed by an API-key-backed fallback and the run becomes failed.
Candidate-fix relationship: This PR explicitly closes the open bug report and changes the CLI compaction selection plus the Codex native compaction implementation and focused tests, matching the reported lifecycle boundary.
After-fix real behavior proof: The PR body reports a redacted loopback-Gateway run at the tested merge commit with no OpenAI API key or base URL, one native compaction start and completion, no context-engine fallback, and a successful agent status. The provided check context also records successful Real behavior proof runs.
Findings None None.
Security None None.

How this fits together

The CLI compaction lifecycle runs after an agent turn when its context budget is exceeded. For a Codex OAuth session, the agent harness and bundled Codex extension must keep compaction on the authenticated app-server connection rather than handing it to OpenClaw’s direct OpenAI context engine.

flowchart LR
  A[Completed Codex agent turn] --> B[CLI budget check]
  B --> C[Codex harness selection]
  C --> D[Resume persisted app-server thread]
  D --> E[Native Codex compaction]
  E --> F[Terminal event and cleanup]
  E --> G[Successful session state]
Loading

Decision needed

Question Recommendation
Does the direct sibling Codex protocol implementation confirm that resuming a persisted thread, starting automatic compaction, and unsubscribing after terminal completion is the supported lifecycle for this budget path? Verify protocol then merge: Confirm the requested app-server sequence and, if it matches the current Codex source and tests, proceed with normal merge review.

Why: Repository policy makes direct inspection of the sibling Codex source a hard gate for a Codex protocol verdict; the managed sandbox prevented that inspection in this review.

Before merge

  • Resolve merge risk (P1) - The patch changes a compatibility-sensitive auth and persisted-thread lifecycle: a reviewer must verify the actual Codex protocol contract for resume, compact, terminal notification handling, and unsubscribe before merge.
  • Resolve merge risk (P2) - The provided runtime proof is strong for the OAuth-only happy path, but source-level review still needs to confirm timeout, cancellation, stale-thread, and non-Codex harness behavior remain unchanged.
  • Complete next step (P2) - Real behavior evidence supports the proposed repair, but the remaining gate is human protocol verification rather than a safe automated branch repair.
Agent review details

Security

None.

PR surface

Source +80, Tests +118. Total +198 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 139 59 +80
Tests 2 144 26 +118
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 283 85 +198

Review metrics

None.

Stored data model

Persistent data-model change detected: database schema: extensions/codex/src/app-server/compact.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #114155
Summary: This PR is the candidate fix for the open report’s Codex OAuth budget-compaction failure.

Members:

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

Merge-risk options

Maintainer options:

  1. Verify the native lifecycle before merge (recommended)
    Inspect the current Codex app-server contract for resume, automatic compaction, terminal completion, and unsubscribe, then keep the focused OAuth-only proof as regression evidence.
  2. Pause for owner confirmation
    Pause this PR if the intended owner of Codex post-run thread cleanup cannot confirm that this lifecycle is supported.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Verify the sibling Codex app-server protocol sequence for persisted-thread resume, native automatic compaction, terminal completion, and unsubscribe before merging.

Technical review

Best possible solution:

Retain native Codex compaction for OAuth-only budget maintenance, with direct review of the Codex app-server protocol and focused confirmation that non-Codex harnesses still use the existing timeout and fallback behavior.

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

Yes in the supplied evidence: an OAuth-only Codex session with a small context budget reaches the native budget-compaction path without API-key fallback. This review could not independently rerun or source-trace that path because the managed sandbox rejected read-only commands before execution.

Is this the best way to solve the issue?

Unclear pending direct Codex protocol inspection. Routing the Codex-owned budget path to its authenticated app-server is the narrower solution than treating a missing API key as a benign fallback, but the exact resume-and-cleanup sequence needs contract confirmation.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The linked bug can turn a completed Codex OAuth agent response into a failed run during routine budget maintenance.
  • merge-risk: 🚨 auth-provider: The fix changes whether Codex OAuth sessions remain on app-server authentication or fall back to direct OpenAI API-key authentication.
  • merge-risk: 🚨 session-state: The patch resumes a persisted Codex thread and alters cleanup timing before compaction.
  • merge-risk: 🚨 availability: An incorrect post-turn compaction lifecycle can fail a completed agent run or leave its maintenance path stalled.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a redacted after-fix OAuth-only loopback-Gateway run showing successful completion, native compaction start and completion, and zero context-engine fallback; the provided check context also records successful Real behavior proof runs.

Evidence

What I checked:

  • Reported current failure: The linked open report describes a reproducible Codex OAuth-only budget-compaction path where a completed answer is followed by an API-key-backed fallback and the run becomes failed. (src/agents/command/cli-compaction.ts:473, 850c9fa7b092)
  • Candidate-fix relationship: This PR explicitly closes the open bug report and changes the CLI compaction selection plus the Codex native compaction implementation and focused tests, matching the reported lifecycle boundary. (src/agents/command/cli-compaction.test.ts:804, 850c9fa7b092)
  • After-fix real behavior proof: The PR body reports a redacted loopback-Gateway run at the tested merge commit with no OpenAI API key or base URL, one native compaction start and completion, no context-engine fallback, and a successful agent status. The provided check context also records successful Real behavior proof runs. (11f1bf65369d)
  • Prior merged behavior: Merged PR 95831 established native Codex OAuth compaction for manual or queued compaction, while this PR targets the remaining post-turn CLI-budget lifecycle ordering gap. (extensions/codex/src/app-server/compact.ts:581, 487951f813a8)
  • Independent source/protocol review gap: The managed read-only sandbox rejected every inspection command before execution, so this review could not complete the required local source/history inspection or the repository-required direct sibling ../codex protocol inspection.

Likely related people:

  • sallyom: Authored the merged native Codex OAuth compaction change that this PR explicitly builds on. (role: feature introducer; confidence: medium; commits: 487951f813a8; files: extensions/codex/src/app-server/compact.ts)
  • HOYALIM: Authored the current candidate fix and supplied focused test and runtime-proof context for the CLI budget-compaction path. (role: current lifecycle contributor; confidence: medium; commits: d93005b5437c, 704042aa0689, 850c9fa7b092; files: src/agents/command/cli-compaction.ts, src/agents/command/cli-compaction.test.ts)

Rank-up moves

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

  • Have a reviewer inspect the exact current sibling Codex protocol implementation for the resume-to-compact-to-unsubscribe sequence.
  • Confirm focused coverage preserves the non-Codex timeout and context-engine fallback paths.

Rating scale

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

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-07-26T22:13:07.389Z sha 704042a :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-26T23:17:51.143Z sha 850c9fa :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 26, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks @HOYALIM for the deep investigation — the failure chain you documented in #114155 is real and confirmed on current main (the intentional "codex app-server owns automatic compaction" skip maps to fallbackToContextEngine: true for unlocked sessions at src/agents/command/cli-compaction.ts:571-579, and the context-engine pass then requires a direct API key that OAuth-only sessions don't have).

Closing the PR because the ownership rework points the fix the other way: after #115284/#115514, the contract is "Codex owns native-thread token pressure; OpenClaw owns the host transcript byte fuse" — and codex-rs genuinely runs inline auto-compaction during turns (codex-rs/core/src/session/turn.rs:1016-1095), so OpenClaw force-driving thread/compact/start from host-side budget estimates works against that boundary, and this PR needs thread-resume/unsubscribe machinery plus a safety-timeout carve-out to do it. The correct fix is deleting the stale context-engine fallback on that skip so the unlocked path skips cleanly like the locked path already does — landing separately with credit. #114155 stays open until that lands.

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: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Budget-triggered compaction hard-fails on Codex OAuth sessions — native compaction path is ordered after the one requiring an API key

3 participants