# Memory Compaction in Coding Agents: A Technical Comparison of Claude Code and OpenAI Codex

## Overview and Motivation

As coding agents mature into long-running, multi-step autonomous systems, context window management has become one of the most consequential engineering challenges in the field. Unlike simple chatbots, coding agents accumulate substantial context from file reads, tool outputs, shell command results, and iterative reasoning chains. When this accumulated context approaches the model's fixed token limit, the system must make architectural decisions about what to preserve, what to discard, and how to summarize — decisions that directly affect agent reliability, instruction fidelity, and task continuity.

This report provides a detailed technical breakdown of how Claude Code (Anthropic) and OpenAI Codex handle memory compaction and context management, drawing on official documentation, engineering writeups, and observable system behavior. Documented facts are clearly distinguished from inference throughout.

---

## Foundational Architecture: How Context Accumulates

### Claude Code's Layered Context Model

Claude Code does not operate as a single monolithic prompt. According to official Anthropic documentation and architectural analyses, it runs an **agentic loop** in which the model iteratively selects tools, reads files, executes shell commands, and accumulates outputs across multiple turns ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)). The context window at any given moment contains a layered stack of content:

| Layer | Content Type | Persistence Behavior |
|---|---|---|
| System instructions | Core behavioral rules | Reloaded after compaction |
| CLAUDE.md files | Project/directory-level instructions | Reloaded after compaction |
| Auto memory | Claude-written persistent notes | Reloaded after compaction |
| Loaded skills | Reusable instruction bundles | **Not automatically reloaded** |
| Conversation history | Prior turns and tool outputs | Subject to compaction/summarization |
| Tool outputs | File reads, shell results, search results | Cleared first during compaction |

This layered model is documented in the official Claude Code context window walkthrough and corroborated by third-party architectural analyses ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management); [Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)).

### OpenAI Codex's Context Assembly Model

OpenAI Codex operates differently at the architectural level. Rather than a persistent conversational session, Codex clones a repository into an isolated cloud sandbox for each task and assembles context dynamically from multiple sources ([Merced, 2026](https://iceberglakehouse.com/posts/2026-03-context-openai-codex/)). The context window for Codex is approximately **192,000 tokens**, and it is populated from:

- The cloned repository contents
- `AGENTS.md` files (analogous to Claude's `CLAUDE.md`)
- Skills (reusable instruction bundles)
- The task prompt
- Previous interactions (in the desktop app's persistent project memory)

Internally, according to a detailed source-code-level analysis of the `codex-rs` codebase, Codex stores conversation history as `ResponseItems` and builds each model prompt from normalized history combined with fixed session context, including developer instructions, agent/user instructions, and environment context ([OpenAI Community, 2026](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)).

---

## Compaction Mechanisms: Triggers and Thresholds

### Claude Code: Tiered Automatic Compaction

Claude Code implements what the official documentation describes as a **tiered compaction system** ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)). The system operates automatically when the context window approaches its limit, and the compaction process follows a documented priority order:

1. **Older tool outputs are cleared first** — these are the largest and most expendable items
2. **The conversation is summarized** if clearing tool outputs is insufficient

This tiered approach is a deliberate design choice: tool outputs (file reads, shell results) are treated as ephemeral, while the conversational reasoning chain is treated as more valuable and is preserved longer before being summarized.

**Automatic trigger**: Compaction fires automatically when the context indicator approaches its limit. The exact threshold is not publicly specified in the available documentation, but the system is described as continuous and non-interruptive — the session continues without user intervention ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)).

**Manual trigger**: Users can invoke `/compact` at any time to force compaction before a large task or when the context indicator is visibly approaching its limit. The official recommendation is to run `/compact` proactively before processing large files or initiating multi-step workflows in an already-long session ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)).

**Session JSONL records**: Compaction events are logged as `ContextCollapseSnapshotEntry` and `ContextCollapseCommitEntry` entries in the session JSONL file, providing an auditable record of when compaction occurred and what state was captured ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)).

### OpenAI Codex: Threshold-Based Auto-Compaction

According to source-code-level analysis of the `codex-rs` repository, Codex implements auto-compaction that triggers when token usage crosses a model-specific threshold. The documented default threshold is approximately **90% of the model's context window** (clamped to a safe value), unless overridden by user configuration ([OpenAI Community, 2026](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)).

