mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add configurable skill watch path filters
This commit is contained in:
@@ -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 =
|
||||
|
||||
@@ -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<OsString>) -> 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<WatchRegistration>,
|
||||
@@ -37,7 +47,13 @@ impl SkillsWatcher {
|
||||
pub(crate) fn new(
|
||||
skills_manager: Arc<SkillsManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
configured_ignore_path_components: BTreeSet<String>,
|
||||
) -> Arc<Self> {
|
||||
let mut ignored_path_components = configured_ignore_path_components
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect::<BTreeSet<_>>();
|
||||
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<SkillsManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
ignored_path_components: BTreeSet<OsString>,
|
||||
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;
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<BundledSkillsConfig>,
|
||||
|
||||
/// Filesystem watch settings used for skills cache invalidation.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub watch: Option<SkillsWatchConfig>,
|
||||
|
||||
/// Whether turns receive the automatic skills instructions block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub include_instructions: Option<bool>,
|
||||
@@ -35,6 +42,38 @@ pub struct SkillsConfig {
|
||||
pub config: Vec<SkillConfig>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
fn deserialize_path_components<'de, D>(deserializer: D) -> Result<BTreeSet<String>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let components = BTreeSet::<String>::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 {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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::<ConfigToml>(&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::<codex_config::types::SkillsWatchConfig>(
|
||||
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(
|
||||
|
||||
@@ -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 `<skills_instructions>` 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<String>,
|
||||
|
||||
/// Whether to inject the `<environment_context>` 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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<FileWatcherEvent> {
|
||||
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<FileWatcherEvent> {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String>, 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,
|
||||
|
||||
Reference in New Issue
Block a user