7. Building the Context Window

Codex builds the model’s context window as an append-only log. On the first step of a window it renders every piece of world state in full; on later steps each section compares itself with a stored snapshot and appends only what changed. The bytes already sent never change, so the provider’s prompt cache keeps matching the prefix.

Chapter 6 showed that every sampling request resends the whole conversation. This chapter explains what that conversation contains and in what order. Some of it is the user’s own words and the model’s replies. The rest is context the harness supplies: instructions, the permission rules, the project’s AGENTS.md files, the working directory and shell, and the skills and tools on offer.

The hard part is change. A user can switch directories, approval policies, or models in the middle of a thread, and an AGENTS.md file can change on disk. Codex must tell the model without rewriting what it already sent. The answer is a small state machine per kind of context, called a world-state section, plus a normalization pass that runs on a copy of history just before each request.

The picture

Turn settings and AGENTS.md files feed an ordered WorldState; on the first step of a window it renders the initial context in full and writes prefix items into the ContextManager, while on later steps it renders only a diff and appends small messages; the user’s message is appended too; for_prompt normalizes a clone of history into Prompt.input for the request builder.

Follow the arrows from left to right. Turn settings and AGENTS.md files become sections of a WorldState, rebuilt for every step. The solid green path runs once per context window: render_full produces the initial context, which assemble_initial_context groups into a few messages at the front of history. The dashed purple path runs on every later step: render_history_diff compares each section with its stored snapshot and appends only what changed. The user’s message joins the same history. Just before sampling, ContextManager::for_prompt normalizes a clone of that history, and the result becomes Prompt.input for the request builder from Chapter 6.

The order of the input array

A snapshot test in codex-rs/core/tests/suite/snapshots/ records the model-visible layout of two turns, where the second turn changes the working directory and the approval policy. The first request looks like this:

00:message/developer:
    <MODEL_INSTRUCTIONS>
01:message/developer[3]:
    [01] <SKILLS_INSTRUCTIONS>
    [02] <PERMISSIONS_INSTRUCTIONS>
    [03] <tools> Deferred tool namespaces: ... </tools>
02:message/user:
    <ENVIRONMENT_CONTEXT>
03:message/user:
    first turn

The general order comes from Session::assemble_initial_context in codex-rs/core/src/session/mod.rs. The table lists the slots of a new window.

Slot Role Content
Prefix developer Base instructions and tool declarations, in incremental-tools windows
Bundle developer One merged message: developer instructions, then world-state developer fragments
Standalone developer Items that must stay separate, such as multi-agent role instructions
Mode developer The multi-agent mode message, if any
Context user One merged message: AGENTS.md, then environment context
Guardian developer The policy prompt, only for guardian reviewer sessions
Managed developer Administrator-required developer instructions, last

In a window without incremental tools, such as one for the non-Lite gpt-5.5, the base instructions are not in history; the request builder adds them in front of everything on each request (Chapter 6). Incremental tools are the default for the Lite catalog models. The user’s first message follows the initial context.

assemble_initial_context sorts each rendered fragment into these slots by role and by the fragment’s opening marker. The core of that sort, from codex-rs/core/src/session/mod.rs:

match fragment.role() {
    "developer"
        if fragment.markers().0 == ModelSwitchInstructions::type_markers().0 =>
    {
        // New-model instructions must precede the rest of the developer context.
        developer_sections.insert(0, fragment.render_fragment());
    }
    "developer" if fragment.markers().0 == MULTI_AGENT_MODE_OPEN_TAG => {
        initial_multi_agent_mode = Some(fragment);
    }
    // ...
    "developer"
        if update.placement == Placement::Standalone
            && fragment.markers().0.is_empty() =>
    {
        standalone_items.push(fragment.render_fragment().into());
    }
    "developer" => developer_sections.push(fragment.render_fragment()),
    "user" => contextual_user_sections.push(fragment.render_fragment()),
    _ => {}
}

Merging keeps related instructions in one message, as separate content parts in a fixed order. The model sees one developer briefing and one contextual user message per window, not a scatter of small messages.

World state: sections, snapshots, and diffs

The section contract

Each kind of context implements WorldStateSection from codex-rs/core/src/context/world_state/mod.rs. A section has a stable string ID, which rollouts persist, and a Snapshot type that holds only the data needed to decide what the model must be told next. Its one required method is render_diff. It receives a PreviousSectionState, which is Absent (the model has never seen this section), Unknown (history shows the section but the typed snapshot is gone), or Known(&snapshot). It returns an optional new snapshot and a list of WorldStateUpdate values.

Each update carries a Placement. Prefix items go at the very front of a new window, Standalone items get their own message, and Mergeable fragments join neighbors of the same role. merge_world_state_updates in context_manager/updates.rs applies that rule.

WorldState stores sections in an IndexMap, so render order equals registration order. Session::build_world_state_for_step in core/src/session/world_state.rs registers them in a fixed sequence: command sessions, top-level tools, the model, an optional token budget, context-window guidance, realtime state, AGENTS.md, permissions, collaboration mode, persistent mode, environments, apps, plugins, deferred tools, extension sections, multi-agent hints, the model catalog, and managed developer instructions. One extension section is special: add_extension_section moves host_skills to just before permissions, which is why skills come first in the bundle above.

Full render and diff render

WorldState::render_full renders every section as Absent, so each produces its complete text. render_history_diff looks up each section’s stored snapshot. If none exists, it searches retained history for the section’s earlier fragment, which is how threads written by older versions migrate. Most sections return no updates when nothing changed.

The first step of a thread calls try_publish_initial_context, which renders in full and appends the result. Every later step calls record_context_updates_and_set_reference_context_item, which renders a diff, appends the merged items, and stores the new snapshot as the baseline. A one-permit Semaphore ensures that only one publisher installs the initial prefix.

The snapshots are persisted, not just held in memory. publish_step_context writes a RolloutItem::WorldState whose WorldStateItem is either a full baseline or a patch; the protocol type’s doc comment calls it “persisted comparison state used to resume model-visible world-state diffing.” A resumed thread therefore diffs against what the model actually saw before the restart, not against an empty state, and does not resend the whole context (Chapter 24 covers resume).

A snapshot is compact. The permissions section stores a SHA-1 fingerprint of its rendered text, a WorldStateHash, not the text itself. The environment section stores structured fields, so its diff can name just the fields that moved. The environment section’s own snapshot test shows a change of date, time zone, network rules, and file-system profile, with the working directory unchanged:

<environment_context>
  <current_date>2026-06-20</current_date>
  <timezone>America/Los_Angeles</timezone>
  <network enabled="true"><allowed>new.example.com</allowed><denied>blocked.example.com</denied></network>
  <filesystem><permission_profile type="external"><file_system type="external" /></permission_profile></filesystem>
</environment_context>

Why diffs keep the prefix stable

The design is a memento plus an event log. Each section remembers what the model last saw, and changes are appended as new events rather than written over old ones. The test overrides_turn_context_but_keeps_cached_prefix_and_key_constant checks the outcome: after a turn override, the first request is still an exact prefix of the second. Editing the original permissions message in place would have been simpler to read, but it would break the cached prefix at item 1 and make every later token a cache miss.

The cost is that stale context stays in the window. After two directory changes, history holds three environment messages, and the model must treat the latest as current. Compaction (Chapter 8) is what finally clears them, because it renders a fresh full context for the new window.

Instructions from config, policy, and administrators

Three instruction sources sit in the developer bundle or next to it. The developer_instructions config value goes first in the merged bundle. Guardian reviewer sessions are the exception: assemble_initial_context keeps their policy prompt out of the bundle as its own GuardianPolicy message, so “the guardian subagent sees a distinct, easy-to-audit instruction block.” Administrator requirements can add additional_developer_instructions, which render as a ManagedDeveloperInstructions message placed last.

Permission and sandbox instructions

PermissionsState renders a <permissions instructions> developer fragment that describes the sandbox and the approval policy in words the model can act on. Its section test shows the read-only case:

<permissions instructions>
Read only.
Ask for approval.
</permissions instructions>

