Skip to content

fix(codex): keep managed relay context in the cached prefix - #206554

Merged
obviyus merged 8 commits into
mainfrom
bugloop-206421
Nov 27, 2026
Merged

obviyus merged 8 commits into
mainfrom
bugloop-206421

Conversation

@obviyus

@obviyus obviyus commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

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 (fix: recover Codex chats after oversized requests #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.

The managed inference relay put skills, shared persona, memory and session project guidance in each request's top-level instructions and disabled the native thread developer carrier. Models that never cache instructions (GPT-6.2 Sol/Astra) then lost that tail on every warm request. Stable context now always rides the refreshable thread developer section; the relay keeps only the personal USER.md overlay, cron policy, plugin system context and per-turn conversation text.
@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.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Proof for #206421 (observed, no secrets):

#206421 managed Codex relay loses prompt-cache tail — proof (2026-11-27)
base = origin/main a8f3e66b6f99 ; candidate = bugloop-206421 1a803295fa8f (see PR head for final SHA)

== Scripted lane (vitest-source; real managed bundled codex 0.172.0 app-server + real relay; synthetic Responses upstream records bodies; 1 turn, 5 update_plan tool calls)
test: extensions/codex/src/app-server/run-attempt.skills.native.test.ts "keeps managed skills in the cached native prefix across a multi-request turn"
base: FAIL  expected instructions not to contain SYNTHETIC_STABLE_SKILL_MARKER (skills in top-level instructions on every frame)   [proofs/206421/base-regression.log]
cand: PASS  marker once in a developer input item on all 6 frames; each frame's input starts with previous frame's input; instructions = turn text only   [proofs/206421/cand-regression.log]

== Controls (scripted, same lane; proofs/206421/scripted/out/*/controls.txt)
base turn1 req1..3: SKILL_A{dev=0,instructions=1} shared_soul{dev=0,instructions=1}
cand turn1 req1..3: SKILL_A{dev=1,instructions=0} shared_soul{dev=1,instructions=0} personal{dev=0,instructions=1}
cand skill edit turn2: SKILL_B{dev=1,instructions=0}; turn2 req1 input starts with turn1 last input (byte-identical): true
cand after native compaction: current skills present=true latest_is_current=true
cand personal overlay in any input item: false; in instructions of every turn request: true
upgrade (thread created on base, continued on cand): same native thread resumed: true; req1 input starts with main's last input: true; SKILL_A dev=1 (one block); second turn adds no further block: true

== Live lane (real openai/gpt-6.2-sol via Codex harness, API key via exec SecretRef OPENCLAW-OPENAI-API-KEY; reporter's 5-tool-call turn; per-request input/cached from rollout token_count)
base managed r1: 21008/0 21497/14831 21591/15320 21702/15414 21785/15525 21913/15608 21995/15736  warm_hit=70.8%
base managed r2: 20960/0 21054/14829 21167/14923 21251/15036 21379/15120 21461/15248  warm_hit=70.7%
base managed r3: 21008/0 21101/14831 21213/14924 21296/15036 21425/15119 21507/15248  warm_hit=70.5%
cand managed r1: 20693/0 21182/20272 21252/20761 21340/20831 21405/20919 21509/20984 21569/21088  warm_hit=97.3%
cand managed r2: 20693/0 21182/20272 21252/20761 21339/20831 21403/20918 21507/20982 21566/21086  warm_hit=97.3%
cand managed r3: 20741/0 20834/20320 20945/20413 21027/20524 21517/20606 21645/21096 21728/21224  warm_hit=97.2%
control appServer.command r1: 20231/0 20326/20228 20439/20323 20521/20436 20650/20518 20733/20647  warm_hit=99.5%
control appServer.command r2: 20279/0 20372/20276 20485/20369 20567/20482 20693/20564 20776/20690  warm_hit=99.5%
control appServer.command r3: 20327/0 20421/20324 20534/20418 20617/20531 20745/20614 20828/20742  warm_hit=99.5%
uncached tail per warm request: base ~6,180 tokens; cand ~420 tokens (remaining relay instructions: conversation turn instructions + tool bindings); control ~3 tokens
moved into cached prefix: ~5,760 tokens per warm request

== Unrelated
run-attempt.skills.native.test.ts "callable Ask User" (explicit command, no relay) times out under host load 28-46 on base too: proofs/206421/base-skills-native-full.log (base, unmodified file: Test timed out in 45000ms)

Residual: the fix leaves ~420 uncached tokens per warm request on gpt-6.2-sol (the relay's per-turn conversation instructions and tool bindings in instructions), vs ~3 on the appServer.command control. Moving that turn text into additionalContext is a separate, reported follow-up and not part of this PR.

@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
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. clawsweeper:intake:bug Preliminary submission classification; full source review pending. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. and removed clawsweeper:intake:bug 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: needs changes before merge.

What this changes

This PR moves shared Codex context into cacheable thread developer instructions while retaining personal overlays and turn context in the parent-only relay.

Example: A managed Codex turn makes five sequential tool calls with a loaded skills catalog.

  • Before: Supplied live results show roughly 6,180 uncached input tokens per warm request.
  • After: Supplied candidate results show roughly 420 uncached input tokens per warm request.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful production repair with direct behavioral evidence, held back by a confirmed snapshot-consumer failure and unresolved lint-check attribution.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied proof exercises the managed Codex app-server and relay, records append-only developer input across a multi-request turn, and includes real-model cache measurements plus personal-overlay, refresh, compaction, and existing-thread continuation controls.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Managed Codex conversations repeatedly process stable context as uncached input, consuming subscription quota or paid input unnecessarily.
Reason: The measured savings justify the focused change, and the collaborator-authored PR records the direction and shared-child-inheritance tradeoff.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR addresses a demonstrated caching defect with a focused production change, but it leaves a snapshot consumer asserting the old instruction layout and failing CI.

Reviewed head: 1a803295fa8f46a66c27521c96558bee27b2577a

Before merge

  • [P2] Update the snapshot consumer for thread-carried shared persona (P2) - The snapshot helper now sends shared persona through refreshableInstructions and returns an empty parent-local block for these ordinary scenarios. This retained test still requires the persona heading and file contents in parentLocal, then excludes those contents from shared at lines 310–313. Both Telegram and Discord scenarios therefore contradict the new layout; the exact-head CI annotation confirms the failure at line 287. Update this consumer to require shared persona in the thread section while preserving collaboration and user-input exclusions.

Findings

  • [P2] [P2] Update the snapshot consumer for thread-carried shared persona — test/scripts/prompt-snapshots.test.ts:287-289
Agent review details

How this fits together

OpenClaw prepares workspace and skill instructions, then the Codex adapter divides them between native thread developer input and parent-only relay instructions before provider dispatch.

flowchart LR
  A[Workspace and skills] --> B[Context preparation]
  B --> C[Shared thread instructions]
  B --> D[Personal overlay]
  E[Current turn context] --> F[Parent only relay]
  D --> F
  C --> G[Codex provider request]
  F --> G
Loading

Technical review

Best possible solution:

Keep the existing thread-carrier repair and update the snapshot consumer to verify shared persona there while retaining personal-overlay isolation.

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

Current-main source confirms the uncached relay placement, and the reporter's official-release comparison plus supplied base/candidate request evidence establish a strong reproduction path without this review executing target code.

Is this the best way to solve the issue?

Reusing the existing refreshable thread owner is a small, coherent repair with an explicitly accepted inheritance tradeoff; the retained snapshot contract must follow that cutover.

Full review comments:

  • [P2] [P2] Update the snapshot consumer for thread-carried shared persona — test/scripts/prompt-snapshots.test.ts:287-289
    The snapshot helper now sends shared persona through refreshableInstructions and returns an empty parent-local block for these ordinary scenarios. This retained test still requires the persona heading and file contents in parentLocal, then excludes those contents from shared at lines 310–313. Both Telegram and Discord scenarios therefore contradict the new layout; the exact-head CI annotation confirms the failure at line 287. Update this consumer to require shared persona in the thread section while preserving collaboration and user-input exclusions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Managed parent-only context delivery changes intended behavior with a stated reason (8169aac: Restore workspace instructions despite catalog-owned collaboration text without adding that context to native history or child prompts.)
  • Shared versus personal persona separation keeps the original intent (6f91eda: Deliver shared persona through inheritable thread instructions on uncovered connections while excluding selected personal profiles.)
  • Volatile prompt-hook context keeps the original intent (8da316f: Keep changing hook context out of persistent thread policy so background listeners do not block follow-up replies.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test test/scripts/prompt-snapshots.test.ts
  • pnpm test src/agents/harness/workspace-context.test.ts
  • pnpm test extensions/codex/src/app-server/run-attempt.native-background-outcome.test.ts
  • git diff --check

What I checked:

Likely related people:

  • Kimi Yu: Raw commit 6f91eda adds src/agents/harness/workspace-context.ts:143 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6f91eda9c72d; files: src/agents/harness/workspace-context.ts)
  • Peter Steinberger: Raw commit b856c0f adds extensions/codex/src/app-server/thread-lifecycle-run.ts:126 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b856c0f47459; files: extensions/codex/src/app-server/thread-lifecycle-run.ts)
  • Sarah Fortune: Raw commit dc8bfda adds src/agents/harness/workspace-context.ts:142 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: dc8bfda016a0; files: src/agents/harness/workspace-context.ts)

PR surface

Source -3, Tests +192, Docs +6. Total +195 across 23 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 11 44 47 -3
Tests 7 245 53 +192
Docs 5 55 49 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 23 344 149 +195

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.

Review metrics

Metric Value Why it matters
Warm request cache reuse 70.5–70.8% → 97.2–97.3% Three supplied live runs per arm show the intended reduction in repeated uncached context.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Managed native children can now inherit shared context, and the existing SDK preparation result gains an optional personal-only field; the maintainer-authored PR explicitly accepts the inheritance change.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • merge-risk: 🚨 compatibility: Managed native children can now inherit shared context, and the existing SDK preparation result gains an optional personal-only field; the maintainer-authored PR explicitly accepts the inheritance change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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, 5:02 AM ET / 10:02 UTC.

- Leave the refreshable skills/persona/memory section out of the thread config fingerprint,
  so a changed section no longer forces a cold resume that protected background work refuses.
- Record the delivered section for persistent live threads too, so the existing warm
  handoff and post-compaction restore deliver edits; ephemeral lifetime keys off generic policy.
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Review round 1 P1 proof (protected thread + skill edit), head fe38f61 vs previous head 8fd3970. Observed, no secrets:

== Review round 1 P1 (protected thread + skill edit) — 2026-11-27
prev head = 8fd3970192d6 ; fix head = fe38f61aa96e (bugloop-206421)
regression: extensions/codex/src/app-server/run-attempt.native-background-outcome.test.ts 'refreshes edited skills on a protected thread without a cold resume'
8fd: FAIL (appServer.command: 'Codex thread thread-1 still has background work after waiting for cleanup; stop its running work and retry.'; managed relay: run never accepted, execution budget timed out)  [proofs/206421/p1/8fd-background.log]
fix: PASS both (thread/start then one thread/inject_items with the new catalog; no thread/resume or unsubscribe; thread still protected)  [proofs/206421/p1/fix-background.log]
touched/affected codex suites on fix: 142+276+186 passed; 1 load timeout (run-attempt.test.ts usage limits) passed on rerun  [p1/fix-affected.log, p1/fix-usage-rerun.log, p1/fix-final-tests.log 277 passed]

== Live Gateway lane (openclaw agent, gpt-6.2-sol, native-shell 'sleep' listener on turn1, 'openclaw skills install' between turns; proofs/206421/live/run-p1.sh)
-- protected-main-managed
gateway-first.log background_refusals=0
listener running after turn1: yes
turn1: secs=74 refused_marker=ok reply_markers=[STARTED]
turn2: secs=17 refused_marker=ok reply_markers=[]
developer kind=thread-policy(creation) chars=5158 has_P1EDIT=false has_synthetic-01=false
usage input=21100 cached=0
usage input=21248 cached=14864
-- protected-p8fd-managed
gateway-first.log background_refusals=3
listener running after turn1: yes
turn1: secs=78 refused=ok status=ok reply="STARTED" skills_snapshot=86055bfc snapshot_has_P1EDIT=false
turn2: secs=24 refused=refused status=undefined reply="" skills_snapshot=undefined snapshot_has_P1EDIT=undefined
developer kind=thread-policy(creation) chars=25506 has_P1EDIT=false has_synthetic-01=true
usage input=21040 cached=0
usage input=21128 cached=20619
-- protected-p8fd-command
gateway-first.log background_refusals=3
listener running after turn1: yes
turn1: secs=21 refused=ok status=ok reply="STARTED" skills_snapshot=a08738b1 snapshot_has_P1EDIT=false
turn2: secs=13 refused=refused status=undefined reply="" skills_snapshot=undefined snapshot_has_P1EDIT=undefined
developer kind=thread-policy(creation) chars=25506 has_P1EDIT=false has_synthetic-01=true
usage input=20626 cached=0
usage input=20715 cached=20623
-- protected-fix-command
gateway-first.log background_refusals=0
gateway-restart.log background_refusals=0
listener running after turn1: yes
turn1: secs=42 refused=ok status=ok reply="STARTED" skills_snapshot=a07507a2 snapshot_has_P1EDIT=false
turn2: secs=12 refused=ok status=ok reply="P1EDIT-weather-radar" skills_snapshot=5dbd2681 snapshot_has_P1EDIT=true
turn3-after-restart: secs=49 refused=ok status=ok reply="P1EDIT-weather-radar" skills_snapshot=fc6151a9 snapshot_has_P1EDIT=true
developer kind=thread-policy(creation) chars=25555 has_P1EDIT=false has_synthetic-01=true
usage input=20299 cached=0
usage input=20386 cached=20296
developer kind=refresh-handoff(warm) chars=20522 has_P1EDIT=true has_synthetic-01=true
usage input=25977 cached=20383
developer kind=policy-handoff(cold-resume) chars=25541 has_P1EDIT=true has_synthetic-01=true
usage input=32854 cached=25974
-- protected-fix-managed
gateway-first.log background_refusals=0
gateway-restart.log background_refusals=0
listener running after turn1: no
turn1: secs=24 refused=ok status=ok reply="I couldn’t start it: native `exec_command` isn’t enabled for this turn." skills_snapshot=5316e15f snapshot_has_P1EDIT=false
turn2: secs=11 refused=ok status=ok reply="P1EDIT-weather-radar" skills_snapshot=31c1cf69 snapshot_has_P1EDIT=true
turn3-after-restart: secs=13 refused=ok status=ok reply="P1EDIT-weather-radar" skills_snapshot=59a2a0be snapshot_has_P1EDIT=true
developer kind=thread-policy(creation) chars=25555 has_P1EDIT=false has_synthetic-01=true
usage input=20761 cached=0
developer kind=refresh-handoff(warm) chars=20522 has_P1EDIT=true has_synthetic-01=true
usage input=26467 cached=20340
developer kind=policy-handoff(cold-resume) chars=25541 has_P1EDIT=true has_synthetic-01=true
usage input=33344 cached=26046
notes: protected-main-managed used the passive watcher under /tmp (symlink) and hit #204839 ('Saved Codex declarations require the original verified local binding'), a separate main defect; later runs use /private/tmp.
notes: fix-managed run had turn1 decline to start the listener (model), so its turn2 was unprotected; fix-command shows the protected case green.

# Conflicts:
#	test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/discord-group-codex-message-tool.md.diff
…thread

- A persona edit or removal now arrives as a refresh handoff on the live thread, not a cold resume;
  the latest section carries the new persona and nothing after it carries the old one.
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Rejected review findings: round 2 on fe38f61aa96e (keep_open, "the broader change to native-child context inheritance needs an owner decision").

This is an owner decision, and it has been made. On 2026-11-27 Ayaan delegated product calls on obvious bugs ("if you think anything is a really, really obvious bug, feel free to make the product decision there after consulting Fable 5.2"). We consulted Fable 5.2 and decided to keep the reversal of #142276's parent-only delivery:

  • Native children inherit the same shared persona, skills and memory text that every non-relay connection (appServer.command) already gives them since fix(codex): restore persona on remote app-server connections #162156. This PR makes the managed relay match that behavior; it adds no new exposure. The personal overlay stays parent-only (the fix(codex): restore persona on remote app-server connections #162156 privacy boundary is kept).
  • The cost is tokens in child threads, which now carry that shared text in their own developer instructions.
  • Keeping parent-only would leave every managed user paying the uncached tail measured on the final head (live gpt-6.2-sol, the reporter's five-tool-call turn, 2 runs per arm). Main 712db11dfc9e (managed): 70.6% warm hit, about 6,200 uncached input tokens per warm request and 51.8k uncached per turn. This PR (2ca1ebe03be6, managed): 97.2–97.3% warm hit, about 575 per warm request and 24.0k per turn. That is about 2.2x the uncached input per turn and about 11x per warm request.

No code change follows from this finding.

@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Final-head proof on 2ca1ebe03be6. Production code is identical to fe38f61aa96e plus a merge of main. Main is the merge parent, 712db11dfc9e. All runs are dist builds on the host with isolated state and real openai/gpt-6.2-sol.

Scripted relay lane (vitest-source; real bundled Codex 0.172.0 app-server and relay; synthetic upstream records the request bodies; run-attempt.skills.native.test.ts "keeps managed skills in the cached native prefix across a multi-request turn")

  • main 712db11dfc9e: FAIL, expected '## OpenClaw Skills…' not to contain 'SYNTHETIC_STABLE_SKILL_MARKER' (skills are in top-level instructions on every frame)
  • 2ca1ebe03be6: PASS

Live cache (the reporter's five-tool-call turn; per-request input/cached from the Codex rollout)

arm run requests (input/cached) warm hit uncached per warm request previous input not cached
main, managed r1 20780/0 20874/14680 20986/14774 21070/14886 21198/14970 21279/15098 70.6% ~6,200 6,100
main, managed r2 20780/0 20874/14680 20989/14774 21073/14889 21200/14973 21283/15100 70.6% ~6,200 6,100
this PR, managed r1 20518/0 21007/20097 21102/20586 21214/20681 21298/20793 21425/20877 21509/21004 97.2% ~586 421
this PR, managed r2 20614/0 21103/20193 21173/20682 21261/20752 21325/20840 21429/20904 21488/21008 97.3% ~567 421
appServer.command r1 20056/0 20149/20053 20261/20146 20345/20258 20473/20342 20556/20470 99.5% ~103 3
appServer.command r2 20008/0 20102/20005 20216/20099 20299/20213 20428/20296 20513/20425 99.5% ~104 3

Uncached input per turn: main 51.8k, this PR 24.0k, appServer.command 20.5k. The first attempt at this PR's r1 was discarded and rerun: the CLI's 10-second Gateway handshake timed out under host load before any model request was sent.

Live P1, managed relay (persistent thread; on turn 1 the model starts sleep in the background through native exec with a yield, and the rollout shows that call. Then openclaw skills install adds P1EDIT-weather-radar, and turn 2 asks for it.)

head run turn 1 listener after turn 1 turn 2 refusals developer items on turn 2 after Gateway restart (turn 3)
previous 8fd3970192d6 1 STARTED (exec, sleep, yield) running refused: "still has background work after waiting for cleanup; stop its running work and retry." 3 — —
2ca1ebe03be6 1 STARTED (exec, sleep, yield) running P1EDIT-weather-radar 0 one warm refresh handoff with the new skill, no cold resume; cached 21,237 of the previous 21,658 input P1EDIT-weather-radar via the cold-resume handoff
2ca1ebe03be6 2 STARTED (exec, sleep, yield) running P1EDIT-weather-radar 0 one warm refresh handoff with the new skill, no cold resume; cached 21,189 of the previous 21,610 input P1EDIT-weather-radar via the cold-resume handoff

…tale

- Native compaction rebuilds from the section a persistent thread was started or resumed with and can sample its continuation before any host handoff, so an in-place refresh could let a withdrawn persona or skill return for one request.
- Reuse now cold-resumes an unprotected persistent thread whose native section differs from the current one (idle edit, or the first turn after protected work ends); protected threads keep the in-place handoff instead of refusing.
- Tests: native compaction continuation on a persistent thread carries the withdrawn catalog's removal; protected edit refreshes in place, then cold-resumes once the listener ends; the external WebSocket persona test asserts the cold resume again.
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Proof for a286631217b9, which fixes review P2 on 2ca1ebe03be6: after an in-place refresh, native compaction could bring back the withdrawn section for one request.

Change: on reuse, a persistent thread is cold-resumed when its native section differs from the current one and nothing protects it (isCodexNativeSectionStale, thread-policy.ts). This covers an idle edit, and also the first turn after protected work ends. Protected threads still get the in-place handoff instead of the refusal. The comparison uses the existing in-memory record (nativeRefreshableInstructions), so no new state is added.

Tests (vitest-source; red side = the same test files copied onto 2ca1ebe03be6)

test 2ca1ebe03be6 a286631217b9
run-attempt.skills.native.test.ts "keeps a withdrawn catalog withdrawn after native compaction rebuilds the persistent thread" (real Codex binary, auto-compaction) FAIL: the continuation after compaction contains the withdrawn creation catalog alpha-native PASS
same test, incognito case (documented one-request reversion) PASS PASS
run-attempt.native-background-outcome.test.ts "refreshes edited skills on a protected thread, then cold-resumes once it ends" (managed relay, appServer.command) FAIL: only thread/start and thread/inject_items were sent, no cold resume after the listener ended PASS: start, one handoff while protected, then unsubscribe, resume and policy handoff with the edited catalog
"delivers and refreshes persona through an external WebSocket Harness" (asserts the cold resume again) FAIL (asserts the in-place refresh) PASS

Affected codex suites on a286631217b9: 116 + 330 + 58 passed. One failure was "callable Ask User", which timed out on the execution budget under host load; that test times out on main too (see results), and it passed in the targeted run.

Live (gpt-6.2-sol, dist build of a286631217b9)

lane result
P1 managed (background sleep via exec with a yield, then skills install, then turn 2) turn 2 answered P1EDIT-weather-radar; 0 refusals; one warm refresh handoff, no cold resume; turn 2 cached 21,284 of the previous 21,705 tokens. After a Gateway restart, turn 3 got the current section through the cold resume.
P1 appServer.command the same: P1EDIT-weather-radar, 0 refusals, warm refresh handoff; turn 2 cached 20,288 of the previous 20,291 tokens.
cache, main managed (712db11dfc9e) 20732/0 20825/14678 20938/14771 21021/14884 21149/14967 21231/15095, 70.7% warm hit
cache, this PR managed 20470/0 20959/20049 21029/20538 21118/20608 21182/20697 21286/20761 21346/20865, 97.3% warm hit
cache, appServer.command 20104/0 20197/20101 20309/20194 20392/20306 20521/20389 20604/20518, 99.5% warm hit

Remaining gap (stated in the body): if a section is edited while protected work runs and the thread compacts before that work ends, one continuation request can still see the previous section. It heals on the first unprotected turn.

- An idle persistent thread cold-resumes for a changed section; protected and incognito threads take the injected handoff, and the compaction limitations apply only to those.
… copy is stale

- Native compaction can sample its continuation from the thread's native section before any injected handoff. On the managed relay, while that native section differs from the current one (an edited incognito thread, or a protected persistent thread awaiting its cold resume), request instructions also carry the current section, as main did on every request.
- The fallback stops once the native copy matches; unedited threads never pay for it, and the section never holds the personal overlay.
- Test: managed incognito edit, withdrawal and compaction; every relayed request in the edited turns, including the continuation after compaction, carries the current catalog and the personal overlay once.
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Proof for 76341cb30f58, which adds the managed relay fallback: while a thread's native section differs from the current one, the relay also sends the current section in request instructions.

  • Red/green test (vitest-source): run-attempt.native-background-outcome.test.ts "refreshes managed catalogs on the thread and relays the edit through compaction". The scenario is a managed incognito thread: create the thread with catalog A, edit it to B, withdraw it (cron turn), set it back to B, then run native compaction inside that turn. The test checks the relayed instructions on the edited turns and on the request after compaction: each carries the current catalog (or the withdrawal notice), never A, and contains the personal overlay exactly once.
    • b2116aa45097: FAIL, the relayed instructions lack the withdrawal or current section.
    • 76341cb30f58: PASS.
  • Live P1, managed (gpt-6.2-sol, dist build of 76341cb30f58): turn 1 started the background sleep via exec with a yield. After the skill edit, turn 2 answered P1EDIT-weather-radar with 0 refusals through one warm refresh handoff. After a Gateway restart, turn 3 got the section through the cold resume and answered P1EDIT-weather-radar.
  • Local review on 76341cb30f58: "patch is correct", no findings.
  • Remaining gap: only connections without a relay (appServer.command) with protected work: one continuation request after compaction can see the previous section until that work ends. On main those threads refuse the turn instead.

@obviyus
obviyus merged commit cf0c99c into main Nov 27, 2026
143 checks passed
@obviyus
obviyus deleted the bugloop-206421 branch November 27, 2026 14:59
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in cf0c99c. With the managed Codex app-server, skills, shared persona and memory now go in the native thread's developer instructions instead of every request's top-level instructions, so warm requests reuse the prompt cache again (gpt-6.2-sol: about 70% before, about 97% after; the same binary via appServer.command measures about 99.5%). Edits arrive in place even while background work runs, and the relay carries the current section until the thread catches up. Thanks @brandon-julio-t for the precise measurements in #206421, and @NaturalMatchaKing for the persona A/B evidence in #204136.

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]>
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:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Codex harness: managed app-server's inference relay stops warm requests from reusing the prompt cache tail

1 participant