The system continuously tracks token usage through a combination of server-reported usage and local estimates, emitting `TokenCount` updates to the UI. This is implemented in `codex-rs/core/src/codex.rs` at line 2603 and the protocol layer at `codex-rs/protocol/src/protocol.rs` line 1443 ([OpenAI Community, 2026](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)).

**Aggressive content bounding**: Before compaction even triggers, Codex applies aggressive truncation policies to noisy content:
- Tool outputs are truncated according to a token/byte policy
- Long text is **middle-truncated** (preserving beginning and end, discarding the middle)
- Function output content items are budgeted explicitly

These policies are implemented in `codex-rs/core/src/context_manager/history.rs` (line 327) and `codex-rs/core/src/truncate.rs` (lines 88 and 100) ([OpenAI Community, 2026](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)).

**Known failure mode**: A documented bug report from March 2026 describes auto-compression failing to trigger even when enabled, with Codex exhausting the context window after a single round of conversation when using non-standard model configurations. The root cause was identified as unsupported model overrides — Codex's auto-compaction is calibrated for built-in models and may not function correctly with custom provider configurations ([OpenAI Community Bug Report, 2026](https://community.openai.com/t/auto-compression-not-triggering-codex-still-runs-out-of-context-window/1376334)).

---

## What Is Preserved vs. Discarded

### Claude Code: Preservation Hierarchy

The distinction between what survives compaction and what does not is one of the most practically significant aspects of Claude Code's architecture ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)):

**Automatically reloaded after compaction:**
- System instructions
- `CLAUDE.md` content (project and subdirectory levels)
- Auto memory entries (notes Claude has written to `memdir/`)

**Not automatically reloaded:**
- **Skills** — this is explicitly documented as an exception. Skill listings do not reload automatically after compaction, meaning that long sessions may lose access to loaded skills unless they are explicitly re-invoked.

**Subject to compaction/loss:**
- Older tool outputs (cleared first)
- Earlier conversation turns (summarized if needed)
- Any instructions given only in earlier messages (not persisted to `CLAUDE.md`)

The official recommendation is unambiguous: **persistent instructions must be placed in `CLAUDE.md`, not in earlier messages**, because earlier messages will eventually be summarized or discarded ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/); [Claude Code Docs, 2026](https://code.claude.com/docs/en/context-window)).

**Compact Instructions**: `CLAUDE.md` supports a dedicated "Compact Instructions" section that controls what the compaction summarizer is directed to preserve. This gives developers programmatic influence over the summarization behavior, making the shape of long-session recall "partly programmable and partly structural" ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)).

### OpenAI Codex: Truncation and Budgeting

Codex's preservation strategy is more aggressive and less user-configurable at the content level. The system applies hard truncation policies rather than semantic summarization as the primary mechanism for content reduction ([OpenAI Community, 2026](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)):

| Content Type | Treatment |
|---|---|
| Tool outputs | Truncated by token/byte policy |
| Long text blocks | Middle-truncated (start and end preserved) |
| Function output items | Explicitly budgeted |
| `AGENTS.md` content | Persistent; reloaded per task |
| Skills | Persistent; reloaded per task |
| Task prompt | Always included |
| Conversation history | Normalized and bounded |

The middle-truncation strategy for long text is a notable engineering choice: it assumes that the beginning and end of a long output are more semantically significant than the middle, which is a reasonable heuristic for many code files and command outputs but may discard critical information in other cases. This is an inference about the design rationale, not an explicitly documented justification.

---

## Multi-Level Memory Architecture

### Claude Code's Memory Hierarchy

Claude Code implements a multi-level memory system that extends beyond simple context window management ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)):

1. **CLAUDE.md files** — hierarchical, project-scoped, always injected at session start. Multiple levels exist: project root, subdirectories (e.g., `src/CLAUDE.md`). Content is injected on every request, making verbosity costly.

2. **Auto memory (`/memory` command)** — Claude writes persistent notes to a `memdir/` directory abstraction. These notes survive across sessions and are reloaded after compaction. Users can view, edit, or clear stored notes via `/memory`.

3. **Conversation history** — ephemeral within a session, subject to compaction.

4. **Skills** — reusable instruction bundles that are loaded but, critically, not auto-reloaded after compaction.