The real text is longer and comes partly from the model’s catalog messages; the test uses stub descriptions. When the profile changes to full access, the diff appends a new block that reads “Full access.” With the per_environment_context feature, the section emits one <environment id="..."> block per environment. Setting include_permissions_instructions = false swaps in CompactPermissionsState, which keeps only the approved command prefixes. Chapters 13 and 14 explain the policies themselves.

AGENTS.md

Discovery

AGENTS.md files are the project’s instructions to the agent. load_project_instructions in codex-rs/core/src/agents_md.rs returns nothing when the active project is untrusted or project_doc_max_bytes is 0. Otherwise agents_md_paths finds the project root by walking up from the working directory to the nearest directory that contains a project_root_markers entry, .git by default. It then checks every directory from the root down to the working directory, inclusive. In each directory, candidate_filenames tries AGENTS.override.md, then AGENTS.md, then each project_doc_fallback_filenames entry, and keeps only the first file it finds. Fallback names that are ., .., or contain a path separator are ignored with a warning.

A global file comes from the Codex home directory. CodexHomeUserInstructionsProvider prefers AGENTS.override.md over AGENTS.md there, takes the first non-empty file, and keeps the last good value if a later read fails.

The byte budget

Project files share one byte budget across all files and environments:

where is the size of the -th file in root-to-cwd order, is the number of bytes loaded from it, is the budget left before it, and is project_doc_max_bytes, which defaults to bytes (DEFAULT_PROJECT_DOC_MAX_BYTES). A file larger than is cut to bytes with a warning such as “Loaded only … bytes”; once reaches 0, later files are skipped with a warning. A file that is empty or only whitespace is dropped and leaves unchanged. The global file does not count against .

Wrapping and the rendered message

LoadedAgentsMd::text joins the global instructions, any thread instructions, and the project files with blank lines. It inserts --- project-doc --- at the first transition to project files, so the model can tell personal rules from repository rules. UserInstructions then wraps the text in a user message. With a global file that says to use British spelling and one repository file, the model sees the following; this example is constructed from the code, not taken from a test:

# AGENTS.md instructions for /repo

<INSTRUCTIONS>
Use British spelling in prose.

--- project-doc ---

Run `just test` before you commit.
</INSTRUCTIONS>

The directory is the working directory of the single project environment. When files come from two or more environments, the header drops the directory and the body labels each group with “for id with root …”.

When AGENTS.md changes

AgentsMdState stores the directory and text as its snapshot. If either changes, it re-emits the whole text with the prefix “These AGENTS.md instructions replace all previously provided AGENTS.md instructions.” If the files disappear, it emits “The previously provided AGENTS.md instructions no longer apply.” A snapshot test that changes the working directory to a folder with a different AGENTS.md shows the second request appending one user message with the new AGENTS.md and environment context.

Environment context

EnvironmentsState renders a <environment_context> user message. With one environment it holds <cwd> and <shell>; with several, an <environments> list with one <environment> element each. It adds <current_date>, <timezone>, <network>, and <filesystem> when they are known. The config keys include_environment_context and include_environment_context_time both default to true; setting the first to false removes the block.

Skills, plugins, and apps in brief

The skills extension contributes the host_skills section, which lists available skills inside <skills_instructions>. It appends usage guidance only when the model sets include_skills_usage_instructions. The apps and plugins sections render only when those features are available and the model sets include_apps_usage_instructions or include_plugin_usage_instructions. Chapter 18 covers what these sections contain and how skills load.

Normalizing history before sending

ContextManager in codex-rs/core/src/context_manager/history.rs keeps history as Arc<Vec<ResponseItemEnvelope>>, oldest first. Its comment explains the Arc: snapshots “share the vector until a caller needs to mutate it, avoiding deep copies.” Before a request, the turn loop clones history and calls for_prompt, which normalizes the clone and leaves stored history as it was.

normalize_history enforces three invariants from its doc comment. Every function or custom tool call gets an output; ensure_call_outputs_present inserts a synthetic output with the text aborted for a call that never finished, for example after an interrupt. Every paired output must have a call, so remove_orphan_outputs drops strays. Images and audio are stripped when the model’s input_modalities do not include them. for_prompt then replaces media files that can no longer be resolved with text placeholders and projects any rejected audio files.

