From e9df803d238d848de608270e66a6c0d0ca6d439c Mon Sep 17 00:00:00 2001 From: Adam Perry Date: Fri, 10 Jul 2026 06:12:41 +0000 Subject: [PATCH] perf(skills): batch namespace ancestor searches --- codex-rs/core-skills/src/loader/namespace.rs | 231 ++++++++---- .../core-skills/src/loader/namespace_batch.rs | 147 ++++++++ .../core-skills/src/loader/namespace_tests.rs | 336 ++++++++++++++++++ .../core-skills/tests/environment_loader.rs | 2 +- codex-rs/utils/plugins/src/lib.rs | 1 + .../utils/plugins/src/plugin_namespace.rs | 11 +- 6 files changed, 654 insertions(+), 74 deletions(-) create mode 100644 codex-rs/core-skills/src/loader/namespace_batch.rs create mode 100644 codex-rs/core-skills/src/loader/namespace_tests.rs diff --git a/codex-rs/core-skills/src/loader/namespace.rs b/codex-rs/core-skills/src/loader/namespace.rs index fa00b1005d..e8f9398c6e 100644 --- a/codex-rs/core-skills/src/loader/namespace.rs +++ b/codex-rs/core-skills/src/loader/namespace.rs @@ -1,34 +1,148 @@ use codex_exec_server::ExecutorFileSystem; +use codex_exec_server::FindUpErrorPolicy; +use codex_exec_server::FindUpMatchKind; +use codex_exec_server::FindUpOptions; use codex_utils_path_uri::PathUri; +use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS; +use codex_utils_plugins::plugin_namespace_for_manifest_uri; use codex_utils_plugins::plugin_namespace_for_root_uri; use futures::StreamExt; use std::collections::HashMap; use std::collections::HashSet; +use std::sync::Arc; +use std::sync::Mutex; +use tokio::sync::OnceCell; +use tokio::sync::Semaphore; use super::discovery::MAX_CONCURRENT_SKILL_LOADS; +#[path = "namespace_batch.rs"] +mod batch; +use batch::resolve_namespace_lookups; + +const MAX_CONCURRENT_NAMESPACE_LOOKUPS: usize = 8; + +struct NamespaceProbeCache<'a> { + fs: &'a dyn ExecutorFileSystem, + roots: Mutex>>>>, + manifests: Mutex>>>>, + permits: Semaphore, +} + +impl<'a> NamespaceProbeCache<'a> { + fn new(fs: &'a dyn ExecutorFileSystem) -> Self { + Self { + fs, + roots: Mutex::new(HashMap::new()), + manifests: Mutex::new(HashMap::new()), + permits: Semaphore::new(MAX_CONCURRENT_SKILL_LOADS), + } + } + + async fn resolve_root(&self, root: &PathUri) -> Option { + let cell = cached_cell(&self.roots, root); + cell.get_or_init(|| async { + let Ok(_permit) = self.permits.acquire().await else { + return None; + }; + plugin_namespace_for_root_uri(self.fs, root).await + }) + .await + .clone() + } + + async fn resolve_manifest(&self, root: &PathUri, manifest: &PathUri) -> Option { + let cell = cached_cell(&self.manifests, manifest); + cell.get_or_init(|| plugin_namespace_for_manifest_uri(self.fs, root, manifest)) + .await + .clone() + } +} + +fn cached_cell( + cells: &Mutex>>>>, + path: &PathUri, +) -> Arc>> { + let mut cells = cells + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + Arc::clone( + cells + .entry(path.clone()) + .or_insert_with(|| Arc::new(OnceCell::new())), + ) +} + +struct ResolvedNamespaceLookup { + root: PathUri, + namespace: Option, +} + +async fn resolve_namespace_lookup( + cache: &NamespaceProbeCache<'_>, + root: PathUri, + probe_root_alone: bool, +) -> ResolvedNamespaceLookup { + let mut next_ancestor = if probe_root_alone { + if let Some(namespace) = cache.resolve_root(&root).await { + return ResolvedNamespaceLookup { + root, + namespace: Some(namespace), + }; + } + root.parent() + } else { + Some(root.clone()) + }; + let options = namespace_find_up_options(); + + while let Some(search_start) = next_ancestor { + let Ok(outcome) = cache + .fs + .find_up(&search_start, &options, /*sandbox*/ None) + .await + else { + break; + }; + let Some(matched) = outcome.matched else { + break; + }; + if let Some(namespace) = cache + .resolve_manifest(&matched.ancestor, &matched.path) + .await + { + return ResolvedNamespaceLookup { + root, + namespace: Some(namespace), + }; + } + next_ancestor = matched.ancestor.parent(); + } + + ResolvedNamespaceLookup { + root, + namespace: None, + } +} + +fn namespace_find_up_options() -> FindUpOptions { + FindUpOptions { + candidate_relative_paths: DISCOVERABLE_PLUGIN_MANIFEST_PATHS + .iter() + .map(ToString::to_string) + .collect(), + match_kind: FindUpMatchKind::File, + non_not_found_error_policy: FindUpErrorPolicy::Ignore, + } +} + /// Resolves the namespace prefix applied to skill names during one skills scan. -/// -/// A plugin namespace is the plugin name from the nearest valid plugin manifest -/// above a skill path. For example, a skill named `search` beneath a plugin named -/// `sample` is exposed as `sample:search`. -/// -/// Resolving the namespace separately for every `SKILL.md` repeats the same -/// ancestor manifest probes for sibling skills. This resolver resolves relevant -/// roots once per scan, then selects the nearest matching root for each skill. -/// -/// Namespace precedence is: -/// -/// 1. an explicitly provided plugin namespace; -/// 2. the deepest matching canonical symlink root or nested plugin root; -/// 3. the namespace inherited from the scanned skills root. pub(crate) struct SkillNamespaceResolver { inherited_namespace: ResolvedSkillNamespace, nested_namespaces: Vec<(PathUri, ResolvedSkillNamespace)>, } impl SkillNamespaceResolver { - /// Builds a resolver whose explicit plugin-owned namespace overrides discovery. pub(crate) fn with_provided_namespace(namespace: &str) -> Self { Self { inherited_namespace: ResolvedSkillNamespace::Plugin(namespace.to_string()), @@ -43,7 +157,6 @@ impl SkillNamespaceResolver { plugin_roots: HashSet, namespace_roots: HashSet, ) -> Self { - // Only probe plugin roots above loaded skills; unused siblings cannot affect names. let mut skill_ancestors = HashSet::new(); for skill_path in skill_paths { let mut ancestor = skill_path.parent(); @@ -56,8 +169,7 @@ impl SkillNamespaceResolver { .into_iter() .filter(|plugin_root| skill_ancestors.contains(plugin_root)) .collect::>(); - - // The scan root is already the fallback above if nothing else matches, exclude from the search. + let discovered_manifest_roots = plugin_roots.clone(); let namespace_roots = namespace_roots .into_iter() .filter(|namespace_root| namespace_root != root) @@ -68,54 +180,33 @@ impl SkillNamespaceResolver { .filter(|plugin_root| plugin_root != root && !namespace_root_set.contains(plugin_root)) .collect::>(); - let lookup_roots = std::iter::once(root.clone()) + let lookup_requests = std::iter::once(root.clone()) .chain(namespace_roots.iter().cloned()) + .map(|lookup_root| { + let probe_root_alone = discovered_manifest_roots.contains(&lookup_root); + (lookup_root, probe_root_alone) + }) .collect::>(); - let mut pending_lookups = lookup_roots - .iter() - .cloned() - .map(|lookup_root| (lookup_root.clone(), lookup_root)) - .collect::>(); - let mut direct_plugin_roots = plugin_roots.iter().cloned().collect::>(); - let mut namespaces_by_root = HashMap::new(); - let mut namespaces_by_lookup_root = HashMap::new(); - while !pending_lookups.is_empty() { - let probe_roots = pending_lookups - .iter() - .map(|(_, ancestor)| ancestor.clone()) - .chain(direct_plugin_roots.drain()) - .filter(|ancestor| !namespaces_by_root.contains_key(ancestor)) - .collect::>(); - namespaces_by_root.extend( - futures::stream::iter(probe_roots) - .map(|manifest_root| async move { - let namespace = plugin_namespace_for_root_uri(fs, &manifest_root).await; - (manifest_root, namespace) - }) - .buffered(MAX_CONCURRENT_SKILL_LOADS) - .collect::>() - .await, - ); - - let mut next_lookups = Vec::new(); - for (lookup_root, ancestor) in pending_lookups { - match namespaces_by_root.get(&ancestor) { - Some(Some(namespace)) => { - namespaces_by_lookup_root.insert(lookup_root, Some(namespace.clone())); - } - Some(None) => match ancestor.parent() { - Some(parent) => next_lookups.push((lookup_root, parent)), - None => { - namespaces_by_lookup_root.insert(lookup_root, None); - } - }, - None => unreachable!("pending namespace ancestor was not probed"), + let probe_cache = NamespaceProbeCache::new(fs); + let lookup_resolutions = resolve_namespace_lookups(&probe_cache, &lookup_requests); + let plugin_resolutions = futures::stream::iter(plugin_roots.iter().cloned()) + .map(|plugin_root| { + let probe_cache = &probe_cache; + async move { + let namespace = probe_cache.resolve_root(&plugin_root).await; + (plugin_root, namespace) } - } - pending_lookups = next_lookups; - } + }) + .buffer_unordered(MAX_CONCURRENT_SKILL_LOADS) + .collect::>(); + let (lookup_resolutions, plugin_resolutions) = + futures::join!(lookup_resolutions, plugin_resolutions); + let namespaces_by_lookup_root = lookup_resolutions + .into_iter() + .map(|lookup| (lookup.root, lookup.namespace)) + .collect::>(); + let namespaces_by_plugin_root = plugin_resolutions.into_iter().collect::>(); - // Ordinary descendants fall back to the nearest valid manifest at or above the scan root. let inherited_namespace = namespaces_by_lookup_root .get(root) .and_then(Option::as_ref) @@ -131,26 +222,21 @@ impl SkillNamespaceResolver { .unwrap_or(ResolvedSkillNamespace::Plain); (namespace_root, namespace) }); - // Invalid nested manifests are omitted, so the deepest remaining match wins. let plugin_lookups = plugin_roots.into_iter().filter_map(|plugin_root| { - namespaces_by_root + namespaces_by_plugin_root .get(&plugin_root) .and_then(Option::as_ref) .cloned() .map(|namespace| (plugin_root, ResolvedSkillNamespace::Plugin(namespace))) }); - let nested_namespaces = namespace_lookups.chain(plugin_lookups).collect(); - Self { inherited_namespace, - nested_namespaces, + nested_namespaces: namespace_lookups.chain(plugin_lookups).collect(), } } pub(crate) fn for_skill(&self, root: &PathUri, path: &PathUri) -> &ResolvedSkillNamespace { - // Ancestor symlink targets cannot override skills still owned by the scan root. let path_is_under_root = path.starts_with(root); - // The deepest matching path prefix is the nearest applicable namespace. self.nested_namespaces .iter() .filter(|(namespace_root, _)| { @@ -163,12 +249,9 @@ impl SkillNamespaceResolver { } } -/// The completed namespace resolution for a skill root. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum ResolvedSkillNamespace { - /// No plugin namespace applies to matching skills. Plain, - /// Qualify matching skill names with this plugin namespace. Plugin(String), } @@ -180,3 +263,7 @@ impl ResolvedSkillNamespace { } } } + +#[cfg(test)] +#[path = "namespace_tests.rs"] +mod tests; diff --git a/codex-rs/core-skills/src/loader/namespace_batch.rs b/codex-rs/core-skills/src/loader/namespace_batch.rs new file mode 100644 index 0000000000..54733faa10 --- /dev/null +++ b/codex-rs/core-skills/src/loader/namespace_batch.rs @@ -0,0 +1,147 @@ +use codex_exec_server::FS_FIND_UP_BATCH_MAX_REQUESTS; +use codex_exec_server::FindUpRequest; +use codex_utils_path_uri::PathUri; +use futures::StreamExt; + +use super::MAX_CONCURRENT_NAMESPACE_LOOKUPS; +use super::NamespaceProbeCache; +use super::ResolvedNamespaceLookup; +use super::namespace_find_up_options; +use super::resolve_namespace_lookup; + +struct PendingNamespaceLookup { + resolution: ResolvedNamespaceLookup, + next_ancestor: Option, +} + +async fn prepare_namespace_lookup( + cache: &NamespaceProbeCache<'_>, + root: PathUri, + probe_root_alone: bool, +) -> PendingNamespaceLookup { + let mut resolution = ResolvedNamespaceLookup { + root: root.clone(), + namespace: None, + }; + let next_ancestor = if probe_root_alone { + if let Some(namespace) = cache.resolve_root(&root).await { + resolution.namespace = Some(namespace); + None + } else { + root.parent() + } + } else { + Some(root) + }; + PendingNamespaceLookup { + resolution, + next_ancestor, + } +} + +async fn try_resolve_namespace_lookups_batched( + cache: &NamespaceProbeCache<'_>, + lookup_roots: &[(PathUri, bool)], +) -> Option> { + let mut prepared = futures::stream::iter(lookup_roots.iter().cloned().enumerate()) + .map(|(index, (root, probe_root_alone))| async move { + ( + index, + prepare_namespace_lookup(cache, root, probe_root_alone).await, + ) + }) + .buffer_unordered(MAX_CONCURRENT_NAMESPACE_LOOKUPS) + .collect::>() + .await; + prepared.sort_by_key(|(index, _)| *index); + let mut lookups = prepared + .into_iter() + .map(|(_, lookup)| lookup) + .collect::>(); + let options = namespace_find_up_options(); + + loop { + let active = lookups + .iter_mut() + .enumerate() + .filter_map(|(index, lookup)| { + lookup + .next_ancestor + .take() + .map(|search_start| (index, search_start)) + }) + .collect::>(); + if active.is_empty() { + break; + } + + let mut round_results = Vec::with_capacity(active.len()); + for chunk in active.chunks(FS_FIND_UP_BATCH_MAX_REQUESTS) { + let requests = chunk + .iter() + .map(|(_, search_start)| FindUpRequest { + start: search_start.clone(), + options: options.clone(), + }) + .collect::>(); + let results = cache + .fs + .find_up_batch(&requests, /*sandbox*/ None) + .await + .ok()?; + if results.len() != requests.len() { + return None; + } + round_results.extend(results); + } + + let mut matched_manifests = Vec::new(); + for ((lookup_index, _), result) in active.into_iter().zip(round_results) { + let Ok(outcome) = result else { + continue; + }; + if let Some(matched) = outcome.matched { + matched_manifests.push((lookup_index, matched.ancestor, matched.path)); + } + } + let resolved_manifests = futures::stream::iter(matched_manifests) + .map(|(lookup_index, ancestor, manifest)| async move { + let namespace = cache.resolve_manifest(&ancestor, &manifest).await; + (lookup_index, ancestor, namespace) + }) + .buffered(MAX_CONCURRENT_NAMESPACE_LOOKUPS) + .collect::>() + .await; + for (lookup_index, ancestor, namespace) in resolved_manifests { + let lookup = &mut lookups[lookup_index]; + if let Some(namespace) = namespace { + lookup.resolution.namespace = Some(namespace); + } else { + lookup.next_ancestor = ancestor.parent(); + } + } + } + + Some( + lookups + .into_iter() + .map(|lookup| lookup.resolution) + .collect(), + ) +} + +pub(super) async fn resolve_namespace_lookups( + cache: &NamespaceProbeCache<'_>, + lookup_roots: &[(PathUri, bool)], +) -> Vec { + if let Some(resolutions) = try_resolve_namespace_lookups_batched(cache, lookup_roots).await { + return resolutions; + } + futures::stream::iter(lookup_roots.iter().cloned()) + .map(|(root, probe_root_alone)| async move { + resolve_namespace_lookup(cache, root, probe_root_alone).await + }) + .buffered(MAX_CONCURRENT_NAMESPACE_LOOKUPS) + .collect() + .await +} diff --git a/codex-rs/core-skills/src/loader/namespace_tests.rs b/codex-rs/core-skills/src/loader/namespace_tests.rs new file mode 100644 index 0000000000..df1ca92e4c --- /dev/null +++ b/codex-rs/core-skills/src/loader/namespace_tests.rs @@ -0,0 +1,336 @@ +use std::collections::HashSet; +use std::io; +use std::path::Path; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use codex_exec_server::CopyOptions; +use codex_exec_server::CreateDirectoryOptions; +use codex_exec_server::ExecutorFileSystem; +use codex_exec_server::ExecutorFileSystemFuture; +use codex_exec_server::FileMetadata; +use codex_exec_server::FileSystemReadStream; +use codex_exec_server::FileSystemResult; +use codex_exec_server::FileSystemSandboxContext; +use codex_exec_server::FindUpOptions; +use codex_exec_server::FindUpOutcome; +use codex_exec_server::FindUpRequest; +use codex_exec_server::LOCAL_FS; +use codex_exec_server::ReadDirectoryEntry; +use codex_exec_server::RemoveOptions; +use codex_utils_path_uri::PathUri; +use pretty_assertions::assert_eq; + +use super::ResolvedSkillNamespace; +use super::SkillNamespaceResolver; + +#[derive(Clone, Copy)] +enum BatchBehavior { + Delegate, + Error, + MalformedCardinality, +} + +struct RecordingFileSystem { + inner: Arc, + batch_behavior: BatchBehavior, + batch_requests: Mutex>>, + individual_find_up_count: AtomicUsize, + read_paths: Mutex>, +} + +impl RecordingFileSystem { + fn new(batch_behavior: BatchBehavior) -> Self { + Self { + inner: Arc::clone(&LOCAL_FS), + batch_behavior, + batch_requests: Mutex::new(Vec::new()), + individual_find_up_count: AtomicUsize::new(0), + read_paths: Mutex::new(Vec::new()), + } + } + + fn batch_sizes(&self) -> Vec { + self.batch_requests + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .map(Vec::len) + .collect() + } + + fn individual_find_up_count(&self) -> usize { + self.individual_find_up_count.load(Ordering::Acquire) + } + + fn read_count(&self, path: &PathUri) -> usize { + self.read_paths + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .filter(|read_path| *read_path == path) + .count() + } +} + +impl ExecutorFileSystem for RecordingFileSystem { + fn canonicalize<'a>( + &'a self, + path: &'a PathUri, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, PathUri> { + self.inner.canonicalize(path, sandbox) + } + + fn read_file<'a>( + &'a self, + path: &'a PathUri, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec> { + self.read_paths + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(path.clone()); + self.inner.read_file(path, sandbox) + } + + fn read_file_stream<'a>( + &'a self, + path: &'a PathUri, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> { + self.inner.read_file_stream(path, sandbox) + } + + fn write_file<'a>( + &'a self, + path: &'a PathUri, + contents: Vec, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, ()> { + self.inner.write_file(path, contents, sandbox) + } + + fn create_directory<'a>( + &'a self, + path: &'a PathUri, + options: CreateDirectoryOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, ()> { + self.inner.create_directory(path, options, sandbox) + } + + fn get_metadata<'a>( + &'a self, + path: &'a PathUri, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, FileMetadata> { + self.inner.get_metadata(path, sandbox) + } + + fn find_up<'a>( + &'a self, + start: &'a PathUri, + options: &'a FindUpOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, FindUpOutcome> { + self.individual_find_up_count.fetch_add(1, Ordering::AcqRel); + self.inner.find_up(start, options, sandbox) + } + + fn find_up_batch<'a>( + &'a self, + requests: &'a [FindUpRequest], + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + self.batch_requests + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(requests.to_vec()); + Box::pin(async move { + match self.batch_behavior { + BatchBehavior::Delegate => self.inner.find_up_batch(requests, sandbox).await, + BatchBehavior::Error => Err(io::Error::other("batch unavailable")), + BatchBehavior::MalformedCardinality => Ok(Vec::new()), + } + }) + } + + fn read_directory<'a>( + &'a self, + path: &'a PathUri, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec> { + self.inner.read_directory(path, sandbox) + } + + fn remove<'a>( + &'a self, + path: &'a PathUri, + options: RemoveOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, ()> { + self.inner.remove(path, options, sandbox) + } + + fn copy<'a>( + &'a self, + source_path: &'a PathUri, + destination_path: &'a PathUri, + options: CopyOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, ()> { + self.inner + .copy(source_path, destination_path, options, sandbox) + } +} + +#[tokio::test] +async fn all_negative_namespace_lookups_use_one_batch_round() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let root = temp_dir.path().join("skills"); + let namespace_roots = [ + temp_dir.path().join("linked-a"), + temp_dir.path().join("linked-b"), + ]; + for path in std::iter::once(&root).chain(namespace_roots.iter()) { + std::fs::create_dir_all(path).expect("create lookup root"); + } + let root = path_uri(&root); + let skill_path = root.join("sample/SKILL.md").expect("skill URI"); + let namespace_roots = namespace_roots + .iter() + .map(|path| path_uri(path)) + .collect::>(); + let file_system = RecordingFileSystem::new(BatchBehavior::Delegate); + + let resolver = SkillNamespaceResolver::discover( + &file_system, + &root, + std::slice::from_ref(&skill_path), + HashSet::new(), + namespace_roots, + ) + .await; + + assert_eq!(file_system.batch_sizes(), vec![3]); + assert_eq!(file_system.individual_find_up_count(), 0); + assert_eq!( + resolver.for_skill(&root, &skill_path), + &ResolvedSkillNamespace::Plain + ); +} + +#[tokio::test] +async fn invalid_nearest_manifest_retries_only_that_lookup_in_a_second_round() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let outer = temp_dir.path().join("outer"); + let invalid = outer.join("invalid"); + write_manifest(&outer, r#"{"name":"outer"}"#); + write_manifest(&invalid, "not json"); + let root = invalid.join("nested/skills"); + std::fs::create_dir_all(&root).expect("create skills root"); + let root = path_uri(&root); + let skill_path = root.join("sample/SKILL.md").expect("skill URI"); + let file_system = RecordingFileSystem::new(BatchBehavior::Delegate); + + let resolver = SkillNamespaceResolver::discover( + &file_system, + &root, + std::slice::from_ref(&skill_path), + HashSet::new(), + HashSet::new(), + ) + .await; + + assert_eq!(file_system.batch_sizes(), vec![1, 1]); + assert_eq!(file_system.individual_find_up_count(), 0); + assert_eq!( + resolver.for_skill(&root, &skill_path), + &ResolvedSkillNamespace::Plugin("outer".to_string()) + ); +} + +#[tokio::test] +async fn duplicate_manifest_matches_share_manifest_validation() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let outer = temp_dir.path().join("outer"); + write_manifest(&outer, r#"{"name":"outer"}"#); + let root = outer.join("skills"); + let linked_a = outer.join("linked-a"); + let linked_b = outer.join("linked-b"); + for path in [&root, &linked_a, &linked_b] { + std::fs::create_dir_all(path).expect("create lookup root"); + } + let root = path_uri(&root); + let skill_path = root.join("sample/SKILL.md").expect("skill URI"); + let namespace_roots = [path_uri(&linked_a), path_uri(&linked_b)] + .into_iter() + .collect(); + let manifest = path_uri(&outer.join(".codex-plugin/plugin.json")); + let file_system = RecordingFileSystem::new(BatchBehavior::Delegate); + + SkillNamespaceResolver::discover( + &file_system, + &root, + std::slice::from_ref(&skill_path), + HashSet::new(), + namespace_roots, + ) + .await; + + assert_eq!(file_system.batch_sizes(), vec![3]); + assert_eq!(file_system.read_count(&manifest), 1); +} + +#[tokio::test] +async fn batch_error_falls_back_to_individual_lookups() { + assert_batch_failure_falls_back(BatchBehavior::Error).await; +} + +#[tokio::test] +async fn malformed_batch_cardinality_falls_back_to_individual_lookups() { + assert_batch_failure_falls_back(BatchBehavior::MalformedCardinality).await; +} + +async fn assert_batch_failure_falls_back(batch_behavior: BatchBehavior) { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let outer = temp_dir.path().join("outer"); + let invalid = outer.join("invalid"); + write_manifest(&outer, r#"{"name":"outer"}"#); + write_manifest(&invalid, "not json"); + let root = invalid.join("nested/skills"); + std::fs::create_dir_all(&root).expect("create skills root"); + let root = path_uri(&root); + let skill_path = root.join("sample/SKILL.md").expect("skill URI"); + let fallback_file_system = RecordingFileSystem::new(batch_behavior); + + let fallback = SkillNamespaceResolver::discover( + &fallback_file_system, + &root, + std::slice::from_ref(&skill_path), + HashSet::new(), + HashSet::new(), + ) + .await; + + assert_eq!( + fallback.for_skill(&root, &skill_path), + &ResolvedSkillNamespace::Plugin("outer".to_string()) + ); + assert_eq!(fallback_file_system.batch_sizes(), vec![1]); + assert_eq!(fallback_file_system.individual_find_up_count(), 2); +} + +fn write_manifest(root: &Path, contents: &str) { + let manifest = root.join(".codex-plugin/plugin.json"); + std::fs::create_dir_all(manifest.parent().expect("manifest parent")) + .expect("create manifest parent"); + std::fs::write(manifest, contents).expect("write manifest"); +} + +fn path_uri(path: &Path) -> PathUri { + PathUri::from_host_native_path(path).expect("path URI") +} diff --git a/codex-rs/core-skills/tests/environment_loader.rs b/codex-rs/core-skills/tests/environment_loader.rs index ed37fa99a3..0e975c5b71 100644 --- a/codex-rs/core-skills/tests/environment_loader.rs +++ b/codex-rs/core-skills/tests/environment_loader.rs @@ -574,7 +574,7 @@ async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() { PathUri::from_host_native_path(dunce::canonicalize(manifest_path).unwrap()).unwrap(); assert_eq!( calls - .metadata_files + .read_files .iter() .filter(|path| **path == manifest_uri) .count(), diff --git a/codex-rs/utils/plugins/src/lib.rs b/codex-rs/utils/plugins/src/lib.rs index 5cb5905495..b22cc2f51f 100644 --- a/codex-rs/utils/plugins/src/lib.rs +++ b/codex-rs/utils/plugins/src/lib.rs @@ -9,6 +9,7 @@ pub mod plugin_namespace; pub use plugin_namespace::DISCOVERABLE_PLUGIN_MANIFEST_PATHS; pub use plugin_namespace::find_plugin_manifest_path; +pub use plugin_namespace::plugin_namespace_for_manifest_uri; pub use plugin_namespace::plugin_namespace_for_root_uri; pub use plugin_namespace::plugin_namespace_for_skill_path; pub use plugin_namespace::plugin_namespace_for_skill_uri; diff --git a/codex-rs/utils/plugins/src/plugin_namespace.rs b/codex-rs/utils/plugins/src/plugin_namespace.rs index 4604942ffe..cc2dd30515 100644 --- a/codex-rs/utils/plugins/src/plugin_namespace.rs +++ b/codex-rs/utils/plugins/src/plugin_namespace.rs @@ -40,8 +40,17 @@ pub async fn plugin_namespace_for_root_uri( Ok(_) | Err(_) => {} } } + plugin_namespace_for_manifest_uri(fs, plugin_root, &manifest_path?).await +} + +/// Reads the plugin namespace from an already-discovered manifest path. +pub async fn plugin_namespace_for_manifest_uri( + fs: &dyn ExecutorFileSystem, + plugin_root: &PathUri, + manifest_path: &PathUri, +) -> Option { let contents = fs - .read_file_text(&manifest_path?, /*sandbox*/ None) + .read_file_text(manifest_path, /*sandbox*/ None) .await .ok()?; let RawPluginManifestName { name: raw_name } = serde_json::from_str(&contents).ok()?;