1use std::collections::{HashMap, HashSet};
49use std::sync::Arc;
50
51use arc_swap::ArcSwap;
52use globset::{Glob, GlobSet, GlobSetBuilder};
53use tracing::warn;
54
55use crate::audit::{AuditEntry, AuditLogger, AuditResult, chrono_now};
56use crate::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput};
57use crate::registry::ToolDef;
58use zeph_config::{CapabilityScopesConfig, PatternStrictness};
59
60#[non_exhaustive]
63#[derive(Debug, thiserror::Error)]
65pub enum ScopeError {
66 #[error("scope '{scope}': pattern '{pattern}' matched zero registered tools (dead pattern)")]
68 DeadPattern { scope: String, pattern: String },
69
70 #[error(
72 "scope '{scope}': pattern '{pattern}' matches the entire registry; use default_scope=\"general\" to opt in"
73 )]
74 AccidentallyFull { scope: String, pattern: String },
75
76 #[error("tool id '{id}' has no namespace prefix (expected '<namespace>:<id>')")]
78 UnqualifiedId { id: String },
79
80 #[error("scope '{scope}': invalid glob pattern '{pattern}': {source}")]
82 InvalidPattern {
83 scope: String,
84 pattern: String,
85 #[source]
86 source: globset::Error,
87 },
88}
89
90#[derive(Debug)]
92pub struct ScopeWarning {
93 pub scope: String,
95 pub pattern: String,
97}
98
99#[derive(Debug, Clone)]
106pub struct ToolScope {
107 pub task_type: Option<String>,
109 admitted: HashSet<String>,
111 is_full: bool,
113 patterns: Vec<String>,
115}
116
117impl ToolScope {
118 #[must_use]
130 pub fn full() -> Self {
131 Self {
132 task_type: None,
133 admitted: HashSet::new(),
134 is_full: true,
135 patterns: vec!["*".to_owned()],
136 }
137 }
138
139 #[must_use]
157 pub fn empty() -> Self {
158 Self {
159 task_type: None,
160 admitted: HashSet::new(),
161 is_full: false,
162 patterns: Vec::new(),
163 }
164 }
165
166 pub fn try_compile<S: std::hash::BuildHasher>(
174 task_type: impl Into<String>,
175 patterns: &[String],
176 registry_ids: &HashSet<String, S>,
177 strictness: PatternStrictness,
178 is_general_scope: bool,
179 ) -> Result<(Self, Vec<ScopeWarning>), ScopeError> {
180 let task_type_str = task_type.into();
181 let mut admitted = HashSet::new();
182 let mut warnings = Vec::new();
183
184 for pattern in patterns {
185 let glob = Glob::new(pattern).map_err(|e| ScopeError::InvalidPattern {
187 scope: task_type_str.clone(),
188 pattern: pattern.clone(),
189 source: e,
190 })?;
191
192 let mut builder = GlobSetBuilder::new();
193 builder.add(glob);
194 let glob_set: GlobSet = builder.build().map_err(|e| ScopeError::InvalidPattern {
195 scope: task_type_str.clone(),
196 pattern: pattern.clone(),
197 source: e,
198 })?;
199
200 let matched: HashSet<String> = registry_ids
201 .iter()
202 .filter(|id| glob_set.is_match(id.as_str()))
203 .cloned()
204 .collect();
205
206 if !is_general_scope && matched.len() == registry_ids.len() && !registry_ids.is_empty()
208 {
209 return Err(ScopeError::AccidentallyFull {
210 scope: task_type_str,
211 pattern: pattern.clone(),
212 });
213 }
214
215 if matched.is_empty() {
216 let is_strict = is_strict_pattern(pattern, strictness);
217 if is_strict {
218 return Err(ScopeError::DeadPattern {
219 scope: task_type_str,
220 pattern: pattern.clone(),
221 });
222 }
223 warnings.push(ScopeWarning {
224 scope: task_type_str.clone(),
225 pattern: pattern.clone(),
226 });
227 }
228
229 admitted.extend(matched);
230 }
231
232 Ok((
233 Self {
234 task_type: Some(task_type_str),
235 admitted,
236 is_full: false,
237 patterns: patterns.to_vec(),
238 },
239 warnings,
240 ))
241 }
242
243 #[must_use]
254 pub fn admits(&self, qualified_tool_id: &str) -> bool {
255 self.is_full || self.admitted.contains(qualified_tool_id)
256 }
257
258 #[must_use]
262 pub fn admitted_ids(&self) -> Vec<&str> {
263 self.admitted.iter().map(String::as_str).collect()
264 }
265
266 #[must_use]
268 pub fn patterns(&self) -> &[String] {
269 &self.patterns
270 }
271
272 #[must_use]
277 pub fn re_resolve<S: std::hash::BuildHasher>(&self, registry_ids: &HashSet<String, S>) -> Self {
278 let task_type_str = self
279 .task_type
280 .clone()
281 .unwrap_or_else(|| "<unknown>".to_owned());
282 let mut admitted = HashSet::new();
283 for pattern in &self.patterns {
284 let Ok(glob) = Glob::new(pattern) else {
285 warn!(scope = %task_type_str, pattern, "re-resolve: invalid glob, skipping");
286 continue;
287 };
288 let mut builder = GlobSetBuilder::new();
289 builder.add(glob);
290 let Ok(glob_set) = builder.build() else {
291 continue;
292 };
293 let matched: HashSet<String> = registry_ids
294 .iter()
295 .filter(|id| glob_set.is_match(id.as_str()))
296 .cloned()
297 .collect();
298 admitted.extend(matched);
299 }
300 Self {
301 task_type: self.task_type.clone(),
302 admitted,
303 is_full: false,
304 patterns: self.patterns.clone(),
305 }
306 }
307}
308
309fn is_strict_pattern(pattern: &str, strictness: PatternStrictness) -> bool {
311 match strictness {
312 PatternStrictness::Strict => true,
313 PatternStrictness::ProvisionalForDynamicNamespaces => {
314 pattern.starts_with("builtin:") || pattern.starts_with("skill:")
316 }
317 _ => false,
318 }
319}
320
321pub struct ScopedToolExecutor<E: ToolExecutor> {
349 inner: E,
350 scope: ArcSwap<ToolScope>,
352 scopes: HashMap<String, Arc<ToolScope>>,
354 scope_at_definition: parking_lot::Mutex<Option<String>>,
356 signal_queue: Option<crate::policy_gate::RiskSignalQueue>,
358 audit: Option<Arc<AuditLogger>>,
360}
361
362impl<E: ToolExecutor> ScopedToolExecutor<E> {
363 #[must_use]
378 pub fn new(inner: E, initial_scope: ToolScope) -> Self {
379 Self {
380 inner,
381 scope: ArcSwap::from_pointee(initial_scope),
382 scopes: HashMap::new(),
383 scope_at_definition: parking_lot::Mutex::new(None),
384 signal_queue: None,
385 audit: None,
386 }
387 }
388
389 #[must_use]
391 pub fn with_audit(mut self, audit: Arc<AuditLogger>) -> Self {
392 self.audit = Some(audit);
393 self
394 }
395
396 #[must_use]
398 pub fn with_signal_queue(mut self, queue: crate::policy_gate::RiskSignalQueue) -> Self {
399 self.signal_queue = Some(queue);
400 self
401 }
402
403 pub fn register_scope(&mut self, name: impl Into<String>, scope: ToolScope) {
405 self.scopes.insert(name.into(), Arc::new(scope));
406 }
407
408 pub fn set_scope_for_task(&self, task_type: &str) -> bool {
410 if let Some(scope) = self.scopes.get(task_type) {
411 self.scope.store(Arc::clone(scope));
412 true
413 } else {
414 false
415 }
416 }
417
418 pub fn set_scope(&self, scope: ToolScope) {
420 self.scope.store(Arc::new(scope));
421 }
422
423 #[must_use]
442 pub fn scope_for_task(&self, task_type: &str) -> Option<Vec<String>> {
443 self.scopes.get(task_type).map(|s| {
444 if s.is_full {
445 vec!["*".to_owned()]
446 } else {
447 s.admitted_ids().iter().map(|s| (*s).to_owned()).collect()
448 }
449 })
450 }
451
452 #[must_use]
454 pub fn scope_at_definition_name(&self) -> Option<String> {
455 self.scope_at_definition.lock().clone()
456 }
457
458 #[must_use]
460 pub fn active_scope_name(&self) -> Option<String> {
461 self.scope.load().task_type.clone()
462 }
463}
464
465impl<E: ToolExecutor> ToolExecutor for ScopedToolExecutor<E> {
466 async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
468 self.inner.execute(response).await
469 }
470
471 async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
472 self.inner.execute_confirmed(response).await
473 }
474
475 fn tool_definitions(&self) -> Vec<ToolDef> {
479 let scope = self.scope.load();
480 self.scope_at_definition.lock().clone_from(&scope.task_type);
481 self.inner
482 .tool_definitions()
483 .into_iter()
484 .filter(|d| {
485 let id = d.id.as_ref();
486 let scope_id: String;
487 let qualified = if id.contains(':') {
488 id
489 } else {
490 scope_id = format!("builtin:{id}");
491 scope_id.as_str()
492 };
493 scope.admits(qualified)
494 })
495 .collect()
496 }
497
498 async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
503 let scope = self.scope.load();
504 let tool_id = call.tool_id.as_str();
505 let qualified_id: String;
509 let scope_id = if tool_id.contains(':') {
510 tool_id
511 } else {
512 qualified_id = format!("builtin:{tool_id}");
513 qualified_id.as_str()
514 };
515
516 if !scope.admits(scope_id) {
517 let scope_name = scope.task_type.clone();
518 let scope_def = self.scope_at_definition.lock().clone();
519 tracing::debug!(
520 tool_id,
521 scope = ?scope_name,
522 "ScopedToolExecutor: out-of-scope rejection"
523 );
524 if let Some(ref q) = self.signal_queue {
526 q.lock().push(3);
527 }
528 if let Some(ref audit) = self.audit {
530 let entry = AuditEntry {
531 timestamp: chrono_now(),
532 tool: call.tool_id.clone(),
533 command: String::new(),
534 result: AuditResult::Blocked {
535 reason: "out_of_scope".to_owned(),
536 },
537 duration_ms: 0,
538 error_category: Some("out_of_scope".to_owned()),
539 error_domain: Some("security".to_owned()),
540 error_phase: None,
541 claim_source: None,
542 mcp_server_id: None,
543 injection_flagged: false,
544 embedding_anomalous: false,
545 cross_boundary_mcp_to_acp: false,
546 adversarial_policy_decision: None,
547 exit_code: None,
548 truncated: false,
549 caller_id: call.caller_id.clone(),
550 skill_name: call.skill_name.clone(),
551 policy_match: None,
552 correlation_id: None,
553 vigil_risk: None,
554 execution_env: None,
555 resolved_cwd: None,
556 scope_at_definition: scope_def,
557 scope_at_dispatch: scope_name,
558 };
559 audit.log(&entry).await;
560 }
561 return Err(ToolError::OutOfScope {
562 tool_id: tool_id.to_owned(),
563 task_type: scope.task_type.clone(),
564 });
565 }
566
567 self.inner.execute_tool_call(call).await
568 }
569
570 async fn execute_tool_call_confirmed(
571 &self,
572 call: &ToolCall,
573 ) -> Result<Option<ToolOutput>, ToolError> {
574 let scope = self.scope.load();
575 let tool_id = call.tool_id.as_str();
576 let qualified_id: String;
577 let scope_id = if tool_id.contains(':') {
578 tool_id
579 } else {
580 qualified_id = format!("builtin:{tool_id}");
581 qualified_id.as_str()
582 };
583 if !scope.admits(scope_id) {
584 let scope_name = scope.task_type.clone();
585 let scope_def = self.scope_at_definition.lock().clone();
586 if let Some(ref q) = self.signal_queue {
587 q.lock().push(3);
588 }
589 if let Some(ref audit) = self.audit {
590 let entry = AuditEntry {
591 timestamp: chrono_now(),
592 tool: call.tool_id.clone(),
593 command: String::new(),
594 result: AuditResult::Blocked {
595 reason: "out_of_scope".to_owned(),
596 },
597 duration_ms: 0,
598 error_category: Some("out_of_scope".to_owned()),
599 error_domain: Some("security".to_owned()),
600 error_phase: None,
601 claim_source: None,
602 mcp_server_id: None,
603 injection_flagged: false,
604 embedding_anomalous: false,
605 cross_boundary_mcp_to_acp: false,
606 adversarial_policy_decision: None,
607 exit_code: None,
608 truncated: false,
609 caller_id: call.caller_id.clone(),
610 skill_name: call.skill_name.clone(),
611 policy_match: None,
612 correlation_id: None,
613 vigil_risk: None,
614 execution_env: None,
615 resolved_cwd: None,
616 scope_at_definition: scope_def,
617 scope_at_dispatch: scope_name,
618 };
619 audit.log(&entry).await;
620 }
621 return Err(ToolError::OutOfScope {
622 tool_id: tool_id.to_owned(),
623 task_type: scope.task_type.clone(),
624 });
625 }
626 self.inner.execute_tool_call_confirmed(call).await
627 }
628
629 fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
630 self.inner.set_skill_env(env);
631 }
632
633 fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
634 self.inner.set_effective_trust(level);
635 }
636
637 fn is_tool_retryable(&self, tool_id: &str) -> bool {
638 self.inner.is_tool_retryable(tool_id)
639 }
640
641 fn is_tool_speculatable(&self, tool_id: &str) -> bool {
642 self.inner.is_tool_speculatable(tool_id)
643 }
644
645 fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
646 self.inner.checkpoint_undo(n)
647 }
648
649 fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
650 self.inner.checkpoint_redo()
651 }
652
653 fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
654 self.inner.checkpoint_list()
655 }
656
657 fn requires_confirmation(&self, call: &ToolCall) -> bool {
658 self.inner.requires_confirmation(call)
659 }
660}
661
662pub fn build_scoped_executor<E: ToolExecutor, S: std::hash::BuildHasher>(
691 inner: E,
692 cfg: &CapabilityScopesConfig,
693 registry_ids: &HashSet<String, S>,
694) -> Result<ScopedToolExecutor<E>, ScopeError> {
695 let default_scope_name = &cfg.default_scope;
696 let strictness = cfg.pattern_strictness;
697
698 let initial_scope = ToolScope::full();
700 let mut executor = ScopedToolExecutor::new(inner, initial_scope);
701
702 for (task_type, scope_cfg) in &cfg.scopes {
703 let is_general = task_type == default_scope_name;
704 let (scope, warnings) = ToolScope::try_compile(
705 task_type.clone(),
706 &scope_cfg.patterns,
707 registry_ids,
708 strictness,
709 is_general,
710 )?;
711 for w in &warnings {
712 warn!(
713 scope = %w.scope,
714 pattern = %w.pattern,
715 "capability scope: provisional zero-match pattern (will re-resolve on dynamic registration)"
716 );
717 }
718 executor.register_scope(task_type.clone(), scope);
719 }
720
721 if cfg.scopes.contains_key(default_scope_name.as_str()) {
723 executor.set_scope_for_task(default_scope_name);
724 }
725
726 Ok(executor)
727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732 use crate::executor::ToolCall;
733 use crate::registry::{InvocationHint, ToolDef};
734 use std::assert_matches;
735 use zeph_common::ToolName;
736 use zeph_config::{CapabilityScopesConfig, PatternStrictness, ScopeConfig};
737
738 fn make_registry(ids: &[&str]) -> HashSet<String> {
739 ids.iter().map(|s| (*s).to_owned()).collect()
740 }
741
742 struct NullExecutor {
743 defs: Vec<ToolDef>,
744 }
745
746 impl ToolExecutor for NullExecutor {
747 async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
748 Ok(None)
749 }
750
751 fn tool_definitions(&self) -> Vec<ToolDef> {
752 self.defs.clone()
753 }
754
755 async fn execute_tool_call(
756 &self,
757 call: &ToolCall,
758 ) -> Result<Option<ToolOutput>, ToolError> {
759 Ok(Some(ToolOutput {
760 tool_name: call.tool_id.clone(),
761 summary: "ok".to_owned(),
762 blocks_executed: 1,
763 filter_stats: None,
764 diff: None,
765 streamed: false,
766 terminal_id: None,
767 locations: None,
768 raw_response: None,
769 claim_source: None,
770 ..Default::default()
771 }))
772 }
773
774 crate::tool_executor_no_inner_defaults!();
775 }
776
777 struct CheckpointingExecutor;
778
779 impl ToolExecutor for CheckpointingExecutor {
780 async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
781 Ok(None)
782 }
783 fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
784 crate::executor::CheckpointActionResult {
785 supported: true,
786 message: "stub".into(),
787 reverted_commands: n,
788 ..Default::default()
789 }
790 }
791 fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
792 crate::executor::CheckpointActionResult {
793 supported: true,
794 message: "stub".into(),
795 ..Default::default()
796 }
797 }
798 fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
799 crate::executor::CheckpointListResult {
800 supported: true,
801 ..Default::default()
802 }
803 }
804 fn requires_confirmation(&self, _call: &ToolCall) -> bool {
805 true
806 }
807 async fn execute_tool_call_confirmed(
808 &self,
809 call: &ToolCall,
810 ) -> Result<Option<ToolOutput>, ToolError> {
811 self.execute_tool_call(call).await
812 }
813 fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
814 false
815 }
816 }
817
818 fn null_def(id: &str) -> ToolDef {
819 ToolDef {
820 id: id.to_owned().into(),
821 description: "test tool".into(),
822 schema: schemars::schema_for!(String),
823 invocation: InvocationHint::ToolCall,
824 output_schema: None,
825 server_id: None,
826 }
827 }
828
829 fn make_call(tool_id: &str) -> ToolCall {
830 ToolCall {
831 tool_id: ToolName::new(tool_id),
832 params: serde_json::Map::new(),
833 caller_id: None,
834 context: None,
835
836 tool_call_id: String::new(),
837 skill_name: None,
838 }
839 }
840
841 #[test]
842 fn full_scope_admits_everything() {
843 let scope = ToolScope::full();
844 assert!(scope.admits("builtin:shell"));
845 assert!(scope.admits("mcp:server/tool"));
846 assert!(scope.admits("builtin:read"));
847 }
848
849 #[test]
850 fn compiled_scope_admits_only_matched() {
851 let registry = make_registry(&["builtin:shell", "builtin:read", "builtin:write"]);
852 let patterns = vec!["builtin:read".to_owned()];
853 let (scope, warnings) = ToolScope::try_compile(
854 "narrow",
855 &patterns,
856 ®istry,
857 PatternStrictness::Strict,
858 false,
859 )
860 .unwrap();
861 assert!(warnings.is_empty());
862 assert!(scope.admits("builtin:read"));
863 assert!(!scope.admits("builtin:shell"));
864 assert!(!scope.admits("builtin:write"));
865 }
866
867 #[test]
868 fn dead_pattern_strict_returns_error() {
869 let registry = make_registry(&["builtin:shell"]);
870 let patterns = vec!["builtin:nonexistent".to_owned()];
871 let result = ToolScope::try_compile(
872 "test",
873 &patterns,
874 ®istry,
875 PatternStrictness::Strict,
876 false,
877 );
878 assert!(
879 matches!(result, Err(ScopeError::DeadPattern { .. })),
880 "expected DeadPattern, got {result:?}"
881 );
882 }
883
884 #[test]
885 fn dead_pattern_provisional_returns_warning() {
886 let registry = make_registry(&["builtin:shell"]);
887 let patterns = vec!["mcp:server/nonexistent".to_owned()];
888 let result = ToolScope::try_compile(
889 "test",
890 &patterns,
891 ®istry,
892 PatternStrictness::ProvisionalForDynamicNamespaces,
893 false,
894 );
895 assert!(result.is_ok());
896 let (_, warnings) = result.unwrap();
897 assert_eq!(warnings.len(), 1);
898 }
899
900 #[test]
901 fn accidentally_full_pattern_returns_error() {
902 let registry = make_registry(&["builtin:shell", "builtin:read"]);
903 let patterns = vec!["*".to_owned()];
904 let result = ToolScope::try_compile(
905 "test",
906 &patterns,
907 ®istry,
908 PatternStrictness::Strict,
909 false, );
911 assert!(
912 matches!(result, Err(ScopeError::AccidentallyFull { .. })),
913 "expected AccidentallyFull for non-general scope with '*'"
914 );
915 }
916
917 #[test]
918 fn general_scope_allows_wildcard() {
919 let registry = make_registry(&["builtin:shell", "builtin:read"]);
920 let patterns = vec!["*".to_owned()];
921 let result = ToolScope::try_compile(
922 "general",
923 &patterns,
924 ®istry,
925 PatternStrictness::Strict,
926 true, );
928 assert!(result.is_ok());
929 }
930
931 #[tokio::test]
932 async fn executor_rejects_out_of_scope_call() {
933 let registry = make_registry(&["builtin:shell", "builtin:read"]);
934 let (scope, _) = ToolScope::try_compile(
935 "narrow",
936 &["builtin:read".to_owned()],
937 ®istry,
938 PatternStrictness::Strict,
939 false,
940 )
941 .unwrap();
942 let inner = NullExecutor {
943 defs: vec![null_def("builtin:shell"), null_def("builtin:read")],
944 };
945 let executor = ScopedToolExecutor::new(inner, scope);
946 let call = make_call("builtin:shell");
947 let result = executor.execute_tool_call(&call).await;
948 assert_matches!(result, Err(ToolError::OutOfScope { .. }));
949 }
950
951 #[tokio::test]
952 async fn executor_allows_in_scope_call() {
953 let registry = make_registry(&["builtin:shell", "builtin:read"]);
954 let (scope, _) = ToolScope::try_compile(
955 "narrow",
956 &["builtin:read".to_owned()],
957 ®istry,
958 PatternStrictness::Strict,
959 false,
960 )
961 .unwrap();
962 let inner = NullExecutor {
963 defs: vec![null_def("builtin:shell"), null_def("builtin:read")],
964 };
965 let executor = ScopedToolExecutor::new(inner, scope);
966 let call = make_call("builtin:read");
967 let result = executor.execute_tool_call(&call).await;
968 assert!(result.is_ok());
969 }
970
971 #[test]
972 fn tool_definitions_filtered_by_scope() {
973 let registry = make_registry(&["builtin:shell", "builtin:read"]);
974 let (scope, _) = ToolScope::try_compile(
975 "narrow",
976 &["builtin:read".to_owned()],
977 ®istry,
978 PatternStrictness::Strict,
979 false,
980 )
981 .unwrap();
982 let inner = NullExecutor {
983 defs: vec![null_def("builtin:shell"), null_def("builtin:read")],
984 };
985 let executor = ScopedToolExecutor::new(inner, scope);
986 let defs = executor.tool_definitions();
987 assert_eq!(defs.len(), 1);
988 assert_eq!(defs[0].id.as_ref(), "builtin:read");
989 }
990
991 #[tokio::test]
992 async fn unnamespaced_tool_id_admitted_via_builtin_prefix() {
993 let registry = make_registry(&["builtin:bash", "builtin:read"]);
996 let (scope, _) = ToolScope::try_compile(
997 "narrow",
998 &["builtin:bash".to_owned()],
999 ®istry,
1000 PatternStrictness::Strict,
1001 false,
1002 )
1003 .unwrap();
1004 let inner = NullExecutor {
1005 defs: vec![null_def("bash"), null_def("read")],
1006 };
1007 let executor = ScopedToolExecutor::new(inner, scope);
1008 let call = make_call("bash");
1010 let result = executor.execute_tool_call(&call).await;
1011 assert!(
1012 result.is_ok(),
1013 "builtin tool with unqualified id must be admitted"
1014 );
1015 let call_read = make_call("read");
1017 let result_read = executor.execute_tool_call(&call_read).await;
1018 assert!(
1019 matches!(result_read, Err(ToolError::OutOfScope { .. })),
1020 "out-of-scope built-in tool must be rejected"
1021 );
1022 }
1023
1024 #[test]
1025 fn build_scoped_executor_accepts_unqualified_registry_id() {
1026 let cfg = CapabilityScopesConfig::default();
1029 let registry = make_registry(&["shell"]); let inner = NullExecutor { defs: vec![] };
1031 let result = build_scoped_executor(inner, &cfg, ®istry);
1032 assert!(
1033 result.is_ok(),
1034 "build_scoped_executor must accept unqualified registry ids"
1035 );
1036 }
1037
1038 #[test]
1039 fn build_scoped_executor_with_builtin_prefix_and_glob() {
1040 let mut cfg = CapabilityScopesConfig::default();
1041 cfg.scopes.insert(
1042 "general".to_owned(),
1043 ScopeConfig {
1044 patterns: vec!["builtin:*".to_owned()],
1045 },
1046 );
1047 cfg.default_scope = "general".to_owned();
1048 let registry = make_registry(&["builtin:bash", "builtin:read", "builtin:fetch"]);
1049 let inner = NullExecutor { defs: vec![] };
1050 let result = build_scoped_executor(inner, &cfg, ®istry);
1051 assert!(
1052 result.is_ok(),
1053 "builtin:* glob must match all builtin tools"
1054 );
1055 }
1056
1057 #[tokio::test]
1058 async fn unqualified_tool_out_of_scope_rejected() {
1059 let registry = make_registry(&["builtin:bash", "builtin:read"]);
1060 let (scope, _) = ToolScope::try_compile(
1061 "narrow",
1062 &["builtin:read".to_owned()],
1063 ®istry,
1064 PatternStrictness::Strict,
1065 false,
1066 )
1067 .unwrap();
1068 let inner = NullExecutor {
1069 defs: vec![null_def("bash"), null_def("read")],
1070 };
1071 let executor = ScopedToolExecutor::new(inner, scope);
1072 let call = make_call("bash"); let result = executor.execute_tool_call(&call).await;
1074 assert!(
1075 matches!(result, Err(ToolError::OutOfScope { .. })),
1076 "unqualified id not in scope must be rejected after normalization"
1077 );
1078 }
1079
1080 #[test]
1081 fn tool_definitions_filtered_by_scope_with_unqualified_ids() {
1082 let registry = make_registry(&["builtin:bash", "builtin:read"]);
1084 let (scope, _) = ToolScope::try_compile(
1085 "narrow",
1086 &["builtin:read".to_owned()],
1087 ®istry,
1088 PatternStrictness::Strict,
1089 false,
1090 )
1091 .unwrap();
1092 let inner = NullExecutor {
1093 defs: vec![null_def("bash"), null_def("read")],
1094 };
1095 let executor = ScopedToolExecutor::new(inner, scope);
1096 let defs = executor.tool_definitions();
1097 assert_eq!(defs.len(), 1);
1098 assert_eq!(defs[0].id.as_ref(), "read");
1099 }
1100
1101 #[test]
1102 fn scope_for_task_returns_ids() {
1103 let registry = make_registry(&["builtin:shell", "builtin:read"]);
1104 let (scope, _) = ToolScope::try_compile(
1105 "narrow",
1106 &["builtin:read".to_owned()],
1107 ®istry,
1108 PatternStrictness::Strict,
1109 false,
1110 )
1111 .unwrap();
1112 let inner = NullExecutor { defs: vec![] };
1113 let mut executor = ScopedToolExecutor::new(inner, ToolScope::full());
1114 executor.register_scope("narrow", scope);
1115 let ids = executor.scope_for_task("narrow");
1116 assert!(ids.is_some());
1117 let ids = ids.unwrap();
1118 assert!(ids.contains(&"builtin:read".to_owned()));
1119 assert!(!ids.contains(&"builtin:shell".to_owned()));
1120 }
1121
1122 #[test]
1123 fn scope_for_task_returns_none_for_unknown() {
1124 let inner = NullExecutor { defs: vec![] };
1125 let executor = ScopedToolExecutor::new(inner, ToolScope::full());
1126 assert!(executor.scope_for_task("does_not_exist").is_none());
1127 }
1128
1129 #[test]
1130 fn re_resolve_updates_admitted_set() {
1131 let registry = make_registry(&["builtin:read", "mcp:server/tool"]);
1134 let (scope, _) = ToolScope::try_compile(
1135 "narrow",
1136 &["builtin:read".to_owned()],
1137 ®istry,
1138 PatternStrictness::Strict,
1139 false,
1140 )
1141 .unwrap();
1142 assert!(scope.admits("builtin:read"));
1143 assert!(!scope.admits("builtin:write"));
1144
1145 let mut new_registry = registry.clone();
1147 new_registry.insert("builtin:write".to_owned());
1148 let updated = scope.re_resolve(&new_registry);
1149 assert!(updated.admits("builtin:read"));
1150 assert!(!updated.admits("builtin:write"));
1152 }
1153
1154 #[test]
1155 fn checkpoint_methods_delegated_to_inner() {
1156 let executor = ScopedToolExecutor::new(CheckpointingExecutor, ToolScope::full());
1157 let undo_result = executor.checkpoint_undo(7);
1158 assert!(undo_result.supported);
1159 assert_eq!(
1160 undo_result.reverted_commands, 7,
1161 "n must be forwarded, not hardcoded"
1162 );
1163 assert!(executor.checkpoint_redo().supported);
1164 assert!(executor.checkpoint_list().supported);
1165 }
1166
1167 #[test]
1168 fn requires_confirmation_delegated_to_inner() {
1169 let executor = ScopedToolExecutor::new(CheckpointingExecutor, ToolScope::full());
1170 assert!(executor.requires_confirmation(&make_call("builtin:shell")));
1171 }
1172
1173 #[test]
1174 fn build_from_config_with_scopes() {
1175 let mut scopes = std::collections::HashMap::new();
1176 scopes.insert(
1177 "general".to_owned(),
1178 ScopeConfig {
1179 patterns: vec!["*".to_owned()],
1180 },
1181 );
1182 scopes.insert(
1183 "narrow".to_owned(),
1184 ScopeConfig {
1185 patterns: vec!["builtin:read".to_owned()],
1186 },
1187 );
1188 let cfg = CapabilityScopesConfig {
1189 default_scope: "general".to_owned(),
1190 strict: false,
1191 pattern_strictness: PatternStrictness::Strict,
1192 scopes,
1193 };
1194 let registry = make_registry(&["builtin:shell", "builtin:read"]);
1195 let inner = NullExecutor { defs: vec![] };
1196 let executor = build_scoped_executor(inner, &cfg, ®istry).unwrap();
1197 let narrow_ids = executor.scope_for_task("narrow");
1199 assert!(narrow_ids.is_some());
1200 let ids = narrow_ids.unwrap();
1201 assert!(ids.contains(&"builtin:read".to_owned()));
1202 }
1203}