core: make AGENTS.md react to environment changes (#29810)

## Why

With deferred executors, a turn can begin before a remote environment
attaches. AGENTS.md discovery previously ran only during session setup,
so instructions from a later environment never reached the model or the
session instruction sources.

WorldState persistence has now landed, so this uses the durable
model-visible baseline directly instead of carrying a temporary
resume/fork compatibility path.

## What

- Add an `AgentsMdManager` in `SessionServices` to own host
instructions, loaded state, and refresh caching.
- When `DeferredExecutor` is enabled, refresh AGENTS.md when attached
environment selections change and freeze the result in the corresponding
`StepContext`.
- Represent AGENTS.md as a persisted WorldState section for every
session, with bounded initial, replacement, and removal updates.
- Remove duplicate AGENTS.md state and rendering from
`SessionConfiguration` and `TurnContext`.
- Build initial context, per-request updates, and compaction context
from the same step-scoped value.
- On resume and fork, compare current instructions with the restored
WorldState baseline and inject a replacement exactly once when they
differ.

Builds on #29833, #29835, and #29837.

## Tests

- Covers a remote environment becoming ready mid-turn, with AGENTS.md
appearing on the next request exactly once and updating canonical
instruction sources.
- Covers full, unchanged, replaced, and removed AGENTS.md WorldState
rendering.
- Covers changed instructions across cold resume and fork without
duplicate reinjection.
- Covers remote-v2 compaction retaining creation-time instructions in
the live session and cold resume appending one replacement when the
source changed.
- Ran focused `codex-core` AGENTS.md, WorldState, and context-update
test suites.
This commit is contained in:
sayan-oai
2026-06-24 22:57:42 -07:00
committed by GitHub
parent 51864b0b4b
commit f2f80ef442
30 changed files with 639 additions and 219 deletions
@@ -0,0 +1,75 @@
use super::WorldStateSection;
use crate::agents_md::LoadedAgentsMd;
use crate::context::ContextualUserFragment;
use crate::context::UserInstructions;
use serde::Deserialize;
use serde::Serialize;
const REPLACEMENT_NOTICE: &str =
"These AGENTS.md instructions replace all previously provided AGENTS.md instructions.";
const REMOVAL_NOTICE: &str = "The previously provided AGENTS.md instructions no longer apply.";
/// The AGENTS.md instructions currently visible to the model.
#[derive(Clone, Debug, Default)]
pub(crate) struct AgentsMdState {
instructions: Option<UserInstructions>,
}
/// Persisted model-visible AGENTS.md state, without filesystem provenance.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub(crate) struct AgentsMdSnapshot {
directory: Option<String>,
text: Option<String>,
}
impl AgentsMdState {
pub(crate) fn new(loaded: Option<&LoadedAgentsMd>) -> Self {
Self {
instructions: loaded.map(LoadedAgentsMd::contextual_user_fragment),
}
}
}
impl WorldStateSection for AgentsMdState {
const ID: &'static str = "agents_md";
type Snapshot = AgentsMdSnapshot;
fn snapshot(&self) -> Self::Snapshot {
match &self.instructions {
Some(instructions) => AgentsMdSnapshot {
directory: instructions.directory.clone(),
text: Some(instructions.text.clone()),
},
None => AgentsMdSnapshot::default(),
}
}
fn render_diff(
&self,
previous: Option<&Self::Snapshot>,
) -> Option<Box<dyn ContextualUserFragment>> {
let current = self.snapshot();
if previous == Some(&current) {
return None;
}
let previous_instructions = previous.and_then(|state| state.text.as_ref());
let instructions = match (&self.instructions, previous_instructions) {
(Some(instructions), Some(_)) => UserInstructions {
directory: instructions.directory.clone(),
text: format!("{REPLACEMENT_NOTICE}\n\n{}", instructions.text),
},
(Some(instructions), None) => instructions.clone(),
(None, Some(_)) => UserInstructions {
directory: None,
text: REMOVAL_NOTICE.to_string(),
},
(None, None) => return None,
};
Some(Box::new(instructions))
}
}
#[cfg(test)]
#[path = "agents_md_tests.rs"]
mod tests;
@@ -0,0 +1,73 @@
use super::*;
use crate::context::world_state::WorldState;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn renders_full_state_and_omits_unchanged_state() {
let loaded = LoadedAgentsMd::from_text_for_testing("use the project formatter");
let mut state = WorldState::default();
state.add_section(AgentsMdState::new(Some(&loaded)));
assert_eq!(
vec![user_message(
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nuse the project formatter\n</INSTRUCTIONS>",
)],
render_fragments(state.render_full()),
);
assert_eq!(
Vec::<ResponseItem>::new(),
render_fragments(state.render_diff(&state.snapshot()))
);
assert_eq!(
state.snapshot().into_value(),
json!({"agents_md": {"text": "use the project formatter"}}),
);
}
#[test]
fn changed_and_removed_state_supersedes_previous_instructions() {
let previous_loaded = LoadedAgentsMd::from_text_for_testing("old instructions");
let mut previous = WorldState::default();
previous.add_section(AgentsMdState::new(Some(&previous_loaded)));
let current_loaded = LoadedAgentsMd::from_text_for_testing("new instructions");
let mut current = WorldState::default();
current.add_section(AgentsMdState::new(Some(&current_loaded)));
assert_eq!(
vec![user_message(
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nThese AGENTS.md instructions replace all previously provided AGENTS.md instructions.\n\nnew instructions\n</INSTRUCTIONS>",
)],
render_fragments(current.render_diff(&previous.snapshot())),
);
let mut removed = WorldState::default();
removed.add_section(AgentsMdState::default());
assert_eq!(
vec![user_message(
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nThe previously provided AGENTS.md instructions no longer apply.\n</INSTRUCTIONS>",
)],
render_fragments(removed.render_diff(&current.snapshot())),
);
}
fn render_fragments(fragments: Vec<Box<dyn ContextualUserFragment>>) -> Vec<ResponseItem> {
fragments
.into_iter()
.map(ContextualUserFragment::into_boxed_response_item)
.collect()
}
fn user_message(text: &str) -> ResponseItem {
ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: text.to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
}
@@ -1,3 +1,4 @@
mod agents_md;
mod environment;
use crate::context::ContextualUserFragment;
@@ -9,6 +10,7 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::fmt;
pub(crate) use agents_md::AgentsMdState;
pub(crate) use environment::EnvironmentsState;
trait ErasedWorldStateSection: Send + Sync {