Status
Draft implementation specification.Goal
Make the bundled Codex app-server harness honor the same OpenClaw context-engine lifecycle contract that embedded OpenClaw turns already honor. A session using provider/modelagentRuntime.id: "codex" or a codex/* model
should still let the selected context-engine plugin, such as
lossless-claw, control context assembly, post-turn ingest, maintenance, and
OpenClaw-level compaction policy as far as the Codex app-server boundary allows.
Non-goals
- Do not reimplement Codex app-server internals.
- Do not make Codex native thread compaction produce a lossless-claw summary.
- Do not require non-Codex models to use the Codex harness.
- Do not change ACP/acpx session behavior. This specification is for the non-ACP embedded agent harness path only.
- Do not make third-party plugins register Codex app-server extension factories; the existing bundled-plugin trust boundary remains unchanged.
Current architecture
The embedded run loop resolves the configured context engine once per run before selecting a concrete low-level harness:src/agents/embedded-agent-runner/run.ts- initializes context-engine plugins
- calls
resolveContextEngine(params.config) - passes
contextEngineandcontextTokenBudgetintorunEmbeddedAttemptWithBackend(...)
runEmbeddedAttemptWithBackend(...) delegates to the selected agent harness:
src/agents/embedded-agent-runner/run/backend.tssrc/agents/harness/selection.ts
extensions/codex/index.tsextensions/codex/harness.ts
EmbeddedRunAttemptParams
as built-in OpenClaw attempts:
extensions/codex/src/app-server/run-attempt.ts
thread/start, thread/resume, and turn/start, and can observe
notifications, but it cannot change Codex’s internal thread store or native
compactor.
Current gap
Built-in OpenClaw attempts call the context-engine lifecycle directly:- bootstrap/maintenance before the attempt
- assemble before the model call
- afterTurn or ingest after the attempt
- maintenance after a successful turn
- context-engine compaction for engines that own compaction
src/agents/embedded-agent-runner/run/attempt.tssrc/agents/embedded-agent-runner/run/attempt.context-engine-helpers.tssrc/agents/embedded-agent-runner/context-engine-maintenance.ts
params.contextEngine.bootstrap,
params.contextEngine.assemble, params.contextEngine.afterTurn,
params.contextEngine.ingestBatch, params.contextEngine.ingest, or
params.contextEngine.maintain.
Relevant Codex code:
extensions/codex/src/app-server/run-attempt.tsextensions/codex/src/app-server/thread-lifecycle.tsextensions/codex/src/app-server/event-projector.tsextensions/codex/src/app-server/compact.ts
Desired behavior
For Codex harness turns, OpenClaw should preserve this lifecycle:- Read the mirrored OpenClaw session transcript.
- Bootstrap the active context engine when a previous session file exists.
- Run bootstrap maintenance when available.
- Assemble context using the active context engine.
- Convert the assembled context into Codex-compatible inputs.
- Start or resume the Codex thread with developer instructions that include any
context-engine
systemPromptAddition. - Start the Codex turn with the assembled user-facing prompt.
- Mirror the Codex result back into the OpenClaw transcript.
- Call
afterTurnif implemented, otherwiseingestBatch/ingest, using the mirrored transcript snapshot. - Run turn maintenance after successful non-aborted turns.
- Preserve Codex native compaction signals and OpenClaw compaction hooks.
Design constraints
Codex app-server remains canonical for native thread state
Codex owns its native thread and any internal extended history. OpenClaw should not try to mutate the app-server’s internal history except through supported protocol calls. OpenClaw’s transcript mirror remains the source for OpenClaw features:- chat history
- search
/newand/resetbookkeeping- future model or harness switching
- context-engine plugin state
Context engine assembly must be projected into Codex inputs
The context-engine interface returns OpenClawAgentMessage[], not a Codex
thread patch. Codex app-server turn/start accepts a current user input, while
thread/start and thread/resume accept developer instructions.
Therefore the implementation needs a projection layer. The safe first version
should avoid pretending it can replace Codex internal history. It should inject
assembled context as deterministic prompt/developer-instruction material around
the current turn.
Prompt-cache stability matters
For engines like lossless-claw, the assembled context should be deterministic for unchanged inputs. Do not add timestamps, random ids, or nondeterministic ordering to generated context text.Runtime selection semantics do not change
Harness selection remains as-is:runtime: "openclaw"selects the built-in OpenClaw harnessruntime: "codex"selects the registered Codex harnessruntime: "auto"lets plugin harnesses claim supported providers- unmatched
autoruns use the built-in OpenClaw harness
Implementation plan
1. Export or relocate reusable context-engine attempt helpers
Today the reusable lifecycle helpers live under the embedded agent runner:src/agents/embedded-agent-runner/run/attempt.context-engine-helpers.tssrc/agents/embedded-agent-runner/run/attempt.prompt-helpers.tssrc/agents/embedded-agent-runner/context-engine-maintenance.ts
src/agents/harness/context-engine-lifecycle.ts
runAttemptContextEngineBootstrapassembleAttemptContextEnginefinalizeAttemptContextEngineTurnbuildAfterTurnRuntimeContextbuildAfterTurnRuntimeContextFromUsage- a small wrapper around
runContextEngineMaintenance
bootstrapHarnessContextEngineassembleHarnessContextEnginefinalizeHarnessContextEngineTurnbuildHarnessContextEngineRuntimeContextrunHarnessContextEngineMaintenance
2. Add a Codex context projection helper
Add a new module:extensions/codex/src/app-server/context-engine-projection.ts
- Accept the assembled
AgentMessage[], original mirrored history, and current prompt. - Determine which context belongs in developer instructions vs current user input.
- Preserve the current user prompt as the final actionable request.
- Render prior messages in a stable, explicit format.
- Avoid volatile metadata.
- Put
systemPromptAdditioninto developer instructions. - Put the assembled transcript context before the current prompt in
promptText. - Label it clearly as OpenClaw assembled context.
- Keep current prompt last.
- Exclude duplicate current user prompt if it already appears at the tail.
3. Wire bootstrap before Codex thread startup
Inextensions/codex/src/app-server/run-attempt.ts:
- Read mirrored session history as today.
- Determine whether the session file existed before this run. Prefer a helper
that checks
fs.stat(params.sessionFile)before mirroring writes. - Open a
SessionManageror use a narrow session manager adapter if the helper requires it. - Call the neutral bootstrap helper when
params.contextEngineexists.
sessionKey convention as the Codex tool bridge and transcript
mirror. Today Codex computes sandboxSessionKey from params.sessionKey or
params.sessionId; use that consistently unless there is a reason to preserve
raw params.sessionKey.
4. Wire assemble before thread/start / thread/resume and turn/start
In runCodexAppServerAttempt:
- Build dynamic tools first, so the context engine sees the actual available tool names.
- Read mirrored session history.
- Run context-engine
assemble(...)whenparams.contextEngineexists. - Project the assembled result into:
- developer instruction addition
- prompt text for
turn/start
- compute base developer instructions with
buildDeveloperInstructions(params) - apply context-engine assembly/projection
- run
before_prompt_buildwith the projected prompt/developer instructions
systemPromptAddition to the final system prompt after its prompt pipeline. The
important invariant is that both context engine and hooks get a deterministic,
documented order.
Recommended order for first implementation:
buildDeveloperInstructions(params)- context-engine
assemble() - append/prepend
systemPromptAdditionto developer instructions - project assembled messages into prompt text
resolveAgentHarnessBeforePromptBuildResult(...)- pass final developer instructions to
startOrResumeThread(...) - pass final prompt text to
buildTurnStartParams(...)
5. Preserve prompt-cache stable formatting
The projection helper must produce byte-stable output for identical inputs:- stable message order
- stable role labels
- no generated timestamps
- no object key order leakage
- no random delimiters
- no per-run ids
6. Wire post-turn after transcript mirroring
Codex’sCodexAppServerEventProjector builds a local messagesSnapshot for the
current turn. mirrorTranscriptBestEffort(...) writes that snapshot into the
OpenClaw transcript mirror.
After mirroring succeeds or fails, call the context-engine finalizer with the
best available message snapshot:
- Prefer full mirrored session context after the write, because
afterTurnexpects the session snapshot, not only the current turn. - Fall back to
historyMessages + result.messagesSnapshotif the session file cannot be reopened.
afterTurn with the fallback snapshot, but log
that the context engine is ingesting from fallback turn data.
7. Normalize usage and prompt-cache runtime context
Codex results include normalized usage from app-server token notifications when available. Pass that usage into the context-engine runtime context. If Codex app-server eventually exposes cache read/write details, map them intoContextEnginePromptCacheInfo. Until then, omit promptCache rather than
inventing zeros.
8. Compaction policy
There are two compaction systems:- OpenClaw context-engine
compact() - Codex app-server native
thread/compact/start
/compact and explicit OpenClaw compaction
When the selected context engine has info.ownsCompaction === true, explicit
OpenClaw compaction should prefer the context engine’s compact() result for
the OpenClaw transcript mirror and plugin state.
When the selected Codex harness has a native thread binding, we may additionally
request Codex native compaction to keep the app-server thread healthy, but this
must be reported as a separate backend action in details.
Recommended behavior:
- If
contextEngine.info.ownsCompaction === true:- call context-engine
compact()first - then best-effort call Codex native compaction when a thread binding exists
- return the context-engine result as the primary result
- include Codex native compaction status in
details.codexNativeCompaction
- call context-engine
- If the active context engine does not own compaction:
- preserve current Codex native compaction behavior
extensions/codex/src/app-server/compact.ts or
wrapping it from the generic compaction path, depending on where
maybeCompactAgentHarnessSession(...) is invoked.
In-turn Codex native contextCompaction events
Codex may emitcontextCompaction item events during a turn. Keep the current
before/after compaction hook emission in event-projector.ts, but do not treat
that as a completed context-engine compaction.
For engines that own compaction, emit an explicit diagnostic when Codex performs
native compaction anyway:
- stream/event name: existing
compactionstream is acceptable - details:
{ backend: "codex-app-server", ownsCompaction: true }
9. Session reset and binding behavior
The existing Codex harnessreset(...) clears the Codex app-server binding from
the OpenClaw session file. Preserve that behavior.
Also ensure context-engine state cleanup continues to happen through existing
OpenClaw session lifecycle paths. Do not add Codex-specific cleanup unless the
context-engine lifecycle currently misses reset/delete events for all harnesses.
10. Error handling
Follow built-in OpenClaw semantics:- bootstrap failures warn and continue
- assemble failures warn and fall back to unassembled pipeline messages/prompt
- afterTurn/ingest failures warn and mark post-turn finalization unsuccessful
- maintenance runs only after successful, non-aborted, non-yield turns
- compaction errors should not be retried as fresh prompts
- If context projection fails, warn and fall back to the original prompt.
- If transcript mirror fails, still attempt context-engine finalization with fallback messages.
- If Codex native compaction fails after context-engine compaction succeeds, do not fail the whole OpenClaw compaction when the context engine is primary.
Test plan
Unit tests
Add tests underextensions/codex/src/app-server:
-
run-attempt.context-engine.test.ts- Codex calls
bootstrapwhen a session file exists. - Codex calls
assemblewith mirrored messages, token budget, tool names, citations mode, model id, and prompt. systemPromptAdditionis included in developer instructions.- Assembled messages are projected into the prompt before current request.
- Codex calls
afterTurnafter transcript mirroring. - Without
afterTurn, Codex callsingestBatchor per-messageingest. - Turn maintenance runs after successful turns.
- Turn maintenance does not run on prompt error, abort, or yield abort.
- Codex calls
-
context-engine-projection.test.ts- stable output for identical inputs
- no duplicate current prompt when assembled history includes it
- handles empty history
- preserves role order
- includes system prompt addition only in developer instructions
-
compact.context-engine.test.ts- owning context engine primary result wins
- Codex native compaction status appears in details when also attempted
- Codex native failure does not fail owning context-engine compaction
- non-owning context engine preserves current native compaction behavior
Existing tests to update
extensions/codex/src/app-server/run-attempt.test.tsif present, otherwise nearest Codex app-server run tests.extensions/codex/src/app-server/event-projector.test.tsonly if compaction event details change.src/agents/harness/selection.test.tsshould not need changes unless config behavior changes; it should remain stable.- Built-in harness context-engine tests should continue to pass unchanged.
Integration / live tests
Add or extend live Codex harness smoke tests:- configure
plugins.slots.contextEngineto a test engine - configure
agents.defaults.modelto acodex/*model - configure provider/model
agentRuntime.id = "codex" - assert test engine observed:
- bootstrap
- assemble
- afterTurn or ingest
- maintenance
Observability
Add debug logs around Codex context-engine lifecycle calls:codex context engine bootstrap started/completed/failedcodex context engine assemble appliedcodex context engine finalize completed/failedcodex context engine maintenance skippedwith reasoncodex native compaction completed alongside context-engine compaction
sessionIdsessionKeyredacted or omitted according to existing logging practiceengineIdthreadIdturnIdassembledMessageCountestimatedTokenshasSystemPromptAddition
Migration / compatibility
This should be backward-compatible:- If no context engine is configured, legacy context engine behavior should be equivalent to today’s Codex harness behavior.
- If context-engine
assemblefails, Codex should continue with the original prompt path. - Existing Codex thread bindings should remain valid.
- Dynamic tool fingerprinting should not include context-engine output; otherwise every context change could force a new Codex thread. Only the tool catalog should affect the dynamic tool fingerprint.
Open questions
-
Should assembled context be injected entirely into the user prompt, entirely
into developer instructions, or split?
Recommendation: split. Put
systemPromptAdditionin developer instructions; put assembled transcript context in the user prompt wrapper. This best matches the current Codex protocol without mutating native thread history. - Should Codex native compaction be disabled when a context engine owns compaction? Recommendation: no, not initially. Codex native compaction may still be necessary to keep the app-server thread alive. But it must be reported as native Codex compaction, not as context-engine compaction.
-
Should
before_prompt_buildrun before or after context-engine assembly? Recommendation: after context-engine projection for Codex, so generic harness hooks see the actual prompt/developer instructions Codex will receive. If built-in harness parity requires the opposite, encode the chosen order in tests and document it here. - Can Codex app-server accept a future structured context/history override? Unknown. If it can, replace the text projection layer with that protocol and keep the lifecycle calls unchanged.
Acceptance criteria
- A
codex/*embedded harness turn invokes the selected context engine’s assemble lifecycle. - A context-engine
systemPromptAdditionaffects Codex developer instructions. - Assembled context affects the Codex turn input deterministically.
- Successful Codex turns call
afterTurnor ingest fallback. - Successful Codex turns run context-engine turn maintenance.
- Failed/aborted/yield-aborted turns do not run turn maintenance.
- Context-engine-owned compaction remains primary for OpenClaw/plugin state.
- Codex native compaction remains auditable as native Codex behavior.
- Existing built-in harness context-engine behavior is unchanged.
- Existing Codex harness behavior is unchanged when no non-legacy context engine is selected or when assembly fails.