From 17e79ae616f2ea6b089e268f80461a7d3a4d8d45 Mon Sep 17 00:00:00 2001 From: ioanbudea-OAI Date: Wed, 18 Nov 2026 12:47:17 +0000 Subject: [PATCH] Support independent refreshes of managed Guardian policy (#62274) ## Why Refreshing Guardian policy should preserve session configuration and allow policy updates even when unrelated managed settings are invalid. ## What changed Add a revisioned snapshot that loads and applies Guardian reviewer restrictions, required models, and policy text together. Preserve the cloud bundle binding and allow the active policy to carry forward when another refresh rebuilds the configuration stack. Merge refreshed `auto_review.policy` fallbacks with retained layers in precedence order before validating the result. ## Testing Add a regression test covering an invalid unrelated managed setting, fallback validation after merging a session override, and removal of stale policy text when its managed bundle disappears. GitOrigin-RevId: ac42925eb916355d9972c3e2a0dd91041b06e47a --- codex-rs/config/src/guardian_policy.rs | 101 +++++++++++ codex-rs/config/src/lib.rs | 2 + codex-rs/config/src/loader/layer_io.rs | 11 +- codex-rs/config/src/loader/local.rs | 2 +- .../config/src/loader/managed_requirements.rs | 164 ++++++++++++++++-- codex-rs/config/src/loader/mod.rs | 1 + codex-rs/config/src/loader/tests.rs | 96 ++++++++++ .../config/src/requirements_layers/layer.rs | 10 +- codex-rs/config/src/state.rs | 111 ++++++++++++ 9 files changed, 470 insertions(+), 28 deletions(-) create mode 100644 codex-rs/config/src/guardian_policy.rs diff --git a/codex-rs/config/src/guardian_policy.rs b/codex-rs/config/src/guardian_policy.rs new file mode 100644 index 0000000000..f6cc00db68 --- /dev/null +++ b/codex-rs/config/src/guardian_policy.rs @@ -0,0 +1,101 @@ +//! Defines the managed review policy boundary and its ordered publication snapshot. +//! Reviewer permissions, model requirements, and policy text always travel together. + +use crate::CloudConfigBundleBinding; +use crate::ConfigLayerEntry; +use crate::ConfigLayerSource; +use crate::ConfigRequirements; +use crate::ConfigRequirementsToml; +use crate::ConfigRequirementsWithSources; + +/// Parsed and raw forms of the requirements projected by the Guardian loader. +#[derive(Debug)] +pub(crate) struct GuardianPolicy { + pub(crate) requirements: ConfigRequirements, + pub(crate) requirements_toml: ConfigRequirementsToml, +} + +/// Copies the same Guardian requirements during publication and preservation. +pub(crate) fn copy_guardian_requirements( + parsed: &mut ConfigRequirements, + raw: &mut ConfigRequirementsToml, + source: &ConfigRequirements, + source_raw: &ConfigRequirementsToml, +) { + parsed.approvals_reviewer = source.approvals_reviewer.clone(); + parsed.auto_review_required_models = source.auto_review_required_models.clone(); + parsed.guardian_policy_config_source = source.guardian_policy_config_source.clone(); + parsed.guardian_extra_policy_source = source.guardian_extra_policy_source.clone(); + raw.allowed_approvals_reviewers + .clone_from(&source_raw.allowed_approvals_reviewers); + raw.auto_review.clone_from(&source_raw.auto_review); + raw.guardian_policy_config + .clone_from(&source_raw.guardian_policy_config); + raw.guardian_extra_policy + .clone_from(&source_raw.guardian_extra_policy); +} + +/// One managed review policy observation. Revisions are allocated before loading; +/// publication records even unchanged observations to reject older in-flight work. +#[derive(Debug)] +pub struct GuardianPolicySnapshot { + pub revision: u64, + pub binding: Option, + pub(crate) policy: Box, + pub(crate) managed_config: Vec, +} + +impl GuardianPolicySnapshot { + pub(crate) fn from_requirements( + revision: u64, + requirements: ConfigRequirementsWithSources, + binding: Option, + managed_config: Vec, + ) -> std::io::Result { + let parsed = ConfigRequirements::try_from(requirements.clone())?; + Ok(Self { + revision, + binding, + policy: Box::new(GuardianPolicy { + requirements: parsed, + requirements_toml: requirements.into_toml(), + }), + managed_config, + }) + } +} + +/// The projected `auto_review` value and precedence of an enabled config layer. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GuardianFallbackLayer { + pub(crate) source: ConfigLayerSource, + pub(crate) value: toml::Value, +} + +impl GuardianFallbackLayer { + pub(crate) fn new(source: ConfigLayerSource, mut value: toml::Value) -> Self { + if let Some(table) = value.as_table_mut() { + table.retain(|key, _| key == "policy"); + } + Self { source, value } + } + + pub(crate) fn project(layer: &ConfigLayerEntry) -> Option { + // An omitted section contributes nothing. A table, even an empty one, + // replaces an earlier scalar, and a surviving scalar fails validation. + let value = match layer.config.get("auto_review")? { + toml::Value::Table(table) => toml::Value::Table( + table + .get("policy") + .map(|value| ("policy".to_owned(), value.clone())) + .into_iter() + .collect(), + ), + value => value.clone(), + }; + Some(Self { + source: layer.name.clone(), + value, + }) + } +} diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index 05ed1eb435..bc1793b33e 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -17,6 +17,8 @@ mod diagnostics; mod filesystem_constraints; mod fingerprint; mod guardian; +mod guardian_policy; +pub use guardian_policy::GuardianPolicySnapshot; mod hook_config; mod host_name; mod in_app_browser_requirements; diff --git a/codex-rs/config/src/loader/layer_io.rs b/codex-rs/config/src/loader/layer_io.rs index 1f6bf6b92d..719ccbe21e 100644 --- a/codex-rs/config/src/loader/layer_io.rs +++ b/codex-rs/config/src/loader/layer_io.rs @@ -46,7 +46,7 @@ pub(super) struct LoadedConfigLayers { pub(super) async fn load_config_layers_internal( fs: &dyn ExecutorFileSystem, codex_home: &Path, - overrides: LoaderOverrides, + overrides: &LoaderOverrides, strict_config: bool, ) -> io::Result { #[cfg(target_os = "macos")] @@ -67,9 +67,10 @@ pub(super) async fn load_config_layers_internal( #[cfg(not(windows))] let ignore_default_managed_config = false; - let managed_config_path = AbsolutePathBuf::from_absolute_path( - managed_config_path.unwrap_or_else(|| managed_config_default_path(codex_home)), - )?; + let managed_config_path = match managed_config_path { + Some(path) => AbsolutePathBuf::from_absolute_path(path)?, + None => AbsolutePathBuf::from_absolute_path(managed_config_default_path(codex_home))?, + }; #[cfg(windows)] let startup_warnings = if ignore_default_managed_config { @@ -114,7 +115,7 @@ pub(super) async fn load_config_layers_internal( .await? .map(|loaded| MangedConfigFromFile { managed_config: loaded, - file: managed_config_path.clone(), + file: managed_config_path, }) }; diff --git a/codex-rs/config/src/loader/local.rs b/codex-rs/config/src/loader/local.rs index 5a42cb4775..891a6bae78 100644 --- a/codex-rs/config/src/loader/local.rs +++ b/codex-rs/config/src/loader/local.rs @@ -111,7 +111,7 @@ pub(super) async fn load_local_config_layers_with_overrides( let loaded_managed = layer_io::load_config_layers_internal( fs, codex_home.as_path(), - overrides.clone(), + overrides, /*strict_config*/ false, ) .await?; diff --git a/codex-rs/config/src/loader/managed_requirements.rs b/codex-rs/config/src/loader/managed_requirements.rs index f2b55fc315..bf76aaa8f4 100644 --- a/codex-rs/config/src/loader/managed_requirements.rs +++ b/codex-rs/config/src/loader/managed_requirements.rs @@ -1,5 +1,5 @@ -//! Loads managed requirements independently of user and project configuration, -//! retaining source layers for diagnostics during full configuration loads. +//! Reads managed requirements in precedence order. Full configuration and Guardian +//! policy compose and validate their own views of those sources. use super::layer_io; use super::layer_io::LoadedConfigLayers; @@ -8,11 +8,16 @@ use super::load_requirements_toml; use super::macos; use super::requirements_layers_from_legacy_scheme; use super::system_requirements_toml_file_with_overrides; +use crate::CloudConfigBundleLoader; +use crate::CloudConfigBundleSnapshot; +use crate::ConfigLayerSource; use crate::ConfigRequirements; use crate::ConfigRequirementsToml; +use crate::GuardianPolicySnapshot; use crate::RequirementsLayerEntry; use crate::compose_requirements; use crate::config_requirements::ConfigRequirementsWithSources; +use crate::guardian_policy::GuardianFallbackLayer; use crate::state::ConfigLoadOptions; use crate::state::LoaderOverrides; use codex_file_system::ExecutorFileSystem; @@ -63,9 +68,118 @@ pub async fn load_managed_requirements_state( Ok(requirements_toml) } -/// Composes the same requirements for full config loads and policy-only checks. -/// The loaded legacy config and source layers are also returned for the full -/// config stack and its ignored-field diagnostics. +/// Loads only managed review requirements, preserving their provenance and source validity. +pub async fn load_guardian_policy_snapshot( + fs: &dyn ExecutorFileSystem, + codex_home: &Path, + overrides: &LoaderOverrides, + cloud_config_bundle: &CloudConfigBundleLoader, + revision: u64, +) -> io::Result { + let mut legacy = layer_io::load_config_layers_internal( + fs, codex_home, overrides, /*strict_config*/ false, + ) + .await?; + let snapshot = if overrides.ignore_managed_requirements { + CloudConfigBundleSnapshot { + config_server: None, + bundle: Ok(None), + binding: None, + } + } else { + cloud_config_bundle.get_snapshot().await + }; + let base = AbsolutePathBuf::from_absolute_path(codex_home)?; + let bundle = snapshot + .bundle + .map_err(io::Error::other)? + .unwrap_or_default(); + // Cloud fragments arrive highest priority first; merging proceeds lowest first. + let mut managed_config = Vec::new(); + for fragment in bundle.config_toml.enterprise_managed.into_iter().rev() { + let mut table: toml::Table = + toml::from_str(&fragment.contents).map_err(io::Error::other)?; + if let Some(value) = table.remove("auto_review") { + managed_config.push(GuardianFallbackLayer::new( + ConfigLayerSource::EnterpriseManaged { + id: fragment.id, + name: fragment.name, + }, + value, + )); + } + } + // Preserve the fallbacks before narrowing legacy config to reviewer requirements. + let mut project_legacy = |source, config: &mut toml::Value| { + if let Some(table) = config.as_table_mut() { + if let Some(value) = table.remove("auto_review") { + managed_config.push(GuardianFallbackLayer::new(source, value)); + } + table.retain(|key, _| key == "approvals_reviewer"); + } + }; + if let Some(layer) = &mut legacy.managed_config { + project_legacy( + ConfigLayerSource::LegacyManagedConfigTomlFromFile { + file: layer.file.clone(), + }, + &mut layer.managed_config, + ); + } + if let Some(layer) = &mut legacy.managed_config_from_mdm { + project_legacy( + ConfigLayerSource::LegacyManagedConfigTomlFromMdm, + &mut layer.managed_config, + ); + } + let layers = bundle + .requirements_toml + .into_layers() + .into_iter() + .map(|layer| layer.with_base_dir(base.clone())) + .collect(); + let requirements_layers = + load_requirements_layers(fs, codex_home, overrides, legacy, layers).await?; + let requirements_layers = requirements_layers + .into_iter() + .map(|layer| { + let (source, mut value, base_dir) = layer.into_raw_parts()?; + if let Some(table) = value.as_table_mut() { + table.retain(|key, _| { + matches!( + key, + "allowed_approvals_reviewers" + | "auto_review" + | "guardian_policy_config" + | "guardian_extra_policy" + | "config_server" + ) + }); + } + let layer = RequirementsLayerEntry::from_toml_value(source, value); + Ok::<_, io::Error>(match base_dir { + Some(base) => layer.with_base_dir(base), + None => layer, + }) + }) + .collect::>>()?; + let mut requirements = compose_requirements(requirements_layers)?.unwrap_or_default(); + if requirements.config_server.take().map(|source| source.value) != snapshot.config_server { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Required managed configuration has not been loaded", + )); + } + // Fallbacks are validated after retained thread layers have been merged. + GuardianPolicySnapshot::from_requirements( + revision, + requirements, + snapshot.binding, + managed_config, + ) +} + +/// Composes all managed requirements and retains source layers for diagnostics. pub(super) async fn load_requirements_from_sources( fs: &dyn ExecutorFileSystem, codex_home: &Path, @@ -77,6 +191,32 @@ pub(super) async fn load_requirements_from_sources( LoadedConfigLayers, Vec, )> { + let loaded_config_layers = + layer_io::load_config_layers_internal(fs, codex_home, overrides, strict_config).await?; + let requirements_layers = load_requirements_layers( + fs, + codex_home, + overrides, + loaded_config_layers.clone(), + bundle_requirements, + ) + .await?; + let mut requirements = compose_requirements(requirements_layers.clone())?.unwrap_or_default(); + if overrides.ignore_login_requirements { + requirements.allowed_login_methods = None; + requirements.allowed_chatgpt_workspaces = None; + } + Ok((requirements, loaded_config_layers, requirements_layers)) +} + +/// Collects ordered requirement layers, converting the supplied legacy configuration. +async fn load_requirements_layers( + fs: &dyn ExecutorFileSystem, + codex_home: &Path, + overrides: &LoaderOverrides, + legacy_config: LoadedConfigLayers, + bundle_requirements: Vec, +) -> io::Result> { let mut requirements_layers = Vec::new(); let mut system_requirements_layer = None; let managed_preferences_requirements_layer; @@ -103,24 +243,14 @@ pub(super) async fn load_requirements_from_sources( managed_preferences_requirements_layer = None; } - let loaded_config_layers = - layer_io::load_config_layers_internal(fs, codex_home, overrides.clone(), strict_config) - .await?; if !overrides.ignore_managed_requirements { requirements_layers.extend(system_requirements_layer); requirements_layers.extend(bundle_requirements); - // Legacy managed_config.toml contributes approval and sandbox requirements. requirements_layers.extend(requirements_layers_from_legacy_scheme( - loaded_config_layers.clone(), + legacy_config, codex_home, )?); requirements_layers.extend(managed_preferences_requirements_layer); } - - let mut requirements = compose_requirements(requirements_layers.clone())?.unwrap_or_default(); - if overrides.ignore_login_requirements { - requirements.allowed_login_methods = None; - requirements.allowed_chatgpt_workspaces = None; - } - Ok((requirements, loaded_config_layers, requirements_layers)) + Ok(requirements_layers) } diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index ec769d6b5a..d853b8b6b6 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -72,6 +72,7 @@ pub use local::LocalConfigLayers; pub use local::LocalTomlLayer; pub use local::LocalTomlLayerStack; pub use local::load_local_config_layers; +pub use managed_requirements::load_guardian_policy_snapshot; pub use managed_requirements::load_managed_requirements_state; #[cfg(windows)] pub use windows::WindowsSystemConfigNamespaceProbe; diff --git a/codex-rs/config/src/loader/tests.rs b/codex-rs/config/src/loader/tests.rs index 57b057733a..bdf390702d 100644 --- a/codex-rs/config/src/loader/tests.rs +++ b/codex-rs/config/src/loader/tests.rs @@ -1366,3 +1366,99 @@ fn otel_headers_helper_interval_must_be_positive() { 900000 ); } + +#[tokio::test] +async fn guardian_refresh_validates_fallback_after_merging_retained_layers() { + let mut stack = ConfigLayerStack::new( + vec![ + ConfigLayerEntry::new( + ConfigLayerSource::EnterpriseManaged { + id: "workspace".into(), + name: "Workspace".into(), + }, + toml::from_str("[auto_review]\npolicy = 'old policy'").unwrap(), + ), + ConfigLayerEntry::new( + ConfigLayerSource::SessionFlags, + toml::from_str("model = 'session-model'").unwrap(), + ), + ], + ConfigRequirements { + allow_login_shell: Some(crate::Sourced::new( + /*value*/ false, + RequirementSource::Unknown, + )), + ..Default::default() + }, + ConfigRequirementsToml { + allow_login_shell: Some(false), + ..Default::default() + }, + ) + .unwrap(); + let home = tempdir().unwrap(); + let path = home.path().join("managed.toml"); + std::fs::write(&path, "sandbox_mode = 'invalid'").unwrap(); + let overrides = LoaderOverrides::with_managed_config_path_for_tests(path); + let load = |cloud_config_bundle, revision| { + load_guardian_policy_snapshot( + &TestFileSystem, + home.path(), + &overrides, + cloud_config_bundle, + revision, + ) + }; + let bundle = + crate::test_support::CloudConfigBundleFixture::enterprise_config("model = 'irrelevant'") + .add_enterprise_config("auto_review = 1") + .add_enterprise_config("auto_review.policy = 'lower priority'") + .add_enterprise_requirement("allowed_approvals_reviewers = ['auto_review']") + .into_loader(); + let snapshot = load(&bundle, /*revision*/ 1).await.unwrap(); + let before = stack.effective_config(); + let mut retained = stack.clone(); + stack.apply_guardian_policy(&snapshot); + retained.retain_guardian_policy_from(&stack); + assert_eq!(retained, stack); + assert!( + stack + .requirements() + .approvals_reviewer + .can_set(&codex_protocol::config_types::ApprovalsReviewer::User) + .is_err() + ); + assert_eq!(stack.effective_config(), before); + assert_eq!( + stack.requirements().allow_login_shell, + Some(crate::Sourced::new( + /*value*/ false, + RequirementSource::Unknown + )) + ); + assert!(stack.guardian_config().is_err()); + + let local = stack + .clone() + .with_session_config(toml::from_str("auto_review.policy = 'local'").unwrap()) + .unwrap(); + assert_eq!( + local.guardian_config().unwrap(), + crate::config_toml::AutoReviewToml { + policy: Some("local".to_owned()), + ..Default::default() + } + ); + // Removing the workspace bundle must not revive its old managed fallback. + let removed = load( + &crate::CloudConfigBundleLoader::default(), + snapshot.revision + 1, + ) + .await + .unwrap(); + stack.apply_guardian_policy(&removed); + assert_eq!( + stack.guardian_config().unwrap(), + crate::config_toml::AutoReviewToml::default() + ); +} diff --git a/codex-rs/config/src/requirements_layers/layer.rs b/codex-rs/config/src/requirements_layers/layer.rs index e02700aebd..9af575f0a6 100644 --- a/codex-rs/config/src/requirements_layers/layer.rs +++ b/codex-rs/config/src/requirements_layers/layer.rs @@ -67,7 +67,7 @@ impl RequirementsLayerEntry { base_dir, path_context: _, } = self; - let toml = parse_layer_toml(&toml, &source)?; + let toml = parse_layer_toml(toml, &source)?; Ok((source, toml, base_dir)) } } @@ -100,7 +100,7 @@ impl ComposableRequirementsLayer { let _guard = base_dir .as_ref() .map(|base_dir| AbsolutePathBufGuard::new(base_dir.as_path())); - let mut regular_toml = parse_layer_toml(&toml, &source)?; + let mut regular_toml = parse_layer_toml(toml, &source)?; if matches!(source, RequirementSource::EnterpriseManaged { .. }) && regular_toml.get("config_server").is_some() @@ -240,19 +240,19 @@ pub(super) struct DomainMergedRequirementsFields { } fn parse_layer_toml( - toml: &RequirementsLayerToml, + toml: RequirementsLayerToml, source: &RequirementSource, ) -> Result { match toml { RequirementsLayerToml::String(contents) => { - toml::from_str(contents).map_err(|err: toml::de::Error| { + toml::from_str(&contents).map_err(|err: toml::de::Error| { RequirementsCompositionError::Parse { layer_source: source.clone(), message: err.to_string(), } }) } - RequirementsLayerToml::Value(value) => Ok(value.clone()), + RequirementsLayerToml::Value(value) => Ok(value), } } diff --git a/codex-rs/config/src/state.rs b/codex-rs/config/src/state.rs index f53328a711..4fe4d788e9 100644 --- a/codex-rs/config/src/state.rs +++ b/codex-rs/config/src/state.rs @@ -12,6 +12,8 @@ use crate::ConfigLayer; use crate::ConfigLayerMetadata; use crate::ConfigLayerSource; use crate::ProfileV2Name; +use crate::guardian_policy::GuardianFallbackLayer; +use crate::guardian_policy::copy_guardian_requirements; use crate::shell_environment_policy::validate_shell_environment_policy_filter_config; use crate::types::AppsConfigToml; use codex_utils_absolute_path::AbsolutePathBuf; @@ -19,6 +21,7 @@ use serde_json::Value as JsonValue; use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use toml::Value as TomlValue; /// User-facing config loading behavior that is not part of the config document. @@ -262,6 +265,10 @@ pub struct ConfigLayerStack { /// Layers are listed from lowest precedence (base) to highest (top), so /// later entries in the Vec override earlier ones. layers: Vec, + /// Guardian's fallback layers apart from the retained user and session layers. + guardian_config: Option>, + /// Runtime source validity for the independently published Guardian snapshot. + guardian_binding: Option, /// Constraints that must be enforced when deriving a [Config] from the /// layers. @@ -293,6 +300,8 @@ impl PartialEq for ConfigLayerStack { applied_config_server, model_provider_requirements, layers, + guardian_config, + guardian_binding: _, requirements, requirements_toml, ignore_user_and_project_exec_policy_rules, @@ -302,6 +311,7 @@ impl PartialEq for ConfigLayerStack { } = self; applied_config_server == &other.applied_config_server && model_provider_requirements == &other.model_provider_requirements + && guardian_config == &other.guardian_config && layers == &other.layers && requirements == &other.requirements && requirements_toml == &other.requirements_toml @@ -313,6 +323,22 @@ impl PartialEq for ConfigLayerStack { } } +fn is_user_or_session_layer(source: &ConfigLayerSource) -> bool { + matches!( + source, + ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags + ) +} + +fn is_managed_guardian_layer(source: &ConfigLayerSource) -> bool { + matches!( + source, + ConfigLayerSource::EnterpriseManaged { .. } + | ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } + | ConfigLayerSource::LegacyManagedConfigTomlFromMdm + ) +} + impl ConfigLayerStack { pub fn new( layers: Vec, @@ -329,6 +355,8 @@ impl ConfigLayerStack { mcp_ema_cancellation: crate::McpEmaCancellation::default(), applied_config_server: None, model_provider_requirements, + guardian_config: None, + guardian_binding: None, layers, requirements, requirements_toml: Box::new(requirements_toml), @@ -419,6 +447,85 @@ impl ConfigLayerStack { Ok(()) } + /// Replaces only Guardian requirements, managed fallbacks, and source validity. + pub fn apply_guardian_policy(&mut self, snapshot: &crate::GuardianPolicySnapshot) { + copy_guardian_requirements( + &mut self.requirements, + &mut self.requirements_toml, + &snapshot.policy.requirements, + &snapshot.policy.requirements_toml, + ); + let mut fallbacks: Vec<_> = match &self.guardian_config { + Some(fallbacks) => fallbacks + .iter() + .filter(|layer| !is_managed_guardian_layer(&layer.source)) + .cloned() + .collect(), + None => self + .layers_low_to_high() + .filter(|layer| { + !is_user_or_session_layer(&layer.name) + && !is_managed_guardian_layer(&layer.name) + }) + .filter_map(GuardianFallbackLayer::project) + .collect(), + }; + fallbacks.extend_from_slice(&snapshot.managed_config); + self.guardian_config = Some(fallbacks.into()); + self.guardian_binding = snapshot.binding.clone(); + } + + /// Source of the Guardian publication, or the full startup load before its first publication. + pub fn guardian_policy_binding(&self) -> Option<&crate::CloudConfigBundleBinding> { + if self.guardian_config.is_some() { + self.guardian_binding.as_ref() + } else { + self.cloud_config_binding.as_ref() + } + } + + /// Retains Guardian policy when a separate runtime refresh rebuilds the stack. + pub fn retain_guardian_policy_from(&mut self, current: &Self) { + copy_guardian_requirements( + &mut self.requirements, + &mut self.requirements_toml, + ¤t.requirements, + ¤t.requirements_toml, + ); + self.guardian_config = Some(current.guardian_config.clone().unwrap_or_else(|| { + current + .layers_low_to_high() + .filter(|layer| !is_user_or_session_layer(&layer.name)) + .filter_map(GuardianFallbackLayer::project) + .collect() + })); + self.guardian_binding = current.guardian_policy_binding().cloned(); + } + + /// Resolves policy text after merging refreshed and retained layers in precedence order. + pub fn guardian_config(&self) -> std::io::Result { + let local = self + .layers_low_to_high() + .filter(|layer| self.guardian_config.is_none() || is_user_or_session_layer(&layer.name)) + .filter_map(GuardianFallbackLayer::project) + .collect::>(); + let mut layers = self + .guardian_config + .as_deref() + .unwrap_or_default() + .iter() + .chain(&local) + .collect::>(); + layers.sort_by_key(|layer| layer.source.precedence()); + let mut fallback = TomlValue::Table(Default::default()); + for layer in layers { + merge_toml_values(&mut fallback, &layer.value); + } + fallback + .try_into() + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) + } + /// Retains session layers while adopting current MCP, plugin, and feature restrictions. /// Rejected refreshes must not restore an earlier policy on the next user reload. pub fn with_mcp_requirements_from(&self, incoming: &Self) -> Self { @@ -553,6 +660,8 @@ impl ConfigLayerStack { mcp_ema_cancellation: self.mcp_ema_cancellation.clone(), applied_config_server: self.applied_config_server.clone(), model_provider_requirements: self.model_provider_requirements.clone(), + guardian_config: self.guardian_config.clone(), + guardian_binding: self.guardian_binding.clone(), requirements: self.requirements.clone(), requirements_toml: self.requirements_toml.clone(), ignore_user_and_project_exec_policy_rules: self @@ -651,6 +760,8 @@ impl ConfigLayerStack { mcp_ema_cancellation: self.mcp_ema_cancellation.clone(), applied_config_server: self.applied_config_server.clone(), model_provider_requirements: self.model_provider_requirements.clone(), + guardian_config: self.guardian_config.clone(), + guardian_binding: self.guardian_binding.clone(), requirements: self.requirements.clone(), requirements_toml: self.requirements_toml.clone(), ignore_user_and_project_exec_policy_rules: self