Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Return world-state snapshots and context updates together (#49894)

pakrym-oai08a7031b6acb
diff --git a/codex-rs/core/src/context/token_budget_context.rs b/codex-rs/core/src/context/token_budget_context.rs
index 0d7bf383f5..90b0a4a9a2 100644
--- a/codex-rs/core/src/context/token_budget_context.rs
+++ b/codex-rs/core/src/context/token_budget_context.rs
@@ -1,6 +1,7 @@
use super::ContextualUserFragment;
use super::world_state::PreviousSectionState;
use super::world_state::WorldStateSection;
+use crate::context::world_state::SectionTransition;
use codex_protocol::AgentPath;
use codex_protocol::models::ContentItemKind;
use codex_protocol::protocol::CONTEXT_WINDOW_CLOSE_TAG;
@@ -79,16 +80,14 @@ impl WorldStateSection for TokenBudgetContext {
const ID: &'static str = "context_window";
type Snapshot = AgentPath;
- fn snapshot(&self) -> Self::Snapshot {
- self.agent_path.clone()
- }
-
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- matches!(previous, PreviousSectionState::Known(agent_path) if agent_path != &self.agent_path)
- .then(|| Box::new(self.clone()) as Box<dyn ContextualUserFragment>)
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.agent_path.clone();
+ let fragment = matches!(previous, PreviousSectionState::Known(agent_path) if agent_path != &self.agent_path)
+ .then(|| Box::new(self.clone()) as Box<dyn ContextualUserFragment>);
+ (Some(current), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/agents_md.rs b/codex-rs/core/src/context/world_state/agents_md.rs
index 1b9a168010..756a020b36 100644
--- a/codex-rs/core/src/context/world_state/agents_md.rs
+++ b/codex-rs/core/src/context/world_state/agents_md.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::agents_md::LoadedAgentsMd;
use crate::context::ContextualUserFragment;
@@ -35,16 +36,6 @@ 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 matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "user" && UserInstructions::matches_text(text)
}
@@ -52,10 +43,16 @@ impl WorldStateSection for AgentsMdState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- let current = self.snapshot();
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = match &self.instructions {
+ Some(instructions) => AgentsMdSnapshot {
+ directory: instructions.directory.clone(),
+ text: Some(instructions.text.clone()),
+ },
+ None => AgentsMdSnapshot::default(),
+ };
if matches!(previous, PreviousSectionState::Known(previous) if previous == &current) {
- return None;
+ return (None, None);
}
let previous_may_contain_instructions = match previous {
@@ -73,9 +70,9 @@ impl WorldStateSection for AgentsMdState {
directory: None,
text: REMOVAL_NOTICE.to_string(),
},
- (None, false) => return None,
+ (None, false) => return (Some(current), None),
};
- Some(Box::new(instructions))
+ (Some(current), Some(Box::new(instructions)))
}
}
diff --git a/codex-rs/core/src/context/world_state/apps_instructions.rs b/codex-rs/core/src/context/world_state/apps_instructions.rs
index 767e1c584e..e419b264aa 100644
--- a/codex-rs/core/src/context/world_state/apps_instructions.rs
+++ b/codex-rs/core/src/context/world_state/apps_instructions.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::AppsInstructions;
use crate::context::ContextualUserFragment;
@@ -19,10 +20,6 @@ impl WorldStateSection for AppsInstructionsState {
const ID: &'static str = "apps_instructions";
type Snapshot = bool;
- fn snapshot(&self) -> Self::Snapshot {
- self.available
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && AppsInstructions::matches_text(text)
}
@@ -38,15 +35,16 @@ impl WorldStateSection for AppsInstructionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.available;
if !self.available
|| matches!(previous, PreviousSectionState::Known(previous) if *previous)
|| matches!(previous, PreviousSectionState::Unknown)
{
- return None;
+ return (Some(current), None);
}
- Some(Box::new(AppsInstructions))
+ (Some(current), Some(Box::new(AppsInstructions)))
}
}
diff --git a/codex-rs/core/src/context/world_state/collaboration_mode.rs b/codex-rs/core/src/context/world_state/collaboration_mode.rs
index e9d7fd192b..c1fda2ebc6 100644
--- a/codex-rs/core/src/context/world_state/collaboration_mode.rs
+++ b/codex-rs/core/src/context/world_state/collaboration_mode.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
@@ -94,10 +95,6 @@ impl WorldStateSection for CollaborationModeState {
const ID: &'static str = "collaboration_mode";
type Snapshot = CollaborationModeSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- self.snapshot.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && CollaborationModeInstructions::matches_text(text)
}
@@ -113,7 +110,8 @@ impl WorldStateSection for CollaborationModeState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.snapshot.clone();
let unchanged = match previous {
PreviousSectionState::Absent => self.instructions.is_none(),
PreviousSectionState::Unknown => false,
@@ -136,12 +134,15 @@ impl WorldStateSection for CollaborationModeState {
}
};
if unchanged {
- return None;
+ return (Some(current), None);
}
- Some(Box::new(CollaborationModeInstructions {
- instructions: self.instructions.clone().unwrap_or_default(),
- }))
+ (
+ Some(current),
+ Some(Box::new(CollaborationModeInstructions {
+ instructions: self.instructions.clone().unwrap_or_default(),
+ })),
+ )
}
}
diff --git a/codex-rs/core/src/context/world_state/collaboration_mode_tests.rs b/codex-rs/core/src/context/world_state/collaboration_mode_tests.rs
index 21d3883b0e..f8e04a36e2 100644
--- a/codex-rs/core/src/context/world_state/collaboration_mode_tests.rs
+++ b/codex-rs/core/src/context/world_state/collaboration_mode_tests.rs
@@ -125,6 +125,7 @@ fn empty_catalog_collaboration_message_suppresses_legacy_instructions() {
assert_eq!(
state
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("explicit empty collaboration message")
.render(),
format!("{COLLABORATION_MODE_OPEN_TAG}{COLLABORATION_MODE_CLOSE_TAG}")
@@ -172,6 +173,7 @@ fn legacy_collaboration_mode_snapshots_refresh_catalog_messages_once() {
assert_eq!(
state
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("legacy snapshot should refresh collaboration instructions")
.render(),
format!(
@@ -180,7 +182,10 @@ fn legacy_collaboration_mode_snapshots_refresh_catalog_messages_once() {
);
assert!(
state
- .render_diff(PreviousSectionState::Known(&state.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &state.render_diff(PreviousSectionState::Absent).0.unwrap()
+ ))
+ .1
.is_none()
);
}
diff --git a/codex-rs/core/src/context/world_state/compact_permissions.rs b/codex-rs/core/src/context/world_state/compact_permissions.rs
index f6822ef7bc..6a6868f43b 100644
--- a/codex-rs/core/src/context/world_state/compact_permissions.rs
+++ b/codex-rs/core/src/context/world_state/compact_permissions.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::APPROVED_COMMAND_PREFIX_SAVED_MESSAGE_PREFIX;
use crate::context::ApprovedCommandPrefixSaved;
@@ -25,10 +26,6 @@ impl WorldStateSection for CompactPermissionsState {
const ID: &'static str = "approved_command_prefixes";
type Snapshot = BTreeSet<Vec<String>>;
- fn snapshot(&self) -> Self::Snapshot {
- self.prefixes.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer"
&& text
@@ -39,18 +36,23 @@ impl WorldStateSection for CompactPermissionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.prefixes.clone();
let added_prefixes = match previous {
PreviousSectionState::Known(previous) => self
.prefixes
.difference(previous)
.cloned()
.collect::<Vec<_>>(),
- PreviousSectionState::Absent | PreviousSectionState::Unknown => return None,
+ PreviousSectionState::Absent | PreviousSectionState::Unknown => {
+ return (Some(current), None);
+ }
};
- format_allow_prefixes(added_prefixes)
- .filter(|prefixes| !prefixes.is_empty())
- .map(|prefixes| Box::new(ApprovedCommandPrefixSaved::new(prefixes)) as _)
+ let fragment: Option<Box<dyn ContextualUserFragment>> =
+ format_allow_prefixes(added_prefixes)
+ .filter(|prefixes| !prefixes.is_empty())
+ .map(|prefixes| Box::new(ApprovedCommandPrefixSaved::new(prefixes)) as _);
+ (Some(current), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/compact_permissions_tests.rs b/codex-rs/core/src/context/world_state/compact_permissions_tests.rs
index 8f777cb1b1..f69426ee6d 100644
--- a/codex-rs/core/src/context/world_state/compact_permissions_tests.rs
+++ b/codex-rs/core/src/context/world_state/compact_permissions_tests.rs
@@ -15,18 +15,26 @@ fn renders_only_newly_approved_prefixes() {
.add_prefix_rule(&["cargo".to_string(), "test".to_string()], Decision::Allow)
.expect("test prefix should be valid");
let with_new_prefix = CompactPermissionsState::new(&exec_policy);
- let existing_snapshot = with_existing_prefix.snapshot();
- let current_snapshot = with_new_prefix.snapshot();
+ let existing_snapshot = with_existing_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
+ let current_snapshot = with_new_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
assert_eq!(
with_new_prefix
.render_diff(Known(&existing_snapshot))
+ .1
.map(|fragment| fragment.render()),
Some("Approved command prefix saved:\n- [\"cargo\", \"test\"]".to_string())
);
assert!(
with_new_prefix
.render_diff(Known(&current_snapshot))
+ .1
.is_none()
);
}
@@ -42,7 +50,10 @@ fn does_not_duplicate_a_retained_legacy_update() {
let state = CompactPermissionsState::new(&exec_policy);
assert_eq!(
- state.render_diff(Unknown).map(|fragment| fragment.render()),
+ state
+ .render_diff(Unknown)
+ .1
+ .map(|fragment| fragment.render()),
None
);
}
@@ -59,6 +70,7 @@ fn does_not_render_existing_prefixes_without_a_previous_snapshot() {
assert!(
CompactPermissionsState::new(&exec_policy)
.render_diff(Absent)
+ .1
.is_none()
);
}
diff --git a/codex-rs/core/src/context/world_state/context_window_guidance.rs b/codex-rs/core/src/context/world_state/context_window_guidance.rs
index 05a289fdd4..e1b7dd81be 100644
--- a/codex-rs/core/src/context/world_state/context_window_guidance.rs
+++ b/codex-rs/core/src/context/world_state/context_window_guidance.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::ContextWindowGuidance;
use crate::context::ContextualUserFragment;
@@ -29,10 +30,6 @@ impl WorldStateSection for ContextWindowGuidanceState {
const ID: &'static str = "context_window_guidance";
type Snapshot = String;
- fn snapshot(&self) -> Self::Snapshot {
- self.message.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && ContextWindowGuidance::matches_text(text)
}
@@ -48,9 +45,9 @@ impl WorldStateSection for ContextWindowGuidanceState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
if matches!(previous, PreviousSectionState::Known(previous) if previous == &self.message) {
- return None;
+ return (None, None);
}
let previous_may_contain_guidance = match previous {
PreviousSectionState::Known(previous) => !previous.is_empty(),
@@ -59,7 +56,7 @@ impl WorldStateSection for ContextWindowGuidanceState {
};
let message = if self.message.is_empty() {
if !previous_may_contain_guidance {
- return None;
+ return (Some(self.message.clone()), None);
}
REMOVAL_NOTICE.to_string()
} else if previous_may_contain_guidance {
@@ -67,7 +64,10 @@ impl WorldStateSection for ContextWindowGuidanceState {
} else {
self.message.clone()
};
- Some(Box::new(ContextWindowGuidance::new(&message)))
+ (
+ Some(self.message.clone()),
+ Some(Box::new(ContextWindowGuidance::new(&message))),
+ )
}
}
diff --git a/codex-rs/core/src/context/world_state/environment.rs b/codex-rs/core/src/context/world_state/environment.rs
index c1656865cb..4880009b58 100644
--- a/codex-rs/core/src/context/world_state/environment.rs
+++ b/codex-rs/core/src/context/world_state/environment.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use crate::context::environment_context::FileSystemContext;
@@ -105,8 +106,11 @@ impl WorldStateSection for EnvironmentsState {
const ID: &'static str = "environments";
type Snapshot = EnvironmentsSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- EnvironmentsSnapshot {
+ fn render_diff(
+ &self,
+ previous: PreviousSectionState<'_, Self::Snapshot>,
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = EnvironmentsSnapshot {
environments: self
.environments
.iter()
@@ -129,14 +133,7 @@ impl WorldStateSection for EnvironmentsState {
network: self.network.as_ref().map(NetworkContext::render),
filesystem: self.filesystem.as_ref().map(FileSystemContext::render),
subagents: self.subagents.clone(),
- }
- }
-
- fn render_diff(
- &self,
- previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- let current = self.snapshot();
+ };
let empty = EnvironmentsSnapshot::default();
let previous = match previous {
PreviousSectionState::Known(previous) => previous,
@@ -175,7 +172,7 @@ impl WorldStateSection for EnvironmentsState {
&& updates
.values()
.all(|update| matches!(update, EnvironmentUpdate::Current(_)));
- (!updates.is_empty() || turn_context_values_changed).then(|| {
+ let fragment = (!updates.is_empty() || turn_context_values_changed).then(|| {
Box::new(RenderedEnvironments {
updates,
legacy_single,
@@ -191,7 +188,8 @@ impl WorldStateSection for EnvironmentsState {
filesystem: self.filesystem.clone(),
subagents: self.subagents.clone(),
}) as Box<dyn ContextualUserFragment>
- })
+ });
+ (Some(current), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/environment_render_tests.rs b/codex-rs/core/src/context/world_state/environment_render_tests.rs
index 1f24d55476..2ea557d9d9 100644
--- a/codex-rs/core/src/context/world_state/environment_render_tests.rs
+++ b/codex-rs/core/src/context/world_state/environment_render_tests.rs
@@ -368,11 +368,12 @@ fn powershell_environment() -> EnvironmentsState {
#[test]
fn shell_version_diff_restates_shell_from_legacy_snapshot() {
let current = powershell_environment();
- let mut previous = current.snapshot();
+ let mut previous = current.render_diff(PreviousSectionState::Absent).0.unwrap();
previous.shell_version = None;
previous.environments.get_mut("local").expect("local").shell = None;
let rendered = current
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("shell version update")
.render();
assert!(
@@ -390,7 +391,13 @@ fn shell_version_diff_clears_previously_visible_version() {
};
assert_eq!(
current
- .render_diff(PreviousSectionState::Known(&previous.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &previous
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ ))
+ .1
.expect("removed shell version")
.render(),
"<environment_context>\n <shell_version status=\"unavailable\" />\n</environment_context>"
@@ -406,19 +413,37 @@ fn current_date_diff_clears_once_and_recovers() {
let unavailable = EnvironmentsState::default();
assert_eq!(
unavailable
- .render_diff(PreviousSectionState::Known(&available.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &available
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ ))
+ .1
.expect("removed current date")
.render(),
"<environment_context>\n <current_date status=\"unavailable\" />\n</environment_context>"
);
assert!(
unavailable
- .render_diff(PreviousSectionState::Known(&unavailable.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &unavailable
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ ))
+ .1
.is_none()
);
assert_eq!(
available
- .render_diff(PreviousSectionState::Known(&unavailable.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &unavailable
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ ))
+ .1
.expect("restored current date")
.render(),
"<environment_context>\n <current_date>2026-06-17</current_date>\n</environment_context>"
diff --git a/codex-rs/core/src/context/world_state/environment_tests.rs b/codex-rs/core/src/context/world_state/environment_tests.rs
index c0461b2c5c..10faf80440 100644
--- a/codex-rs/core/src/context/world_state/environment_tests.rs
+++ b/codex-rs/core/src/context/world_state/environment_tests.rs
@@ -173,9 +173,10 @@ fn changing_primary_environment_updates_model_context_and_persisted_state() -> R
.collect(),
..Default::default()
};
- let previous = before.snapshot();
+ let previous = before.render_diff(PreviousSectionState::Absent).0.unwrap();
let rendered = after
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("primary change should update the model")
.render();
@@ -232,10 +233,16 @@ fn legacy_single_environment_snapshot_does_not_change() -> Result<()> {
assert!(
environment
.render_diff(PreviousSectionState::Known(&legacy_snapshot))
+ .1
.is_none()
);
assert_eq!(
- serde_json::to_value(environment.snapshot())?["environments"]["local"],
+ serde_json::to_value(
+ environment
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ )?["environments"]["local"],
json!({
"cwd": PathUri::parse("file:///repo")?.inferred_native_path_string(),
"status": "available",
@@ -281,7 +288,10 @@ fn crossing_single_environment_boundary_restates_current_environments() -> Resul
};
let expanded = multiple
- .render_diff(PreviousSectionState::Known(&single.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &single.render_diff(PreviousSectionState::Absent).0.unwrap(),
+ ))
+ .1
.expect("adding an environment should update the model")
.render();
assert_eq!(
@@ -292,7 +302,13 @@ fn crossing_single_environment_boundary_restates_current_environments() -> Resul
);
let reduced = single
- .render_diff(PreviousSectionState::Known(&multiple.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &multiple
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap(),
+ ))
+ .1
.expect("removing an environment should update the model")
.render();
assert_eq!(
@@ -362,7 +378,10 @@ fn failure_context_is_escaped_incremental_and_cleared_on_recovery() -> Result<()
"#);
assert!(
failed
- .render_diff(PreviousSectionState::Known(&failed.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &failed.render_diff(PreviousSectionState::Absent).0.unwrap()
+ ))
+ .1
.is_none()
);
let recovered = EnvironmentsState {
@@ -375,7 +394,10 @@ fn failure_context_is_escaped_incremental_and_cleared_on_recovery() -> Result<()
..Default::default()
};
let update = recovered
- .render_diff(PreviousSectionState::Known(&failed.snapshot()))
+ .render_diff(PreviousSectionState::Known(
+ &failed.render_diff(PreviousSectionState::Absent).0.unwrap(),
+ ))
+ .1
.expect("recovery must be visible to the model");
assert!(!update.body().contains("<error>"));
assert!(update.body().contains("<shell>bash</shell>"));
diff --git a/codex-rs/core/src/context/world_state/environments_instructions.rs b/codex-rs/core/src/context/world_state/environments_instructions.rs
index 47576ed53c..cfa853d4a2 100644
--- a/codex-rs/core/src/context/world_state/environments_instructions.rs
+++ b/codex-rs/core/src/context/world_state/environments_instructions.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use crate::context::EnvironmentsInstructions;
@@ -19,10 +20,6 @@ impl WorldStateSection for EnvironmentsInstructionsState {
const ID: &'static str = "environments_instructions";
type Snapshot = bool;
- fn snapshot(&self) -> Self::Snapshot {
- self.enabled
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && EnvironmentsInstructions::matches_text(text)
}
@@ -38,15 +35,16 @@ impl WorldStateSection for EnvironmentsInstructionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.enabled;
if !self.enabled
|| matches!(previous, PreviousSectionState::Known(previous) if *previous)
|| matches!(previous, PreviousSectionState::Unknown)
{
- return None;
+ return (Some(current), None);
}
- Some(Box::new(EnvironmentsInstructions))
+ (Some(current), Some(Box::new(EnvironmentsInstructions)))
}
}
diff --git a/codex-rs/core/src/context/world_state/managed_developer_instructions.rs b/codex-rs/core/src/context/world_state/managed_developer_instructions.rs
index 665596290e..4086bc33c3 100644
--- a/codex-rs/core/src/context/world_state/managed_developer_instructions.rs
+++ b/codex-rs/core/src/context/world_state/managed_developer_instructions.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
@@ -104,15 +105,6 @@ impl WorldStateSection for ManagedDeveloperInstructionsState {
const ID: &'static str = "managed_developer_instructions";
type Snapshot = ManagedDeveloperInstructionsSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- ManagedDeveloperInstructionsSnapshot {
- instructions: self
- .instructions
- .as_ref()
- .map(WorldStateHash::from_fragment),
- }
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && ManagedDeveloperInstructions::matches_text(text)
}
@@ -128,10 +120,15 @@ impl WorldStateSection for ManagedDeveloperInstructionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- if matches!(previous, PreviousSectionState::Known(previous) if previous == &self.snapshot())
- {
- return None;
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = ManagedDeveloperInstructionsSnapshot {
+ instructions: self
+ .instructions
+ .as_ref()
+ .map(WorldStateHash::from_fragment),
+ };
+ if matches!(previous, PreviousSectionState::Known(previous) if previous == &current) {
+ return (None, None);
}
let previous_had_instructions = match previous {
PreviousSectionState::Absent => false,
@@ -146,9 +143,9 @@ impl WorldStateSection for ManagedDeveloperInstructionsState {
(None, true) => ManagedDeveloperInstructions {
instructions: REMOVAL_NOTICE.to_string(),
},
- (None, false) => return None,
+ (None, false) => return (Some(current), None),
};
- Some(Box::new(fragment))
+ (Some(current), Some(Box::new(fragment)))
}
}
diff --git a/codex-rs/core/src/context/world_state/mod.rs b/codex-rs/core/src/context/world_state/mod.rs
index 1171debf43..f9cf044f51 100644
--- a/codex-rs/core/src/context/world_state/mod.rs
+++ b/codex-rs/core/src/context/world_state/mod.rs
@@ -56,7 +56,7 @@ pub(crate) use plugins_instructions::PluginsInstructionsState;
pub(crate) use realtime::RealtimeState;
pub(crate) use tools::ToolsState;
-type SectionTransition = (Option<Value>, Option<Box<dyn ContextualUserFragment>>);
+pub(crate) type SectionTransition<S = Value> = (Option<S>, Option<Box<dyn ContextualUserFragment>>);
trait ErasedWorldStateSection: Send + Sync {
fn matches_legacy_fragment(&self, role: &str, text: &str) -> bool;
@@ -130,10 +130,10 @@ impl<S: WorldStateSection> ErasedWorldStateSection for S {
PreviousSectionState::Absent => PreviousSectionState::Absent,
PreviousSectionState::Unknown => PreviousSectionState::Unknown,
};
- let snapshot = section_snapshot(self, self.snapshot()).unwrap_or(Value::Null);
+ let (snapshot, fragment) = WorldStateSection::render_diff(self, previous);
(
- Some(snapshot),
- WorldStateSection::render_diff(self, previous),
+ snapshot.map(|snapshot| section_snapshot(self, snapshot).unwrap_or(Value::Null)),
+ fragment,
)
}
}
@@ -224,8 +224,6 @@ pub(crate) trait WorldStateSection: Send + Sync + 'static {
const ID: &'static str;
type Snapshot: DeserializeOwned + Serialize;
- fn snapshot(&self) -> Self::Snapshot;
-
/// Whether the section contributes comparison state to persisted rollouts.
fn should_persist(&self) -> bool {
true
@@ -250,10 +248,12 @@ pub(crate) trait WorldStateSection: Send + Sync + 'static {
false
}
+ /// Returns independently optional updates to the snapshot and model context.
+ /// A missing snapshot leaves the stored comparison state unchanged.
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>>;
+ ) -> SectionTransition<Self::Snapshot>;
}
/// Stable fingerprint of a model-visible World State fragment.
diff --git a/codex-rs/core/src/context/world_state/model.rs b/codex-rs/core/src/context/world_state/model.rs
index c353034160..bfa20fba54 100644
--- a/codex-rs/core/src/context/world_state/model.rs
+++ b/codex-rs/core/src/context/world_state/model.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use crate::context::ModelSwitchInstructions;
@@ -25,10 +26,6 @@ impl WorldStateSection for ModelInstructionsState {
const ID: &'static str = "model";
type Snapshot = String;
- fn snapshot(&self) -> Self::Snapshot {
- self.model.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && ModelSwitchInstructions::matches_text(text)
}
@@ -44,7 +41,8 @@ impl WorldStateSection for ModelInstructionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.model.clone();
let model_changed = match previous {
PreviousSectionState::Known(previous) => previous != &self.model,
PreviousSectionState::Unknown | PreviousSectionState::Absent => self
@@ -53,10 +51,12 @@ impl WorldStateSection for ModelInstructionsState {
.is_some_and(|previous| previous != self.model),
};
- (model_changed && !self.instructions.is_empty()).then(|| {
- Box::new(ModelSwitchInstructions::new(self.instructions.clone()))
- as Box<dyn ContextualUserFragment>
- })
+ let fragment: Option<Box<dyn ContextualUserFragment>> =
+ (model_changed && !self.instructions.is_empty()).then(|| {
+ Box::new(ModelSwitchInstructions::new(self.instructions.clone()))
+ as Box<dyn ContextualUserFragment>
+ });
+ (Some(current), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/model_catalog.rs b/codex-rs/core/src/context/world_state/model_catalog.rs
index db685166a5..acaa5520a6 100644
--- a/codex-rs/core/src/context/world_state/model_catalog.rs
+++ b/codex-rs/core/src/context/world_state/model_catalog.rs
@@ -3,6 +3,7 @@
//! never rewrite earlier messages, and missing retained context gets a fresh catalog.
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::agent::child_config::MAX_SPAWN_AGENT_MODEL_OVERRIDES;
@@ -114,10 +115,6 @@ impl WorldStateSection for ModelCatalogState {
const ID: &'static str = "model_catalog";
type Snapshot = WorldStateHash;
- fn snapshot(&self) -> Self::Snapshot {
- WorldStateHash::from_fragment(self)
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && Self::matches_text(text)
}
@@ -133,12 +130,13 @@ impl WorldStateSection for ModelCatalogState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- if matches!(previous, PreviousSectionState::Known(previous) if previous == &self.snapshot())
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = WorldStateHash::from_fragment(self);
+ if matches!(previous, PreviousSectionState::Known(previous) if previous == &current)
|| self.catalog.is_empty() && matches!(previous, PreviousSectionState::Absent)
{
- return None;
+ return (Some(current), None);
}
- Some(Box::new(self.clone()))
+ (Some(current), Some(Box::new(self.clone())))
}
}
diff --git a/codex-rs/core/src/context/world_state/model_tests.rs b/codex-rs/core/src/context/world_state/model_tests.rs
index 806718cc4f..12e5caaffc 100644
--- a/codex-rs/core/src/context/world_state/model_tests.rs
+++ b/codex-rs/core/src/context/world_state/model_tests.rs
@@ -14,6 +14,7 @@ fn model_change_renders_when_persisted_or_inferred_from_previous_turn() {
assert_eq!(
state
.render_diff(previous)
+ .1
.expect("model change should render")
.markers(),
ModelSwitchInstructions::type_markers()
@@ -29,7 +30,8 @@ fn unchanged_model_does_not_render() {
assert!(
state
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.is_none()
);
- assert!(state.render_diff(PreviousSectionState::Absent).is_none());
+ assert!(state.render_diff(PreviousSectionState::Absent).1.is_none());
}
diff --git a/codex-rs/core/src/context/world_state/multi_agent_mode.rs b/codex-rs/core/src/context/world_state/multi_agent_mode.rs
index bb63e02526..57710ae8e1 100644
--- a/codex-rs/core/src/context/world_state/multi_agent_mode.rs
+++ b/codex-rs/core/src/context/world_state/multi_agent_mode.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use super::multi_agent_usage_hint::MultiAgentUsageHintState;
@@ -35,7 +36,7 @@ impl MultiAgentModeState {
}
pub(crate) fn with_usage_hint(mut self, usage_hint: &MultiAgentUsageHintState) -> Self {
- self.usage_hint_hash = Some(usage_hint.snapshot());
+ self.usage_hint_hash = Some(usage_hint.fingerprint.clone());
self
}
}
@@ -44,10 +45,6 @@ impl WorldStateSection for MultiAgentModeState {
const ID: &'static str = "multi_agent_mode";
type Snapshot = Self;
- fn snapshot(&self) -> Self::Snapshot {
- self.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && MultiAgentModeInstructions::matches_text(text)
}
@@ -63,13 +60,13 @@ impl WorldStateSection for MultiAgentModeState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
let mode = match (&self.mode, previous) {
(Some(mode), PreviousSectionState::Known(previous))
if previous.mode.as_ref() == Some(mode)
&& previous.usage_hint_hash == self.usage_hint_hash =>
{
- return None;
+ return (None, None);
}
(Some(mode), _) => mode.clone(),
(None, PreviousSectionState::Known(previous))
@@ -78,11 +75,14 @@ impl WorldStateSection for MultiAgentModeState {
MultiAgentMode::ExplicitRequestOnly
}
(None, PreviousSectionState::Unknown) => MultiAgentMode::ExplicitRequestOnly,
- (None, PreviousSectionState::Absent | PreviousSectionState::Known(_)) => return None,
+ (None, PreviousSectionState::Absent | PreviousSectionState::Known(_)) => {
+ return (Some(self.clone()), None);
+ }
};
- MultiAgentModeInstructions::from_mode(mode)
- .map(|instructions| Box::new(instructions) as Box<dyn ContextualUserFragment>)
+ let fragment = MultiAgentModeInstructions::from_mode(mode)
+ .map(|instructions| Box::new(instructions) as Box<dyn ContextualUserFragment>);
+ (Some(self.clone()), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/multi_agent_mode_tests.rs b/codex-rs/core/src/context/world_state/multi_agent_mode_tests.rs
index 2741cb3bca..8248c5e2df 100644
--- a/codex-rs/core/src/context/world_state/multi_agent_mode_tests.rs
+++ b/codex-rs/core/src/context/world_state/multi_agent_mode_tests.rs
@@ -84,6 +84,7 @@ fn unchanged_mode_is_reemitted_after_usage_hint_migration() {
let instructions = current
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("unchanged mode should follow migrated usage instructions");
assert_eq!(
@@ -143,13 +144,19 @@ fn catalog_role_updates_remain_separate_from_active_mode() {
#[test]
fn custom_mode_is_bounded_before_snapshot_and_rendering() {
let state = state(Some(MultiAgentMode::Custom("custom mode ".repeat(1_000))));
- let Some(MultiAgentMode::Custom(snapshot_mode)) = state.snapshot().mode else {
+ let Some(MultiAgentMode::Custom(snapshot_mode)) = state
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap()
+ .mode
+ else {
panic!("expected custom multi-agent mode")
};
assert!(approx_token_count(&snapshot_mode) < 1_000);
let rendered = state
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("custom mode should render")
.render();
assert!(approx_token_count(&rendered) < 1_000);
diff --git a/codex-rs/core/src/context/world_state/multi_agent_usage_hint.rs b/codex-rs/core/src/context/world_state/multi_agent_usage_hint.rs
index acdde8a9f6..dcb2bb3be9 100644
--- a/codex-rs/core/src/context/world_state/multi_agent_usage_hint.rs
+++ b/codex-rs/core/src/context/world_state/multi_agent_usage_hint.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
@@ -9,11 +10,16 @@ use crate::context::MultiAgentUsageHint;
#[derive(Clone, Debug)]
pub(crate) struct MultiAgentUsageHintState {
instructions: MultiAgentRoleInstructions,
+ pub(super) fingerprint: WorldStateHash,
}
impl MultiAgentUsageHintState {
pub(crate) fn new(instructions: MultiAgentRoleInstructions) -> Self {
- Self { instructions }
+ let fingerprint = WorldStateHash::from_fragment(&instructions);
+ Self {
+ instructions,
+ fingerprint,
+ }
}
}
@@ -21,10 +27,6 @@ impl WorldStateSection for MultiAgentUsageHintState {
const ID: &'static str = "multi_agent_usage_hint";
type Snapshot = WorldStateHash;
- fn snapshot(&self) -> Self::Snapshot {
- WorldStateHash::from_fragment(&self.instructions)
- }
-
fn matches_current_legacy_fragment(&self, role: &str, text: &str) -> bool {
role == self.instructions.role() && text == self.instructions.render()
}
@@ -32,9 +34,11 @@ impl WorldStateSection for MultiAgentUsageHintState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- match previous {
- PreviousSectionState::Known(previous) if previous == &self.snapshot() => None,
+ ) -> SectionTransition<Self::Snapshot> {
+ let fragment: Option<Box<dyn ContextualUserFragment>> = match previous {
+ PreviousSectionState::Known(previous) if previous == &self.fingerprint => {
+ return (None, None);
+ }
PreviousSectionState::Unknown => None,
PreviousSectionState::Known(_) | PreviousSectionState::Absent => {
if self.instructions.markers().0.is_empty() {
@@ -45,6 +49,7 @@ impl WorldStateSection for MultiAgentUsageHintState {
Some(Box::new(self.instructions.clone()))
}
}
- }
+ };
+ (Some(self.fingerprint.clone()), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/permissions.rs b/codex-rs/core/src/context/world_state/permissions.rs
index 90c13d94f1..d515c5c315 100644
--- a/codex-rs/core/src/context/world_state/permissions.rs
+++ b/codex-rs/core/src/context/world_state/permissions.rs
@@ -1,6 +1,7 @@
//! Tracks model-visible permission instructions and approved-command prefix changes.
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ApprovedCommandPrefixSaved;
@@ -75,10 +76,6 @@ impl WorldStateSection for PermissionsState {
const ID: &'static str = "permissions";
type Snapshot = PermissionsSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- self.snapshot.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && PermissionsInstructions::matches_text(text)
}
@@ -94,7 +91,8 @@ impl WorldStateSection for PermissionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.snapshot.clone();
match (previous, &self.snapshot) {
(
PreviousSectionState::Known(PermissionsSnapshot::Current {
@@ -107,7 +105,7 @@ impl WorldStateSection for PermissionsState {
},
) if previous_instructions == instructions => {
if previous_prefixes == approved_command_prefixes {
- return None;
+ return (None, None);
}
if previous_prefixes.is_subset(approved_command_prefixes) {
let added_prefixes = approved_command_prefixes
@@ -115,18 +113,23 @@ impl WorldStateSection for PermissionsState {
.cloned()
.collect();
if let Some(prefixes) = format_allow_prefixes(added_prefixes) {
- return Some(Box::new(ApprovedCommandPrefixSaved::new(prefixes)));
+ return (
+ Some(current),
+ Some(Box::new(ApprovedCommandPrefixSaved::new(prefixes))),
+ );
}
}
}
(
PreviousSectionState::Known(PermissionsSnapshot::Legacy(previous)),
PermissionsSnapshot::Current { .. },
- ) if previous == &WorldStateHash::from_fragment(&self.instructions) => return None,
+ ) if previous == &WorldStateHash::from_fragment(&self.instructions) => {
+ return (Some(current), None);
+ }
_ => {}
}
- Some(Box::new(self.instructions.clone()))
+ (Some(current), Some(Box::new(self.instructions.clone())))
}
}
diff --git a/codex-rs/core/src/context/world_state/permissions_tests.rs b/codex-rs/core/src/context/world_state/permissions_tests.rs
index 70dc97c4fb..aa80e34dd7 100644
--- a/codex-rs/core/src/context/world_state/permissions_tests.rs
+++ b/codex-rs/core/src/context/world_state/permissions_tests.rs
@@ -49,10 +49,17 @@ fn approved_prefix_is_rendered_without_reinjecting_permissions() {
.expect("test prefix should be valid");
let with_approved_prefix = permissions_state_with_default_messages(&exec_policy);
let approved_prefix = r#"["touch", "allow-prefix.txt"]"#;
- let without_snapshot = without_approved_prefix.snapshot();
- let with_snapshot = with_approved_prefix.snapshot();
+ let without_snapshot = without_approved_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
+ let with_snapshot = with_approved_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
let rendered_update = with_approved_prefix
.render_diff(Known(&without_snapshot))
+ .1
.expect("approving a prefix should render a world-state update")
.render();
@@ -105,19 +112,26 @@ fn renders_only_newly_approved_prefixes() {
.add_prefix_rule(&["cargo".to_string(), "test".to_string()], Decision::Allow)
.expect("test prefix should be valid");
let with_new_prefix = permissions_state_with_default_messages(&exec_policy);
- let existing_snapshot = with_existing_prefix.snapshot();
- let current_snapshot = with_new_prefix.snapshot();
+ let existing_snapshot = with_existing_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
+ let current_snapshot = with_new_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap();
assert_eq!(
with_new_prefix
.render_diff(Known(&existing_snapshot))
+ .1
.map(|fragment| fragment.render()),
Some("Approved command prefix saved:\n- [\"cargo\", \"test\"]".to_string())
);
- assert!(
- with_new_prefix
- .render_diff(Known(&current_snapshot))
- .is_none()
+ let (snapshot, fragment) = with_new_prefix.render_diff(Known(&current_snapshot));
+ assert_eq!(
+ (snapshot, fragment.map(|fragment| fragment.render())),
+ (None, None)
);
}
@@ -174,7 +188,13 @@ fn removing_an_approved_prefix_renders_full_permissions() {
let without_approved_prefix = permissions_state_with_default_messages(&Policy::empty());
let rendered = without_approved_prefix
- .render_diff(Known(&with_approved_prefix.snapshot()))
+ .render_diff(Known(
+ &with_approved_prefix
+ .render_diff(PreviousSectionState::Absent)
+ .0
+ .unwrap(),
+ ))
+ .1
.expect("removing a prefix should refresh permissions")
.render();
diff --git a/codex-rs/core/src/context/world_state/persistent_mode.rs b/codex-rs/core/src/context/world_state/persistent_mode.rs
index 6b05589219..b4582dd41e 100644
--- a/codex-rs/core/src/context/world_state/persistent_mode.rs
+++ b/codex-rs/core/src/context/world_state/persistent_mode.rs
@@ -2,6 +2,7 @@
//! Mode changes retire prior instructions; callers provide the resolved instruction template.
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
@@ -72,13 +73,6 @@ impl WorldStateSection for PersistentModeState {
const ID: &'static str = "persistent_mode";
type Snapshot = PersistentModeSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- PersistentModeSnapshot {
- instructions: (!self.instructions.is_empty())
- .then(|| WorldStateHash::from_fragment(self)),
- }
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && Self::matches_text(text)
}
@@ -94,10 +88,13 @@ impl WorldStateSection for PersistentModeState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- if matches!(previous, PreviousSectionState::Known(previous) if previous == &self.snapshot())
- {
- return None;
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = PersistentModeSnapshot {
+ instructions: (!self.instructions.is_empty())
+ .then(|| WorldStateHash::from_fragment(self)),
+ };
+ if matches!(previous, PreviousSectionState::Known(previous) if previous == &current) {
+ return (None, None);
}
let previous_had_instructions = match previous {
PreviousSectionState::Absent => false,
@@ -105,12 +102,12 @@ impl WorldStateSection for PersistentModeState {
PreviousSectionState::Known(previous) => previous.instructions.is_some(),
};
let instructions = match (self.instructions.as_str(), previous_had_instructions) {
- ("", false) => return None,
+ ("", false) => return (Some(current), None),
("", true) => REMOVAL_NOTICE.to_string(),
(instructions, true) => format!("{REPLACEMENT_NOTICE}\n\n{instructions}"),
(instructions, false) => instructions.to_string(),
};
- Some(Box::new(Self { instructions }))
+ (Some(current), Some(Box::new(Self { instructions })))
}
}
diff --git a/codex-rs/core/src/context/world_state/plugins_instructions.rs b/codex-rs/core/src/context/world_state/plugins_instructions.rs
index 303307317d..373980d5d8 100644
--- a/codex-rs/core/src/context/world_state/plugins_instructions.rs
+++ b/codex-rs/core/src/context/world_state/plugins_instructions.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::AvailablePluginsInstructions;
use crate::context::ContextualUserFragment;
@@ -19,10 +20,6 @@ impl WorldStateSection for PluginsInstructionsState {
const ID: &'static str = "plugins_instructions";
type Snapshot = bool;
- fn snapshot(&self) -> Self::Snapshot {
- self.available
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && AvailablePluginsInstructions::matches_text(text)
}
@@ -38,15 +35,16 @@ impl WorldStateSection for PluginsInstructionsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.available;
if !self.available
|| matches!(previous, PreviousSectionState::Known(previous) if *previous)
|| matches!(previous, PreviousSectionState::Unknown)
{
- return None;
+ return (Some(current), None);
}
- Some(Box::new(AvailablePluginsInstructions))
+ (Some(current), Some(Box::new(AvailablePluginsInstructions)))
}
}
diff --git a/codex-rs/core/src/context/world_state/realtime.rs b/codex-rs/core/src/context/world_state/realtime.rs
index 7911854c08..db4a93151f 100644
--- a/codex-rs/core/src/context/world_state/realtime.rs
+++ b/codex-rs/core/src/context/world_state/realtime.rs
@@ -1,4 +1,5 @@
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use crate::context::RealtimeEndInstructions;
@@ -58,10 +59,6 @@ impl WorldStateSection for RealtimeState {
const ID: &'static str = "realtime";
type Snapshot = RealtimeSnapshot;
- fn snapshot(&self) -> Self::Snapshot {
- self.snapshot.clone()
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && RealtimeStartInstructions::matches_text(text)
}
@@ -77,9 +74,11 @@ impl WorldStateSection for RealtimeState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- match previous {
- PreviousSectionState::Known(previous) if previous == &self.snapshot => None,
+ ) -> SectionTransition<Self::Snapshot> {
+ let fragment = match previous {
+ PreviousSectionState::Known(previous) if previous == &self.snapshot => {
+ return (None, None);
+ }
PreviousSectionState::Known(previous) => self.render_transition(previous.active),
PreviousSectionState::Absent | PreviousSectionState::Unknown
if self.snapshot.active =>
@@ -87,7 +86,8 @@ impl WorldStateSection for RealtimeState {
Some(self.render_start())
}
PreviousSectionState::Absent | PreviousSectionState::Unknown => None,
- }
+ };
+ (Some(self.snapshot.clone()), fragment)
}
}
diff --git a/codex-rs/core/src/context/world_state/test_support.rs b/codex-rs/core/src/context/world_state/test_support.rs
index d698049e58..68d09877da 100644
--- a/codex-rs/core/src/context/world_state/test_support.rs
+++ b/codex-rs/core/src/context/world_state/test_support.rs
@@ -78,6 +78,7 @@ fn sort_json(value: serde_json::Value) -> serde_json::Value {
}
fn snapshot_value<S: WorldStateSection>(section: &S) -> serde_json::Value {
- super::section_snapshot(section, section.snapshot())
+ ErasedWorldStateSection::render_diff(section, PreviousSectionState::Absent)
+ .0
.expect("world-state section snapshot should serialize to a non-null value")
}
diff --git a/codex-rs/core/src/context/world_state/tools.rs b/codex-rs/core/src/context/world_state/tools.rs
index b3f3ff3665..ac9cb197ff 100644
--- a/codex-rs/core/src/context/world_state/tools.rs
+++ b/codex-rs/core/src/context/world_state/tools.rs
@@ -4,9 +4,9 @@
use self::budget::DESCRIPTION_TRUNCATION_SUFFIX;
use self::budget::truncate_namespace_rows;
use super::PreviousSectionState;
+use super::SectionTransition;
use super::WorldStateContextFragment;
use super::WorldStateSection;
-use crate::context::ContextualUserFragment;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::RenderedWorldStateFragment;
use codex_otel::THREAD_TOOLS_FRAGMENT_BYTES_METRIC;
@@ -85,10 +85,6 @@ impl WorldStateSection for ToolsState {
// Object-valued entries let RFC 7386 patches add and remove namespaces individually.
type Snapshot = BTreeMap<String, String>;
- fn snapshot(&self) -> Self::Snapshot {
- self.deferred_namespaces.clone()
- }
-
fn should_persist(&self) -> bool {
!self.deferred_namespaces.is_empty()
}
@@ -96,8 +92,8 @@ impl WorldStateSection for ToolsState {
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- let current = self.snapshot();
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.deferred_namespaces.clone();
if matches!(previous, PreviousSectionState::Known(previous) if previous == &current)
|| self.deferred_namespaces.is_empty()
&& matches!(
@@ -105,7 +101,7 @@ impl WorldStateSection for ToolsState {
PreviousSectionState::Absent | PreviousSectionState::Unknown
)
{
- return None;
+ return (Some(current), None);
}
let rendered = match previous {
@@ -139,14 +135,17 @@ impl WorldStateSection for ToolsState {
}
};
record_fragment_metrics(self.metrics.as_ref(), previous, &rendered);
- Some(Box::new(WorldStateContextFragment {
- fragment: RenderedWorldStateFragment::new(
- "developer",
- (TOOLS_OPEN_TAG, TOOLS_CLOSE_TAG),
- rendered.body,
- ),
- content_kind: ContentItemKind("tools.deferred_namespaces".to_string()),
- }))
+ (
+ Some(current),
+ Some(Box::new(WorldStateContextFragment {
+ fragment: RenderedWorldStateFragment::new(
+ "developer",
+ (TOOLS_OPEN_TAG, TOOLS_CLOSE_TAG),
+ rendered.body,
+ ),
+ content_kind: ContentItemKind("tools.deferred_namespaces".to_string()),
+ })),
+ )
}
}
diff --git a/codex-rs/core/src/context/world_state/tools_tests.rs b/codex-rs/core/src/context/world_state/tools_tests.rs
index 4d4d49c217..5e407a231f 100644
--- a/codex-rs/core/src/context/world_state/tools_tests.rs
+++ b/codex-rs/core/src/context/world_state/tools_tests.rs
@@ -69,6 +69,7 @@ fn renders_first_line_of_namespace_descriptions() {
let rendered = tools
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("tools state should render")
.render();
@@ -101,10 +102,8 @@ fn renders_added_removed_and_updated_namespace_descriptions() {
),
]);
- let rendered = tools
- .render_diff(PreviousSectionState::Known(&previous))
- .expect("tools state delta should render")
- .render();
+ let (snapshot, fragment) = tools.render_diff(PreviousSectionState::Known(&previous));
+ let rendered = fragment.expect("tools state delta should render").render();
assert_eq!(
rendered,
@@ -118,7 +117,8 @@ fn renders_added_removed_and_updated_namespace_descriptions() {
);
assert!(
tools
- .render_diff(PreviousSectionState::Known(&tools.snapshot()))
+ .render_diff(PreviousSectionState::Known(&snapshot.unwrap()))
+ .1
.is_none()
);
assert!(metrics.take().is_empty());
@@ -139,18 +139,16 @@ fn caps_namespace_descriptions_by_character_count() {
Arc::new(RecordingMetrics::default()),
);
+ let (snapshot, fragment) = tools.render_diff(PreviousSectionState::Absent);
assert_eq!(
- tools.snapshot(),
+ snapshot.unwrap(),
BTreeMap::from([
("exact".to_string(), exact_description.clone()),
("over".to_string(), capped_description.clone()),
])
);
assert_eq!(
- tools
- .render_diff(PreviousSectionState::Absent)
- .expect("tools state should render")
- .render(),
+ fragment.expect("tools state should render").render(),
format!(
"<tools>\nDeferred tool namespaces:\n- exact: {exact_description}\n- over: {capped_description}\n</tools>"
)
@@ -177,6 +175,7 @@ fn records_fragment_metrics_after_description_normalization_and_truncation() {
let tools = ToolsState::new(namespaces, metrics.clone());
let rendered = tools
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("tools state should render")
.render();
@@ -204,13 +203,11 @@ fn retains_all_names_before_sharing_description_bytes() {
Arc::new(RecordingMetrics::default()),
);
- let rendered = tools
- .render_diff(PreviousSectionState::Absent)
- .expect("tools state should render")
- .render();
+ let (snapshot, fragment) = tools.render_diff(PreviousSectionState::Absent);
+ let rendered = fragment.expect("tools state should render").render();
- let entries = tools
- .snapshot()
+ let entries = snapshot
+ .unwrap()
.keys()
.enumerate()
.map(|(index, namespace)| {
@@ -243,6 +240,7 @@ fn retains_names_that_fit_without_reserving_an_omission_notice() {
);
let rendered = tools
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("tools state should render")
.render();
let entries = namespaces
@@ -275,6 +273,7 @@ fn preserves_raw_names_and_complete_unicode_at_the_budget_boundary() {
let rendered = tools
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("tools state should render")
.render();
@@ -302,6 +301,7 @@ fn redistributes_description_space_after_short_and_empty_descriptions() {
let rendered = tools
.render_diff(PreviousSectionState::Absent)
+ .1
.expect("tools state should render")
.render();
@@ -325,6 +325,7 @@ fn reserves_names_and_shares_descriptions_across_added_and_removed_groups() {
let rendered = tools
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("tools state delta should render")
.render();
@@ -361,6 +362,7 @@ fn omits_whole_names_per_group_only_after_dropping_every_description() {
let rendered = tools
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("tools state delta should render")
.render();
@@ -383,6 +385,7 @@ fn reserves_the_empty_state_notice_when_all_namespaces_are_removed() {
let rendered = ToolsState::new([], Arc::new(RecordingMetrics::default()))
.render_diff(PreviousSectionState::Known(&previous))
+ .1
.expect("final tools state delta should render")
.render();
diff --git a/codex-rs/core/src/context/world_state/world_state_tests.rs b/codex-rs/core/src/context/world_state/world_state_tests.rs
index 7bb0584e43..ed801bc52e 100644
--- a/codex-rs/core/src/context/world_state/world_state_tests.rs
+++ b/codex-rs/core/src/context/world_state/world_state_tests.rs
@@ -17,21 +17,19 @@ impl WorldStateSection for TestSection {
const ID: &'static str = "test";
type Snapshot = Self;
- fn snapshot(&self) -> Self::Snapshot {
- self.clone()
- }
-
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- match previous {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = self.clone();
+ let fragment: Option<Box<dyn ContextualUserFragment>> = match previous {
PreviousSectionState::Known(previous) if self.value != previous.value => {
Some(Box::new(TestFragment(self.value.clone())))
}
PreviousSectionState::Unknown => Some(Box::new(TestFragment("unknown".to_string()))),
PreviousSectionState::Absent | PreviousSectionState::Known(_) => None,
- }
+ };
+ (Some(current), fragment)
}
}
@@ -73,13 +71,11 @@ impl WorldStateSection for DuplicateTestSection {
const ID: &'static str = "test";
type Snapshot = ();
- fn snapshot(&self) -> Self::Snapshot {}
-
fn render_diff(
&self,
_previous: PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn ContextualUserFragment>> {
- None
+ ) -> SectionTransition<Self::Snapshot> {
+ (Some(()), None)
}
}
diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs
index baede4a4cc..aff9158186 100644
--- a/codex-rs/core/src/context_manager/history_tests.rs
+++ b/codex-rs/core/src/context_manager/history_tests.rs
@@ -1,6 +1,7 @@
use super::*;
use crate::context::APPROVED_COMMAND_PREFIX_SAVED_MESSAGE_PREFIX;
use crate::context::UserInstructions;
+use crate::context::world_state::SectionTransition;
use crate::context::world_state::WorldState;
use crate::context::world_state::WorldStateSection;
use base64::Engine;
@@ -524,10 +525,6 @@ impl WorldStateSection for TestWorldStateSection {
const ID: &'static str = "test";
type Snapshot = bool;
- fn snapshot(&self) -> Self::Snapshot {
- true
- }
-
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "user" && UserInstructions::matches_text(text)
}
@@ -535,18 +532,24 @@ impl WorldStateSection for TestWorldStateSection {
fn render_diff(
&self,
previous: crate::context::world_state::PreviousSectionState<'_, Self::Snapshot>,
- ) -> Option<Box<dyn crate::context::ContextualUserFragment>> {
+ ) -> SectionTransition<Self::Snapshot> {
+ let current = true;
let text = match previous {
- crate::context::world_state::PreviousSectionState::Known(true) => return None,
+ crate::context::world_state::PreviousSectionState::Known(true) => {
+ return (None, None);
+ }
crate::context::world_state::PreviousSectionState::Unknown => "unknown",
crate::context::world_state::PreviousSectionState::Absent
| crate::context::world_state::PreviousSectionState::Known(false) => "test",
};
- Some(Box::new(UserInstructions {
- directory: None,
- text: text.to_string(),
- })
- as Box<dyn crate::context::ContextualUserFragment>)
+ (
+ Some(current),
+ Some(Box::new(UserInstructions {
+ directory: None,
+ text: text.to_string(),
+ })
+ as Box<dyn crate::context::ContextualUserFragment>),
+ )
}
}