This pass is a guard at the boundary. History stays a faithful record, including half-finished calls, while every request the model sees is well formed.

How settings changes reach the model

Codex communicates every mid-thread change as appended context. The table lists the main cases.

Change What gets appended Section or mechanism
Working directory New <environment_context> EnvironmentsState
Approval or sandbox policy New <permissions instructions> PermissionsState
AGENTS.md text Full text with replacement notice AgentsMdState
Model <model_switch> developer message ModelInstructionsState
Reasoning effort ConfigurationUpdate item record_reasoning_effort_override

The turn-override snapshot shows the first case and the second together. Request 2 resends items 00 to 03 unchanged, then appends:

04:message/assistant:
    turn one complete
05:message/developer:
    <PERMISSIONS_INSTRUCTIONS>
06:message/user:
    <ENVIRONMENT_CONTEXT>
07:message/user:
    second turn with context updates

A model change produces a <model_switch> block that says “The user was previously using a different model” and carries the new model’s instructions. In a new window, assemble_initial_context puts it first in the developer bundle. A switch can also force compaction with the previous model first (Chapter 8).

Reasoning effort has the most careful path. When reasoning_effort_override is on, the provider is OpenAI, and the model sets supports_reasoning_effort_updates, the request’s reasoning.effort stays pinned per model for the window. A new effort travels as a harness-authored ConfigurationUpdate item in history, and the request builder keeps only the latest of several adjacent ones. The module comment calls these “cache-preserving effort updates”, and a successful compaction retires the pin.

Status at commit 081295be9d. World-state diffs and initial-context assembly: IMPLEMENTED. incremental_tools: STABLE, on by default. reasoning_effort_override: STABLE, on by default. AGENTS.md discovery with a 32,768-byte default budget: IMPLEMENTED. include_environment_context, include_environment_context_time, and include_permissions_instructions: config keys, default true. per_environment_context: UNDER DEVELOPMENT, off. Read in code and snapshot tests, not run.

What breaks

Symptom Cause Check
AGENTS.md ignored Untrusted project, budget 0, or no root marker above cwd Trust level; project_doc_max_bytes; project_root_markers
A nested AGENTS.md ignored AGENTS.override.md in the same directory wins List both files in that directory
Warning “Loaded only … bytes” 32 KiB project budget used up Trim files or raise project_doc_max_bytes
Model acts on an old directory Stale environment message plus a missed diff Latest <environment_context> in the rollout
Unexpected aborted tool output Call interrupted before its output ensure_call_outputs_present
Cache hit rate drops after a change A request edited the prefix Prefix assertion in prompt_caching.rs tests

Code map

What it is Source Identifier
Initial context assembly codex:codex-rs/core/src/session/mod.rs assemble_initial_context
Section registration order codex:codex-rs/core/src/session/world_state.rs build_world_state_for_step
Section contract and renderers codex:codex-rs/core/src/context/world_state/mod.rs render_history_diff
Update merging codex:codex-rs/core/src/context_manager/updates.rs merge_world_state_updates
AGENTS.md discovery codex:codex-rs/core/src/agents_md.rs candidate_filenames
AGENTS.md change notices codex:codex-rs/core/src/context/world_state/agents_md.rs REPLACEMENT_NOTICE
History normalization codex:codex-rs/core/src/context_manager/history.rs normalize_history
Effort updates codex:codex-rs/core/src/session/reasoning_effort.rs record_reasoning_effort_override

Recall check

What does a section return when nothing changed since its snapshot?
No updates, so nothing is appended and the cached prefix stays intact.

In what order does Codex search for instruction files in one directory?
AGENTS.override.md, then AGENTS.md, then the configured fallbacks; only the first one found counts.

What separates global instructions from project instructions?
The line --- project-doc --- at the first transition to project files.

Why does a call with no output still have an output in the request?
ensure_call_outputs_present adds a synthetic aborted output to the normalized copy.

How does a reasoning-effort change avoid breaking the cache?
The request effort stays pinned, and the change travels as a ConfigurationUpdate item appended to history.