This four-level hierarchy gives developers significant control over what persists, at what granularity, and at what token cost. The tradeoff is explicit: more persistent memory means more tokens consumed on every request, leaving less room for conversation and tool output ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)).

### OpenAI Codex's Memory Hierarchy

Codex's memory hierarchy is structured around its task-isolated architecture ([Merced, 2026](https://iceberglakehouse.com/posts/2026-03-context-openai-codex/)):

1. **AGENTS.md files** — repository-resident, loaded per task, analogous to `CLAUDE.md`
2. **Skills** — reusable bundles of instructions, templates, and scripts
3. **Task prompt** — the natural language description provided for each task
4. **Persistent project memory** — available in the desktop app, carries context across sessions
5. **Conversation history** — bounded and truncated within the `codex-rs` history manager

The key architectural difference from Claude Code is that Codex's default mode is **task-isolated**: each task gets a fresh sandbox with a fresh context assembly. This means compaction within a single task is less of a concern for shorter tasks, but long-running tasks that accumulate substantial tool output are still subject to the same 90%-threshold auto-compaction behavior.

---

## Observability and User Controls

### Claude Code

Claude Code provides three primary observability and control mechanisms:

- **`/context`** — live breakdown of context usage by category, with optimization suggestions
- **`/compact`** — manual compaction trigger
- **`/memory`** — inspection and management of persistent auto-memory notes
- **`/config`** — includes the ability to disable auto-compact (`auto-compact=false`) ([Sparkco AI, 2025](https://sparkco.ai/blog/mastering-claudes-context-window-a-2025-deep-dive))

The combination of `/context` for monitoring and `/compact` for manual control gives developers meaningful agency over compaction timing, which is particularly valuable before large tasks.

### OpenAI Codex

Codex provides token usage tracking via continuous `TokenCount` updates to the UI, derived from both server-reported usage and local estimates. The `config.toml` file allows threshold overrides for custom provider configurations, though this is explicitly documented as intended only for custom providers, not for built-in models ([OpenAI Community Bug Report, 2026](https://community.openai.com/t/auto-compression-not-triggering-codex-still-runs-out-of-context-window/1376334)).

---

## Risks and Practical Implications for Long-Running Agents

### Instruction Drift

The most significant risk in both systems is **instruction drift** — the gradual loss of behavioral constraints or task-specific instructions as context is compacted. In Claude Code, this risk is mitigated by the `CLAUDE.md` reload mechanism, but only if instructions have been explicitly placed there. Instructions given only in earlier messages will be summarized and may lose precision ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)). In Codex, `AGENTS.md` provides similar protection, but the aggressive truncation of tool outputs means that intermediate reasoning steps may be lost without a summarization fallback.

### Skill Loss in Claude Code

The documented exception for skills — that they are **not automatically reloaded after compaction** — is a subtle but consequential architectural detail. In long sessions that rely on loaded skills for specialized behavior, compaction may silently remove those capabilities without any visible error. This is a risk that developers must actively manage by either re-invoking skills after compaction or migrating critical skill content into `CLAUDE.md` ([Penligent AI, 2025](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)).

### Middle-Truncation Information Loss in Codex

Codex's middle-truncation strategy for long text is efficient but potentially lossy in ways that are difficult to predict. For code files where critical logic appears in the middle of a long function, or for command outputs where the most relevant error message appears mid-output, middle-truncation may discard exactly the information the agent needs. This is an inference about risk based on the documented truncation behavior, not a documented failure mode.

### Context Budget Consumption by Persistent Instructions

Both systems face the same fundamental tradeoff: more persistent context (verbose `CLAUDE.md` or `AGENTS.md` files) means fewer tokens available for conversation and tool output on every request. The official Claude Code documentation explicitly warns that verbose `CLAUDE.md` files "consume context budget on every request, leaving less room for conversation and tool output" ([Mintlify/Claude Code Source, 2026](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)).

### Coding Agents as Long-Context Processors

A March 2026 research paper from Carnegie Mellon and related institutions argues that coding agents are effective long-context processors precisely because they externalize context management into explicit, executable interactions — organizing text in file systems and manipulating it with native tools — rather than relying on latent attention mechanisms ([Cao et al., 2026](https://arxiv.org/abs/2603.20432)). Across multiple benchmarks, coding agents outperformed published state-of-the-art long-context methods by an average of **17.3%**. This finding suggests that the compaction mechanisms described above are not merely workarounds for a limitation, but are part of a fundamentally more effective approach to long-context processing.

---

## Comparative Summary

| Dimension | Claude Code | OpenAI Codex |
|---|---|---|
| Context window | Not publicly specified | ~192,000 tokens |
| Auto-compaction trigger | Approaches limit (threshold undisclosed) | ~90% of model window |
| Primary compaction method | Tiered: clear tool outputs → summarize | Truncation + budgeting; auto-compaction at threshold |
| Summarization | Yes, documented | Not explicitly documented as primary method |
| Persistent instructions | CLAUDE.md (auto-reloaded) | AGENTS.md (per-task reload) |
| Skills after compaction | **Not auto-reloaded** (documented exception) | Reloaded per task (task-isolated architecture) |
| Auto-memory | Yes (`memdir/`, `/memory` command) | Desktop app persistent project memory |
| Manual compaction | `/compact` command | Not documented as a user-facing command |
| Observability | `/context`, `/memory`, `/compact` | Continuous `TokenCount` UI updates |
| Disable auto-compact | `/config auto-compact=false` | `config.toml` override (custom providers only) |
| Compaction audit trail | Session JSONL entries | Not documented |
| Known failure modes | Skill loss after compaction | Auto-compaction failure with unsupported model configs |

---

## Conclusion

Both Claude Code and OpenAI Codex have implemented sophisticated, multi-layered approaches to context compaction that go well beyond simple summarization. Claude Code's tiered compaction system — clearing tool outputs first, then summarizing conversation — combined with its multi-level memory hierarchy (`CLAUDE.md`, auto-memory, skills) and user-controllable compaction via `/compact` and `/context`, represents a more transparent and user-configurable approach. The documented exception for skills not reloading after compaction is a meaningful operational risk that developers must actively manage.

OpenAI Codex's approach is architecturally distinct: its task-isolated sandbox model reduces the frequency of within-session compaction for shorter tasks, while its aggressive truncation policies (including middle-truncation) and 90%-threshold auto-compaction handle longer tasks. The source-code-level evidence from `codex-rs` reveals a more engineering-driven, less user-configurable system, with known failure modes when operating outside its intended model configurations.

For practitioners running long-duration coding agents, the practical implication is clear: **persistent instructions must be placed in configuration files (`CLAUDE.md` or `AGENTS.md`), not in conversational messages**, and developers should actively monitor context usage and trigger manual compaction before large tasks rather than relying entirely on automatic mechanisms.

---

## References

Cao, W., Yin, X., Dhingra, B., & Zhou, S. (2026, March 20). *Coding agents are effective long-context processors*. arXiv. [https://arxiv.org/abs/2603.20432](https://arxiv.org/abs/2603.20432)

Claude Code Documentation. (2026). *Explore the context window*. Anthropic. [https://code.claude.com/docs/en/context-window](https://code.claude.com/docs/en/context-window)

Merced, A. (2026, March 7). *Context management strategies for OpenAI Codex: A complete guide across browser, CLI, and app*. Alex Merced's Lakehouse Blog. [https://iceberglakehouse.com/posts/2026-03-context-openai-codex/](https://iceberglakehouse.com/posts/2026-03-context-openai-codex/)

Mintlify/Saurav Shakya. (2026, March 31). *Context management - Claude Code source*. Mintlify. [https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management](https://www.mintlify.com/saurav-shakya/Claude_Code-_Source_Code/advanced/context-management)

OpenAI Developer Community. (2026, February 11). *Best practices for cost-efficient, high-quality context management in long AI chats*. OpenAI Community. [https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996](https://community.openai.com/t/best-practices-for-cost-efficient-high-quality-context-management-in-long-ai-chats/1373996)

OpenAI Developer Community. (2026, March 11). *Auto compression not triggering – Codex still runs out of context window*. OpenAI Community Bugs. [https://community.openai.com/t/auto-compression-not-triggering-codex-still-runs-out-of-context-window/1376334](https://community.openai.com/t/auto-compression-not-triggering-codex-still-runs-out-of-context-window/1376334)

Penligent AI. (2025). *Inside Claude Code: The architecture behind tools, memory, hooks, and MCP*. Penligent. [https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/](https://www.penligent.ai/hackinglabs/inside-claude-code-the-architecture-behind-tools-memory-hooks-and-mcp/)

Sparkco AI. (2025). *Mastering Claude's context window: A 2025 deep dive*. Sparkco. [https://sparkco.ai/blog/mastering-claudes-context-window-a-2025-deep-dive](https://sparkco.ai/blog/mastering-claudes-context-window-a-2025-deep-dive)

---

## Verification Addendum

This addendum was added after the GPT Researcher run because the generated report mixed official documentation, third-party writeups, and community/forum analysis. The high-level shape is useful, but the Codex-specific claims should lean on official OpenAI sources where available.

### OpenAI Codex: Officially Documented Compaction

OpenAI's engineering post [Unrolling the Codex agent loop](https://openai.com/index/unrolling-the-codex-agent-loop/) is the strongest official source found in this pass.

Documented facts from that post:

- Codex grows a conversation thread by including messages and tool calls from previous turns in later prompts.
- Codex avoids using `previous_response_id` today so requests can remain stateless and compatible with Zero Data Retention configurations.
- Prompt caching matters because exact prompt-prefix matches let Codex reuse computation across turns.
- Codex's general strategy for avoiding context-window exhaustion is to compact the conversation once token count exceeds a threshold.
- Earlier Codex compaction required manual `/compact` and summarized the conversation with custom instructions.
- Newer Codex uses the Responses API `/responses/compact` endpoint, which returns a smaller list of items that can replace the prior `input`.
- The compacted item list includes a special `type=compaction` item with opaque `encrypted_content`, preserving model-side latent continuity while freeing context.
- Codex now automatically uses this endpoint when `auto_compact_limit` is exceeded.

Important caveat: the generated report's more specific claims about an approximately 90% threshold, exact context window size, line numbers in `codex-rs`, middle truncation, and UI token-count internals came from community/source-code analysis, not from the official OpenAI article. Treat those as plausible implementation notes to verify against the open-source Codex repository before citing them as fact.

### Anthropic Claude: Officially Documented Context Management

Anthropic's API docs describe three distinct mechanisms that match the user's "three levels" intuition, though the naming is more precise as "context management strategies" rather than a single three-level Claude Code memory stack.

Official sources:

- [Compaction](https://platform.claude.com/docs/en/build-with-claude/compaction)
- [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing)
- [Claude Code memory](https://docs.anthropic.com/en/docs/claude-code/memory)

Documented mechanisms:

1. Server-side compaction: when input tokens exceed the configured threshold, Claude summarizes the current conversation, creates a `compaction` block, and subsequent requests drop all message blocks before that block while continuing from the summary. The default trigger is documented as 150,000 tokens, with a minimum trigger of 50,000 tokens.
2. Context editing: Anthropic supports server-side clearing strategies for specific content types. `clear_tool_uses_20250919` removes the oldest tool results first, preserving recent tool uses; `clear_thinking_20251015` manages how many thinking blocks remain in context.
3. SDK client-side compaction: when using the SDK tool runner, the SDK can monitor token usage, ask Claude to generate a structured summary in `<summary>` tags, replace the full message history with that summary, and continue from the compacted state. Anthropic says server-side compaction is generally preferred.

The memory tool can be combined with context editing: when tool results are about to be cleared, Claude can be warned to preserve important information into memory files first. This is the closest official mechanism to "offloading active context into durable memory" in the Anthropic docs.

### Practical Synthesis

For long-running coding agents, the robust architecture is not just "summarize older chat." It is a stack:

- bounded tool outputs and context editing for high-volume, low-durable-value data
- compaction summaries for conversation/task continuity
- project memory files (`CLAUDE.md`, `AGENTS.md`, or explicit memory files) for durable instructions and reusable facts
- prompt caching discipline so compaction and mid-thread config changes do not destroy cache locality more than necessary

The strongest contrast:

- Anthropic documents multiple context-management controls directly in the Claude API: server-side compaction, context editing, SDK compaction, and memory-tool interplay.
- OpenAI documents Codex's agent-loop compaction at the harness level: Codex uses `/responses/compact` automatically after `auto_compact_limit`, replacing `input` with a compacted list of items that includes a `type=compaction` block.

Open research gap: the exact Codex compaction prompt, scoring/ranking criteria for what is preserved, and threshold defaults should be verified directly from the open-source Codex repository before being treated as settled implementation detail.
