diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 6747830b89..a18f5bd0b7 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -361,7 +361,11 @@ impl MessageProcessor { thread_manager .plugins_manager() .set_analytics_events_client(analytics_events_client.clone()); - let skills_watcher = SkillsWatcher::new(thread_manager.skills_manager(), outgoing.clone()); + let skills_watcher = SkillsWatcher::new( + thread_manager.skills_manager(), + outgoing.clone(), + config.skill_watch_ignore_path_components.clone(), + ); let pending_thread_unloads = Arc::new(Mutex::new(HashSet::new())); let thread_watch_manager = diff --git a/codex-rs/app-server/src/skills_watcher.rs b/codex-rs/app-server/src/skills_watcher.rs index 57edb89c7f..f92e0f2740 100644 --- a/codex-rs/app-server/src/skills_watcher.rs +++ b/codex-rs/app-server/src/skills_watcher.rs @@ -1,3 +1,7 @@ +use std::collections::BTreeSet; +use std::ffi::OsString; +use std::path::Component; +use std::path::Path; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; @@ -26,6 +30,12 @@ const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10); #[cfg(test)] const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50); +fn has_ignored_component(path: &Path, ignored_components: &BTreeSet) -> bool { + path.components().any(|component| { + matches!(component, Component::Normal(name) if ignored_components.contains(name)) + }) +} + pub(crate) struct SkillsWatcher { subscriber: FileWatcherSubscriber, runtime_extra_roots_registration: Mutex, @@ -37,7 +47,13 @@ impl SkillsWatcher { pub(crate) fn new( skills_manager: Arc, outgoing: Arc, + configured_ignore_path_components: BTreeSet, ) -> Arc { + let mut ignored_path_components = configured_ignore_path_components + .into_iter() + .map(OsString::from) + .collect::>(); + ignored_path_components.insert(OsString::from(".git")); let file_watcher = match FileWatcher::new() { Ok(file_watcher) => Arc::new(file_watcher), Err(err) => { @@ -48,7 +64,13 @@ impl SkillsWatcher { let (subscriber, rx) = file_watcher.add_subscriber(); let shutdown_token = CancellationToken::new(); let shutdown_drop_guard = shutdown_token.clone().drop_guard(); - Self::spawn_event_loop(rx, skills_manager, outgoing, shutdown_token.child_token()); + Self::spawn_event_loop( + rx, + skills_manager, + outgoing, + ignored_path_components, + shutdown_token.child_token(), + ); Arc::new(Self { subscriber, runtime_extra_roots_registration: Mutex::new(WatchRegistration::default()), @@ -126,6 +148,7 @@ impl SkillsWatcher { rx: Receiver, skills_manager: Arc, outgoing: Arc, + ignored_path_components: BTreeSet, shutdown_token: CancellationToken, ) { let mut rx = ThrottledWatchReceiver::new(rx, WATCHER_THROTTLE_INTERVAL); @@ -137,7 +160,9 @@ impl SkillsWatcher { loop { let event = tokio::select! { _ = shutdown_token.cancelled() => break, - event = rx.recv() => event, + event = rx.recv_filtered(|path| { + !has_ignored_component(path, &ignored_path_components) + }) => event, }; if event.is_none() { break; @@ -152,3 +177,7 @@ impl SkillsWatcher { }); } } + +#[cfg(test)] +#[path = "skills_watcher_tests.rs"] +mod tests; diff --git a/codex-rs/app-server/src/skills_watcher_tests.rs b/codex-rs/app-server/src/skills_watcher_tests.rs new file mode 100644 index 0000000000..835b7c823a --- /dev/null +++ b/codex-rs/app-server/src/skills_watcher_tests.rs @@ -0,0 +1,59 @@ +use std::collections::BTreeSet; +use std::ffi::OsString; +use std::path::Path; + +use pretty_assertions::assert_eq; + +use super::has_ignored_component; + +#[test] +fn detects_configured_ignored_path_components() { + let ignored_components = + BTreeSet::from([OsString::from(".git"), OsString::from(".watch-metadata")]); + let actual = [ + has_ignored_component( + Path::new(".agents/skills/.git/FETCH_HEAD"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/demo/.git/config"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/.watch-metadata/state"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/demo/.watch-metadata/cache"), + &ignored_components, + ), + ]; + + assert_eq!(actual, [true, true, true, true]); +} + +#[test] +fn preserves_similarly_named_skill_paths() { + let ignored_components = + BTreeSet::from([OsString::from(".git"), OsString::from(".watch-metadata")]); + let actual = [ + has_ignored_component( + Path::new(".agents/skills/demo/SKILL.md"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/demo/.gitignore"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/demo/skill.git.md"), + &ignored_components, + ), + has_ignored_component( + Path::new(".agents/skills/demo/.watch-metadata-cache/script.py"), + &ignored_components, + ), + ]; + + assert_eq!(actual, [false, false, false, false]); +} diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index ed26757715..95cb3b07ea 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -136,6 +136,7 @@ pub use requirements_layers::compose_requirements; pub use skills_config::BundledSkillsConfig; pub use skills_config::SkillConfig; pub use skills_config::SkillsConfig; +pub use skills_config::SkillsWatchConfig; pub use state::ConfigLayerEntry; pub use state::ConfigLayerStack; pub use state::ConfigLayerStackOrdering; diff --git a/codex-rs/config/src/skills_config.rs b/codex-rs/config/src/skills_config.rs index 948b9060c4..a67cd0f008 100644 --- a/codex-rs/config/src/skills_config.rs +++ b/codex-rs/config/src/skills_config.rs @@ -3,7 +3,10 @@ use codex_utils_absolute_path::AbsolutePathBuf; use schemars::JsonSchema; use serde::Deserialize; +use serde::Deserializer; use serde::Serialize; +use serde::de::Error as _; +use std::collections::BTreeSet; const fn default_enabled() -> bool { true @@ -27,6 +30,10 @@ pub struct SkillsConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub bundled: Option, + /// Filesystem watch settings used for skills cache invalidation. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub watch: Option, + /// Whether turns receive the automatic skills instructions block. #[serde(default, skip_serializing_if = "Option::is_none")] pub include_instructions: Option, @@ -35,6 +42,38 @@ pub struct SkillsConfig { pub config: Vec, } +/// Filesystem watch settings for skill roots. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SkillsWatchConfig { + /// Exact path components whose filesystem events should be ignored. + #[serde( + default, + deserialize_with = "deserialize_path_components", + skip_serializing_if = "BTreeSet::is_empty" + )] + pub ignore_path_components: BTreeSet, +} + +fn deserialize_path_components<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let components = BTreeSet::::deserialize(deserializer)?; + for component in &components { + if component.is_empty() + || component == "." + || component == ".." + || component.contains(['\0', '/', '\\']) + { + return Err(D::Error::custom(format!( + "skill watch ignore path component must be a single non-empty path component: {component:?}" + ))); + } + } + Ok(components) +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct BundledSkillsConfig { diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 7cf8ac66a4..02c573bf0a 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -801,6 +801,7 @@ pub struct Notice { pub use crate::skills_config::BundledSkillsConfig; pub use crate::skills_config::SkillConfig; pub use crate::skills_config::SkillsConfig; +pub use crate::skills_config::SkillsWatchConfig; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 068f482c7a..c9a71acb90 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2689,6 +2689,29 @@ "include_instructions": { "description": "Whether turns receive the automatic skills instructions block.", "type": "boolean" + }, + "watch": { + "allOf": [ + { + "$ref": "#/definitions/SkillsWatchConfig" + } + ], + "description": "Filesystem watch settings used for skills cache invalidation." + } + }, + "type": "object" + }, + "SkillsWatchConfig": { + "additionalProperties": false, + "description": "Filesystem watch settings for skill roots.", + "properties": { + "ignore_path_components": { + "description": "Exact path components whose filesystem events should be ignored.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": true } }, "type": "object" @@ -5268,4 +5291,4 @@ }, "title": "ConfigToml", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index f422591d89..1b4c39bcc5 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -325,12 +325,92 @@ enabled = false cfg.skills, Some(SkillsConfig { bundled: Some(BundledSkillsConfig { enabled: false }), + watch: None, include_instructions: Some(false), config: Vec::new(), }) ); } +#[test] +fn parses_skills_watch_ignore_path_components() { + let cfg: ConfigToml = toml::from_str( + r#" +[skills.watch] +ignore_path_components = [".watch-metadata", ".cache", ".watch-metadata"] +"#, + ) + .expect("TOML deserialization should succeed"); + + assert_eq!( + cfg.skills + .expect("skills config") + .watch + .expect("skills watch config") + .ignore_path_components, + BTreeSet::from([".cache".to_string(), ".watch-metadata".to_string()]) + ); +} + +#[test] +fn rejects_invalid_skills_watch_ignore_path_components() { + for component in ["", ".", "..", "directory/name", r"directory\name"] { + let input = format!( + r#" +[skills.watch] +ignore_path_components = [{component:?}] +"# + ); + + let error = toml::from_str::(&input) + .expect_err("invalid path component should be rejected"); + assert!( + error + .to_string() + .contains("must be a single non-empty path component"), + "unexpected error for {component:?}: {error}" + ); + } +} + +#[test] +fn rejects_nul_skills_watch_ignore_path_component() { + let error = serde_json::from_value::( + serde_json::json!({ "ignore_path_components": ["\0"] }), + ) + .expect_err("NUL path component should be rejected"); + + assert!( + error + .to_string() + .contains("must be a single non-empty path component"), + "unexpected error: {error}" + ); +} + +#[tokio::test] +async fn loads_skills_watch_ignore_path_components_into_effective_config() -> std::io::Result<()> { + let cfg: ConfigToml = toml::from_str( + r#" +[skills.watch] +ignore_path_components = [".watch-metadata", ".cache"] +"#, + ) + .expect("TOML deserialization should succeed"); + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + tempdir()?.abs(), + ) + .await?; + + assert_eq!( + config.skill_watch_ignore_path_components, + BTreeSet::from([".cache".to_string(), ".watch-metadata".to_string()]) + ); + Ok(()) +} + #[test] fn tools_web_search_true_deserializes_to_none() { let cfg: ConfigToml = toml::from_str( diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index f292891c43..0d735bffcb 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -112,6 +112,7 @@ use rmcp::model::UrlElicitationCapability; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::HashSet; use std::io::ErrorKind; @@ -677,6 +678,9 @@ pub struct Config { /// Whether to inject the `` developer block. pub include_skill_instructions: bool, + /// Path components whose filesystem events do not invalidate the skills cache. + pub skill_watch_ignore_path_components: BTreeSet, + /// Whether to inject the `` user block. pub include_environment_context: bool, @@ -3253,6 +3257,12 @@ impl Config { .as_ref() .and_then(|skills| skills.include_instructions) .unwrap_or(true); + let skill_watch_ignore_path_components = cfg + .skills + .as_ref() + .and_then(|skills| skills.watch.as_ref()) + .map(|watch| watch.ignore_path_components.clone()) + .unwrap_or_default(); let include_environment_context = cfg.include_environment_context.unwrap_or(true); let guardian_policy_config = guardian_policy_config_from_requirements(config_layer_stack.requirements_toml()) @@ -3459,6 +3469,7 @@ impl Config { include_apps_instructions, include_collaboration_mode_instructions, include_skill_instructions, + skill_watch_ignore_path_components, include_environment_context, // The config.toml omits "_mode" because it's a config file. However, "_mode" // is important in code to differentiate the mode from the store implementation. diff --git a/codex-rs/file-watcher/src/file_watcher_tests.rs b/codex-rs/file-watcher/src/file_watcher_tests.rs index 8bd7858c21..b04a8c95db 100644 --- a/codex-rs/file-watcher/src/file_watcher_tests.rs +++ b/codex-rs/file-watcher/src/file_watcher_tests.rs @@ -86,6 +86,44 @@ async fn throttled_receiver_flushes_pending_on_shutdown() { assert_eq!(closed, None); } +#[tokio::test] +async fn throttled_receiver_filters_paths_before_emitting() { + let (tx, rx) = watch_channel(); + let mut throttled = ThrottledWatchReceiver::new(rx, TEST_THROTTLE_INTERVAL); + + tx.add_changed_paths(&[path("ignored"), path("kept")]).await; + drop(tx); + + let event = timeout( + Duration::from_secs(1), + throttled.recv_filtered(|path| path != Path::new("ignored")), + ) + .await + .expect("filtered emit timeout"); + assert_eq!( + event, + Some(FileWatcherEvent { + paths: vec![path("kept")], + }) + ); + assert_eq!(throttled.next_allowed.is_some(), true); +} + +#[tokio::test] +async fn throttled_receiver_does_not_throttle_fully_filtered_batch() { + let (tx, rx) = watch_channel(); + let mut throttled = ThrottledWatchReceiver::new(rx, TEST_THROTTLE_INTERVAL); + + tx.add_changed_paths(&[path("ignored")]).await; + drop(tx); + + let event = timeout(Duration::from_secs(1), throttled.recv_filtered(|_| false)) + .await + .expect("filtered close timeout"); + assert_eq!(event, None); + assert_eq!(throttled.next_allowed, None); +} + #[tokio::test] async fn debounced_receiver_coalesces_each_event_batch() { let (tx, rx) = watch_channel(); diff --git a/codex-rs/file-watcher/src/lib.rs b/codex-rs/file-watcher/src/lib.rs index a0b1a42401..798af3d1d6 100644 --- a/codex-rs/file-watcher/src/lib.rs +++ b/codex-rs/file-watcher/src/lib.rs @@ -241,15 +241,29 @@ impl ThrottledWatchReceiver { /// Receives the next event, enforcing the configured minimum delay after /// the previous emission. pub async fn recv(&mut self) -> Option { - if let Some(next_allowed) = self.next_allowed { - sleep_until(next_allowed).await; - } + self.recv_filtered(|_| true).await + } - let event = self.rx.recv().await; - if event.is_some() { + /// Returns the next event with at least one path accepted by `keep_path`. + /// + /// Fully filtered events do not advance the throttle window. + pub async fn recv_filtered( + &mut self, + mut keep_path: impl FnMut(&Path) -> bool, + ) -> Option { + loop { + if let Some(next_allowed) = self.next_allowed { + sleep_until(next_allowed).await; + } + + let mut event = self.rx.recv().await?; + event.paths.retain(|path| keep_path(path.as_path())); + if event.paths.is_empty() { + continue; + } self.next_allowed = Some(Instant::now() + self.interval); + return Some(event); } - event } } diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 608c9a90a1..77ee3feb7f 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::collections::HashMap; use std::io::IsTerminal; use std::io::Read; @@ -196,6 +197,7 @@ fn new_config(model: Option, arg0_paths: Arg0DispatchPaths) -> anyhow::R include_apps_instructions: false, include_collaboration_mode_instructions: false, include_skill_instructions: false, + skill_watch_ignore_path_components: BTreeSet::new(), include_environment_context: false, compact_prompt: None, notify: None,