Merge f38077e765 into sapling-pr-archive-bolinfest

This commit is contained in:
Michael Bolin
2026-02-28 09:01:15 -08:00
committed by GitHub
23 changed files with 1201 additions and 212 deletions
+9
View File
@@ -1,5 +1,14 @@
load("//:defs.bzl", "codex_rust_crate")
filegroup(
name = "model_availability_nux_fixtures",
srcs = [
"models.json",
"tests/cli_responses_fixture.sse",
],
visibility = ["//visibility:public"],
)
codex_rust_crate(
name = "core",
crate_name = "codex_core",
+49
View File
@@ -227,8 +227,10 @@ mod tests {
use super::*;
use crate::config::ConfigBuilder;
use crate::config_loader::ConfigLayerStackOrdering;
use crate::skills::SkillsManager;
use codex_protocol::openai_models::ReasoningEffort;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;
@@ -470,6 +472,53 @@ writable_roots = ["./sandbox-root"]
assert_eq!(session_flags_layer_count(&config), before_layers + 1);
}
#[cfg_attr(windows, ignore)]
#[tokio::test]
async fn apply_role_skills_config_disables_skill_for_spawned_agent() {
let (home, mut config) = test_config_with_cli_overrides(Vec::new()).await;
let skill_dir = home.path().join("skills").join("demo");
fs::create_dir_all(&skill_dir).expect("create skill dir");
let skill_path = skill_dir.join("SKILL.md");
fs::write(
&skill_path,
"---\nname: demo-skill\ndescription: demo description\n---\n\n# Body\n",
)
.expect("write skill");
let role_path = write_role_config(
&home,
"skills-role.toml",
&format!(
r#"[[skills.config]]
path = "{}"
enabled = false
"#,
skill_path.display()
),
)
.await;
config.agent_roles.insert(
"custom".to_string(),
AgentRoleConfig {
description: None,
config_file: Some(role_path),
},
);
apply_role_to_config(&mut config, Some("custom"))
.await
.expect("custom role should apply");
let skills_manager = SkillsManager::new(home.path().to_path_buf());
let outcome = skills_manager.skills_for_config(&config);
let skill = outcome
.skills
.iter()
.find(|skill| skill.name == "demo-skill")
.expect("demo skill should be discovered");
assert_eq!(outcome.is_skill_enabled(skill), false);
}
#[test]
fn spawn_tool_spec_build_deduplicates_user_defined_built_in_roles() {
let user_defined_roles = BTreeMap::from([
+29 -10
View File
@@ -371,14 +371,20 @@ impl Codex {
.map_err(|err| CodexErr::Fatal(format!("failed to load rules: {err}")))?;
let config = Arc::new(config);
let _ = models_manager
.list_models(crate::models_manager::manager::RefreshStrategy::OnlineIfUncached)
.await;
let model = models_manager
.get_default_model(
&config.model,
crate::models_manager::manager::RefreshStrategy::OnlineIfUncached,
let refresh_strategy = match session_source {
SessionSource::SubAgent(_) => crate::models_manager::manager::RefreshStrategy::Offline,
_ => crate::models_manager::manager::RefreshStrategy::OnlineIfUncached,
};
if config.model.is_none()
|| !matches!(
refresh_strategy,
crate::models_manager::manager::RefreshStrategy::Offline
)
{
let _ = models_manager.list_models(refresh_strategy).await;
}
let model = models_manager
.get_default_model(&config.model, refresh_strategy)
.await;
// Resolve base instructions for the session. Priority order:
@@ -1727,6 +1733,13 @@ impl Session {
async fn record_initial_history(&self, conversation_history: InitialHistory) {
let turn_context = self.new_default_turn().await;
self.clear_mcp_tool_selection().await;
let is_subagent = {
let state = self.state.lock().await;
matches!(
state.session_configuration.session_source,
SessionSource::SubAgent(_)
)
};
match conversation_history {
InitialHistory::New => {
// Build and record initial items (user instructions + environment context)
@@ -1741,7 +1754,9 @@ impl Session {
}
self.set_previous_model(None).await;
// Ensure initial items are visible to immediate readers (e.g., tests, forks).
self.flush_rollout().await;
if !is_subagent {
self.flush_rollout().await;
}
}
InitialHistory::Resumed(resumed_history) => {
let rollout_items = resumed_history.history;
@@ -1792,7 +1807,9 @@ impl Session {
// Defer seeding the session's initial context until the first turn starts so
// turn/start overrides can be merged before we write to the rollout.
self.flush_rollout().await;
if !is_subagent {
self.flush_rollout().await;
}
}
InitialHistory::Forked(rollout_items) => {
let restored_tool_selection =
@@ -1838,7 +1855,9 @@ impl Session {
self.ensure_rollout_materialized().await;
// Flush after seeding history and any persisted rollout copy.
self.flush_rollout().await;
if !is_subagent {
self.flush_rollout().await;
}
}
}
}
+11 -11
View File
@@ -5921,12 +5921,12 @@ mcp_oauth_callback_url = "https://example.com/callback"
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.cloud_requirements(CloudRequirementsLoader::new(async {
Some(crate::config_loader::ConfigRequirementsToml {
Ok(Some(crate::config_loader::ConfigRequirementsToml {
allowed_sandbox_modes: Some(vec![
crate::config_loader::SandboxModeRequirement::ReadOnly,
]),
..Default::default()
})
}))
}))
.build()
.await?;
@@ -5962,9 +5962,9 @@ mcp_oauth_callback_url = "https://example.com/callback"
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cloud_requirements(CloudRequirementsLoader::new(
async move { Some(requirements) },
))
.cloud_requirements(CloudRequirementsLoader::new(async move {
Ok(Some(requirements))
}))
.build()
.await?;
assert_eq!(
@@ -5988,12 +5988,12 @@ mcp_oauth_callback_url = "https://example.com/callback"
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cloud_requirements(CloudRequirementsLoader::new(async {
Some(crate::config_loader::ConfigRequirementsToml {
Ok(Some(crate::config_loader::ConfigRequirementsToml {
allowed_web_search_modes: Some(vec![
crate::config_loader::WebSearchModeRequirement::Cached,
]),
..Default::default()
})
}))
}))
.build()
.await?;
@@ -6029,10 +6029,10 @@ trust_level = "untrusted"
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(workspace.path().to_path_buf()))
.cloud_requirements(CloudRequirementsLoader::new(async {
Some(crate::config_loader::ConfigRequirementsToml {
Ok(Some(crate::config_loader::ConfigRequirementsToml {
allowed_approval_policies: Some(vec![AskForApproval::OnRequest]),
..Default::default()
})
}))
}))
.build()
.await?;
@@ -6058,10 +6058,10 @@ trust_level = "untrusted"
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cloud_requirements(CloudRequirementsLoader::new(async {
Some(crate::config_loader::ConfigRequirementsToml {
Ok(Some(crate::config_loader::ConfigRequirementsToml {
allowed_approval_policies: Some(vec![AskForApproval::OnRequest]),
..Default::default()
})
}))
}))
.build()
.await?;
+1 -1
View File
@@ -26,7 +26,7 @@ pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev";
pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 16;
pub const DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS: i64 = 30;
pub const DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS: i64 = 6;
pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL: usize = 1_024;
pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL: usize = 256;
pub const DEFAULT_MEMORIES_MAX_UNUSED_DAYS: i64 = 30;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
+2 -1
View File
@@ -25,6 +25,7 @@ use std::path::Path;
use std::path::PathBuf;
use toml::Value as TomlValue;
pub use codex_config::CloudRequirementsLoadError;
pub use codex_config::CloudRequirementsLoader;
pub use codex_config::ConfigError;
pub use codex_config::ConfigLayerEntry;
@@ -116,7 +117,7 @@ pub async fn load_config_layers_state(
) -> io::Result<ConfigLayerStack> {
let mut config_requirements_toml = ConfigRequirementsWithSources::default();
if let Some(requirements) = cloud_requirements.get().await {
if let Some(requirements) = cloud_requirements.get().await.map_err(io::Error::other)? {
config_requirements_toml
.merge_unset_fields(RequirementSource::CloudRequirements, requirements);
}
+29 -3
View File
@@ -5,6 +5,7 @@ use crate::config::ConfigOverrides;
use crate::config::ConfigToml;
use crate::config::ConstraintError;
use crate::config::ProjectConfig;
use crate::config_loader::CloudRequirementsLoadError;
use crate::config_loader::CloudRequirementsLoader;
use crate::config_loader::ConfigLayerEntry;
use crate::config_loader::ConfigLoadError;
@@ -576,7 +577,7 @@ allowed_approval_policies = ["on-request"]
..LoaderOverrides::default()
},
CloudRequirementsLoader::new(async {
Some(ConfigRequirementsToml {
Ok(Some(ConfigRequirementsToml {
allowed_approval_policies: Some(vec![AskForApproval::Never]),
allowed_sandbox_modes: None,
allowed_web_search_modes: None,
@@ -584,7 +585,7 @@ allowed_approval_policies = ["on-request"]
rules: None,
enforce_residency: None,
network: None,
})
}))
}),
)
.await?;
@@ -671,7 +672,7 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()>
network: None,
};
let expected = requirements.clone();
let cloud_requirements = CloudRequirementsLoader::new(async move { Some(requirements) });
let cloud_requirements = CloudRequirementsLoader::new(async move { Ok(Some(requirements)) });
let layers = load_config_layers_state(
&codex_home,
@@ -702,6 +703,31 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()>
Ok(())
}
#[tokio::test]
async fn load_config_layers_fails_when_cloud_requirements_loader_fails() -> anyhow::Result<()> {
let tmp = tempdir()?;
let codex_home = tmp.path().join("home");
tokio::fs::create_dir_all(&codex_home).await?;
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path())?;
let err = load_config_layers_state(
&codex_home,
Some(cwd),
&[] as &[(String, TomlValue)],
LoaderOverrides::default(),
CloudRequirementsLoader::new(async {
Err(CloudRequirementsLoadError::new("cloud requirements failed"))
}),
)
.await
.expect_err("cloud requirements failure should fail closed");
assert_eq!(err.kind(), std::io::ErrorKind::Other);
assert!(err.to_string().contains("cloud requirements failed"));
Ok(())
}
#[tokio::test]
async fn project_layers_prefer_closest_cwd() -> std::io::Result<()> {
let tmp = tempdir()?;
+109 -16
View File
@@ -5,6 +5,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::sync::RwLock;
use codex_app_server_protocol::ConfigLayerSource;
use codex_protocol::protocol::SkillScope;
use codex_utils_absolute_path::AbsolutePathBuf;
use toml::Value as TomlValue;
@@ -14,6 +15,7 @@ use tracing::warn;
use crate::config::Config;
use crate::config::types::SkillsConfig;
use crate::config_loader::CloudRequirementsLoader;
use crate::config_loader::ConfigLayerStackOrdering;
use crate::config_loader::LoaderOverrides;
use crate::config_loader::load_config_layers_state;
use crate::skills::SkillLoadOutcome;
@@ -172,24 +174,31 @@ fn disabled_paths_from_stack(
) -> HashSet<PathBuf> {
let mut disabled = HashSet::new();
let mut configs = HashMap::new();
// Skills config is user-layer only for now; higher-precedence layers are ignored.
let Some(user_layer) = config_layer_stack.get_user_layer() else {
return disabled;
};
let Some(skills_value) = user_layer.config.get("skills") else {
return disabled;
};
let skills: SkillsConfig = match skills_value.clone().try_into() {
Ok(skills) => skills,
Err(err) => {
warn!("invalid skills config: {err}");
return disabled;
for layer in
config_layer_stack.get_layers(ConfigLayerStackOrdering::LowestPrecedenceFirst, true)
{
if !matches!(
layer.name,
ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags
) {
continue;
}
};
for entry in skills.config {
let path = normalize_override_path(entry.path.as_path());
configs.insert(path, entry.enabled);
let Some(skills_value) = layer.config.get("skills") else {
continue;
};
let skills: SkillsConfig = match skills_value.clone().try_into() {
Ok(skills) => skills,
Err(err) => {
warn!("invalid skills config: {err}");
continue;
}
};
for entry in skills.config {
let path = normalize_override_path(entry.path.as_path());
configs.insert(path, entry.enabled);
}
}
for (path, enabled) in configs {
@@ -220,6 +229,9 @@ mod tests {
use super::*;
use crate::config::ConfigBuilder;
use crate::config::ConfigOverrides;
use crate::config_loader::ConfigLayerEntry;
use crate::config_loader::ConfigLayerStack;
use crate::config_loader::ConfigRequirementsToml;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::PathBuf;
@@ -402,4 +414,85 @@ mod tests {
assert_eq!(first, second);
}
#[cfg_attr(windows, ignore)]
#[test]
fn disabled_paths_from_stack_allows_session_flags_to_override_user_layer() {
let tempdir = tempfile::tempdir().expect("tempdir");
let skill_path = tempdir.path().join("skills").join("demo").join("SKILL.md");
let user_file = AbsolutePathBuf::try_from(tempdir.path().join("config.toml"))
.expect("user config path should be absolute");
let user_layer = ConfigLayerEntry::new(
ConfigLayerSource::User { file: user_file },
toml::from_str(&format!(
r#"[[skills.config]]
path = "{}"
enabled = false
"#,
skill_path.display()
))
.expect("user layer toml"),
);
let session_layer = ConfigLayerEntry::new(
ConfigLayerSource::SessionFlags,
toml::from_str(&format!(
r#"[[skills.config]]
path = "{}"
enabled = true
"#,
skill_path.display()
))
.expect("session layer toml"),
);
let stack = ConfigLayerStack::new(
vec![user_layer, session_layer],
Default::default(),
ConfigRequirementsToml::default(),
)
.expect("valid config layer stack");
assert_eq!(disabled_paths_from_stack(&stack), HashSet::new());
}
#[cfg_attr(windows, ignore)]
#[test]
fn disabled_paths_from_stack_allows_session_flags_to_disable_user_enabled_skill() {
let tempdir = tempfile::tempdir().expect("tempdir");
let skill_path = tempdir.path().join("skills").join("demo").join("SKILL.md");
let user_file = AbsolutePathBuf::try_from(tempdir.path().join("config.toml"))
.expect("user config path should be absolute");
let user_layer = ConfigLayerEntry::new(
ConfigLayerSource::User { file: user_file },
toml::from_str(&format!(
r#"[[skills.config]]
path = "{}"
enabled = true
"#,
skill_path.display()
))
.expect("user layer toml"),
);
let session_layer = ConfigLayerEntry::new(
ConfigLayerSource::SessionFlags,
toml::from_str(&format!(
r#"[[skills.config]]
path = "{}"
enabled = false
"#,
skill_path.display()
))
.expect("session layer toml"),
);
let stack = ConfigLayerStack::new(
vec![user_layer, session_layer],
Default::default(),
ConfigRequirementsToml::default(),
)
.expect("valid config layer stack");
assert_eq!(
disabled_paths_from_stack(&stack),
HashSet::from([skill_path])
);
}
}
+66 -4
View File
@@ -48,13 +48,75 @@ Quick-pass budget:
During execution: if you hit repeated errors, confusing behavior, or suspect
relevant prior context, redo the quick memory pass.
When to update memory:
How to decide whether to verify memory:
- Consider both risk of drift and verification effort.
- If a fact is likely to drift and is cheap to verify, verify it before
answering.
- If a fact is likely to drift but verification is expensive, slow, or
disruptive, it is acceptable to answer from memory in an interactive turn,
but you should say that it is memory-derived, note that it may be stale, and
consider offering to refresh it live.
- If a fact is lower-drift and cheap to verify, use judgment: verification is
more important when the fact is central to the answer or especially easy to
confirm.
- If a fact is lower-drift and expensive to verify, it is usually fine to
answer from memory directly.
When answering from memory without current verification:
- If you rely on memory for a fact that you did not verify in the current turn,
say so briefly in the final answer.
- If that fact is plausibly drift-prone or comes from an older note, older
snapshot, or prior run summary, say that it may be stale or outdated.
- If live verification was skipped and a refresh would be useful in the
interactive context, consider offering to verify or refresh it live.
- Do not present unverified memory-derived facts as confirmed-current.
- For interactive requests, prefer a short refresh offer over silently doing
expensive verification that the user did not ask for.
- When the unverified fact is about prior results, commands, timing, or an
older snapshot, a concrete refresh offer can be especially helpful.
When to update memory (automatic, same turn; required):
- Treat memory as guidance, not truth: if memory conflicts with current repo
state, tool outputs, environment, or user feedback, current evidence wins.
- If you discover stale/misleading memory, update memory files accordingly.
- When user explicitly asks to remember/update memory, revise memory_summary.md
and/or MEMORY.md.
- Memory is writable. You are authorized to edit {{ base_path }}/MEMORY.md and
{{ base_path }}/memory_summary.md when stale guidance is detected.
- If any memory fact conflicts with current evidence (repo state, tool output,
or user correction), you MUST update memory in the same turn. Do not wait for
a separate user prompt.
- If you detect stale memory, updating MEMORY.md is part of task completion,
not optional cleanup.
- A final answer without the required MEMORY.md edit is incorrect.
- A memory entry can be partially stale: if the broad guidance is still useful
but a stored detail is outdated (for example line numbers, exact paths, exact
commands, or exact model/version strings), you should keep using current
evidence in your answer and update the stale detail in MEMORY.md.
- Correcting only the answer is not enough when you have identified a stale
stored detail in memory.
- If memory contains a broad point that is still right but any concrete stored
detail is wrong or outdated, the memory is stale and MEMORY.md should be
corrected in the same turn after you verify the replacement.
- Required behavior after detecting stale memory:
1. Verify the correct replacement using local evidence.
2. Continue the task using current evidence; do not rely on stale memory.
3. Edit memory files later in the same turn, before your final response:
- Always update {{ base_path }}/MEMORY.md.
- Update {{ base_path }}/memory_summary.md only if the correction affects
reusable guidance and you have complete local file context for a
targeted edit.
4. Read back the changed MEMORY.md lines to confirm the update.
5. Finalize the task after the memory updates are written.
- Do not finish the turn until the stale memory is corrected or you have
determined the correction is ambiguous.
- If you verified a contradiction and did not edit MEMORY.md, the task is
incomplete.
- Only ask a clarifying question instead of editing when the replacement is
ambiguous (multiple plausible targets with low confidence and no single
verified replacement from local evidence).
- When user explicitly asks to remember something or update the memory, revise
the files accordingly.
Memory citation requirements: