Skip to main content

zeph_tools/
scope.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! `ScopedToolExecutor`: config-driven capability scoping wrapper.
5//!
6//! Wraps any `ToolExecutor` and filters both `tool_definitions()` (LLM tool list) and
7//! `execute_tool_call()` (dispatch path) to an operator-configured allow-list of
8//! fully-qualified tool ids.
9//!
10//! # Wiring order
11//!
12//! ```text
13//! ScopedToolExecutor          ← outermost (this crate)
14//!   → PolicyGateExecutor
15//!       → TrustGateExecutor
16//!           → CompositeExecutor
17//!               → ToolFilter, AuditedExecutor, ...
18//! ```
19//!
20//! `ScopedToolExecutor` is placed outside `PolicyGateExecutor` so an out-of-scope call
21//! short-circuits before policy evaluation.
22//!
23//! # Tool-id namespacing
24//!
25//! All tool ids MUST carry a namespace prefix before scope resolution:
26//!
27//! | Source | Prefix |
28//! |---|---|
29//! | Built-in executors | `builtin:` |
30//! | Skill-defined tools | `skill:<name>/` |
31//! | MCP tools | `mcp:<server_id>/` |
32//! | ACP / A2A proxied tools | `acp:<peer>/` / `a2a:<peer>/` |
33//!
34//! Built-in executors register tools with unqualified ids (`"bash"`, `"read"`, etc.).
35//! At the scope boundary these are automatically normalised to `builtin:<id>` so that
36//! patterns like `builtin:*` or `builtin:bash` resolve correctly.  The caller of
37//! `build_scoped_executor` (see `runner.rs`) is responsible for pre-qualifying registry
38//! ids before passing them in.
39//!
40//! # Pattern strictness
41//!
42//! - `builtin:` / `skill:` globs: strict — zero-match is `ScopeError::DeadPattern`.
43//! - `mcp:` / `acp:` / `a2a:` globs: provisional — zero-match is
44//!   `ScopeWarning::ProvisionalDeadPattern` (re-resolved on dynamic registration).
45//! - A glob matching the **entire** registry without an explicit `general` opt-in is
46//!   `ScopeError::AccidentallyFull`.
47
48use 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// ── Errors & warnings ─────────────────────────────────────────────────────────
61
62#[non_exhaustive]
63/// Fatal startup error emitted when a scope configuration is invalid.
64#[derive(Debug, thiserror::Error)]
65pub enum ScopeError {
66    /// A glob pattern in a strict namespace matched zero registered tool ids.
67    #[error("scope '{scope}': pattern '{pattern}' matched zero registered tools (dead pattern)")]
68    DeadPattern { scope: String, pattern: String },
69
70    /// A glob pattern expanded to the entire tool registry without an explicit opt-in.
71    #[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    /// An executor registered a tool id without a namespace prefix.
77    #[error("tool id '{id}' has no namespace prefix (expected '<namespace>:<id>')")]
78    UnqualifiedId { id: String },
79
80    /// A glob pattern could not be compiled.
81    #[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/// Non-fatal warning emitted for provisional-namespace zero-match patterns.
91#[derive(Debug)]
92pub struct ScopeWarning {
93    /// The scope name containing the unresolved pattern.
94    pub scope: String,
95    /// The glob pattern that matched zero ids at build time.
96    pub pattern: String,
97}
98
99// ── ToolScope ─────────────────────────────────────────────────────────────────
100
101/// Materialised tool scope: a pre-compiled allow-list of fully-qualified tool ids.
102///
103/// At agent build time, glob patterns are resolved against the registered tool set
104/// and stored as a `HashSet<String>`. Runtime admission is an O(1) lookup.
105#[derive(Debug, Clone)]
106pub struct ToolScope {
107    /// Identifier of this scope (task-type name).
108    pub task_type: Option<String>,
109    /// Expanded, materialised set of fully-qualified tool ids.
110    admitted: HashSet<String>,
111    /// `true` for the `general` default-scope only; admits every id without lookup.
112    is_full: bool,
113    /// Original patterns, kept for re-resolution when new tools are registered dynamically.
114    patterns: Vec<String>,
115}
116
117impl ToolScope {
118    /// The identity scope: admits every tool id. Used for the `general` default scope.
119    ///
120    /// # Examples
121    ///
122    /// ```rust
123    /// use zeph_tools::scope::ToolScope;
124    ///
125    /// let scope = ToolScope::full();
126    /// assert!(scope.admits("builtin:shell"));
127    /// assert!(scope.admits("mcp:any_server/any_tool"));
128    /// ```
129    #[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    /// The deny-all scope: admits no tool at all.
140    ///
141    /// Used as a fail-**closed** fallback when scope compilation fails for a single
142    /// session/connection (spec-050 FR-CG-005/NFR-CG-004: a misconfigured
143    /// `[security.capability_scopes]` entry must never silently degrade to "no scoping at
144    /// all" — that would be fail-**open** for a security control the operator explicitly
145    /// enabled). Prefer this over falling back to the unscoped inner executor.
146    ///
147    /// # Examples
148    ///
149    /// ```rust
150    /// use zeph_tools::scope::ToolScope;
151    ///
152    /// let scope = ToolScope::empty();
153    /// assert!(!scope.admits("builtin:shell"));
154    /// assert!(!scope.admits("mcp:any_server/any_tool"));
155    /// ```
156    #[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    /// Compile a scope from glob patterns against the materialised registry.
167    ///
168    /// # Errors
169    ///
170    /// Returns `ScopeError::DeadPattern` when a strict-namespace glob matches zero ids,
171    /// `ScopeError::AccidentallyFull` when a pattern expands to the entire registry without
172    /// an explicit `general` opt-in, or `ScopeError::InvalidPattern` on invalid glob syntax.
173    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            // Validate that glob compiles.
186            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            // Check for accidentally-full expansion (unless this is the general scope).
207            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    /// Returns `true` when the given fully-qualified tool id is admitted by this scope.
244    ///
245    /// # Examples
246    ///
247    /// ```rust
248    /// use zeph_tools::scope::ToolScope;
249    ///
250    /// let scope = ToolScope::full();
251    /// assert!(scope.admits("builtin:shell"));
252    /// ```
253    #[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    /// Returns the list of admitted tool ids (excluding `full` scopes).
259    ///
260    /// Useful for `/scope list` output and the `scope_at_definition` audit field.
261    #[must_use]
262    pub fn admitted_ids(&self) -> Vec<&str> {
263        self.admitted.iter().map(String::as_str).collect()
264    }
265
266    /// The raw glob patterns this scope was compiled from (for re-resolution).
267    #[must_use]
268    pub fn patterns(&self) -> &[String] {
269        &self.patterns
270    }
271
272    /// Re-resolve the scope against a new registry (called on dynamic tool registration).
273    ///
274    /// Returns a new `ToolScope` with the updated admit set; warnings are logged but not
275    /// returned (non-fatal for provisional namespaces).
276    #[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
309/// Returns `true` when the pattern targets a strict namespace (`builtin:` or `skill:`).
310fn is_strict_pattern(pattern: &str, strictness: PatternStrictness) -> bool {
311    match strictness {
312        PatternStrictness::Strict => true,
313        PatternStrictness::ProvisionalForDynamicNamespaces => {
314            // Strict for builtin: and skill:; provisional for mcp:, acp:, a2a:
315            pattern.starts_with("builtin:") || pattern.starts_with("skill:")
316        }
317        _ => false,
318    }
319}
320
321// ── ScopedToolExecutor ────────────────────────────────────────────────────────
322
323/// Wraps any `ToolExecutor` and enforces a capability scope on both tool listing and dispatch.
324///
325/// # Type parameter
326///
327/// `E` is the inner executor (e.g., `PolicyGateExecutor<TrustGateExecutor<CompositeExecutor>>`).
328///
329/// # Examples
330///
331/// ```rust,no_run
332/// use std::collections::HashSet;
333/// use zeph_tools::scope::{ScopedToolExecutor, ToolScope};
334/// use zeph_tools::{ToolExecutor, ToolCall};
335/// use zeph_common::ToolName;
336///
337/// // Build a full (no-op) scope — identity, admits everything.
338/// let scope = ToolScope::full();
339///
340/// // Wrap some inner executor (omitted for brevity).
341/// struct MockExecutor;
342/// impl ToolExecutor for MockExecutor {
343///     async fn execute(&self, _: &str) -> Result<Option<zeph_tools::ToolOutput>, zeph_tools::ToolError> { Ok(None) }
344///     zeph_tools::tool_executor_no_inner_defaults!();
345/// }
346/// let executor = ScopedToolExecutor::new(MockExecutor, scope);
347/// ```
348pub struct ScopedToolExecutor<E: ToolExecutor> {
349    inner: E,
350    /// Atomically swappable active scope. Swapped via `set_scope()`.
351    scope: ArcSwap<ToolScope>,
352    /// Named scope map for task-type lookup.
353    scopes: HashMap<String, Arc<ToolScope>>,
354    /// Name of the scope currently surfaced to the LLM (captured at `tool_definitions()` time).
355    scope_at_definition: parking_lot::Mutex<Option<String>>,
356    /// Optional shared queue — `OutOfScope` signal codes pushed here; drained by `begin_turn()`.
357    signal_queue: Option<crate::policy_gate::RiskSignalQueue>,
358    /// Optional audit logger — `out_of_scope` entries emitted on every rejection.
359    audit: Option<Arc<AuditLogger>>,
360}
361
362impl<E: ToolExecutor> ScopedToolExecutor<E> {
363    /// Create a new `ScopedToolExecutor` with the given initial scope.
364    ///
365    /// # Examples
366    ///
367    /// ```rust,no_run
368    /// use zeph_tools::scope::{ScopedToolExecutor, ToolScope};
369    ///
370    /// struct Noop;
371    /// impl zeph_tools::ToolExecutor for Noop {
372    ///     async fn execute(&self, _: &str) -> Result<Option<zeph_tools::ToolOutput>, zeph_tools::ToolError> { Ok(None) }
373    ///     zeph_tools::tool_executor_no_inner_defaults!();
374    /// }
375    /// let executor = ScopedToolExecutor::new(Noop, ToolScope::full());
376    /// ```
377    #[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    /// Attach an audit logger so every `OutOfScope` rejection writes an audit entry.
390    #[must_use]
391    pub fn with_audit(mut self, audit: Arc<AuditLogger>) -> Self {
392        self.audit = Some(audit);
393        self
394    }
395
396    /// Attach a shared signal queue so `OutOfScope` rejections are recorded in the sentinel.
397    #[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    /// Register a named scope for use with `set_scope_for_task`.
404    pub fn register_scope(&mut self, name: impl Into<String>, scope: ToolScope) {
405        self.scopes.insert(name.into(), Arc::new(scope));
406    }
407
408    /// Switch the active scope by task-type name. Returns `false` when the name is not found.
409    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    /// Replace the active scope with the given one directly.
419    pub fn set_scope(&self, scope: ToolScope) {
420        self.scope.store(Arc::new(scope));
421    }
422
423    /// Return the list of tool ids admitted by the scope for `task_type`.
424    ///
425    /// Returns `None` when `task_type` is not registered.
426    ///
427    /// # Examples
428    ///
429    /// ```rust,no_run
430    /// use zeph_tools::scope::{ScopedToolExecutor, ToolScope};
431    ///
432    /// struct Noop;
433    /// impl zeph_tools::ToolExecutor for Noop {
434    ///     async fn execute(&self, _: &str) -> Result<Option<zeph_tools::ToolOutput>, zeph_tools::ToolError> { Ok(None) }
435    ///     zeph_tools::tool_executor_no_inner_defaults!();
436    /// }
437    /// let mut executor = ScopedToolExecutor::new(Noop, ToolScope::full());
438    /// // scope_for_task returns None for unregistered task types
439    /// assert!(executor.scope_for_task("unknown").is_none());
440    /// ```
441    #[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    /// Name of the active scope at the last `tool_definitions()` call (for audit).
453    #[must_use]
454    pub fn scope_at_definition_name(&self) -> Option<String> {
455        self.scope_at_definition.lock().clone()
456    }
457
458    /// Name of the currently active scope (for audit at dispatch time).
459    #[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    // CRIT-03 carve-out: legacy fenced-block dispatch path is not scoped (mirrors PolicyGate).
467    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    /// Return the filtered tool definitions visible to the LLM under the active scope.
476    ///
477    /// Captures the active scope name into `scope_at_definition` for audit use.
478    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    /// Execute a structured tool call, rejecting out-of-scope ids before any side-effect.
499    ///
500    /// Returns `ToolError::OutOfScope` when the tool id is not in the active scope.
501    /// The audit log entry at the call site must carry `error_category = "out_of_scope"`.
502    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        // Built-in tools dispatch with unqualified ids ("bash", "read", etc.).
506        // Synthesize the "builtin:" prefix at the scope boundary so the admitted set
507        // (which contains "builtin:bash" etc.) resolves correctly.
508        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            // Signal code 3 = OutOfScope (matches RiskSignal::OutOfScope in zeph-core).
525            if let Some(ref q) = self.signal_queue {
526                q.lock().push(3);
527            }
528            // F4: emit audit entry with error_category = "out_of_scope".
529            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
662// ── Config-driven builder ──────────────────────────────────────────────────────
663
664/// Build a `ScopedToolExecutor` from a `CapabilityScopesConfig` and a registered tool set.
665///
666/// Returns a fatal `ScopeError` when any strict-namespace pattern matches zero tools.
667/// Emits `ScopeWarning` entries for provisional-namespace zero-match patterns.
668///
669/// # Errors
670///
671/// Returns `ScopeError` when scope configuration is invalid (dead patterns, accidental-full).
672///
673/// # Examples
674///
675/// ```rust,no_run
676/// use std::collections::HashSet;
677/// use zeph_config::CapabilityScopesConfig;
678/// use zeph_tools::scope::build_scoped_executor;
679///
680/// struct Noop;
681/// impl zeph_tools::ToolExecutor for Noop {
682///     async fn execute(&self, _: &str) -> Result<Option<zeph_tools::ToolOutput>, zeph_tools::ToolError> { Ok(None) }
683///     zeph_tools::tool_executor_no_inner_defaults!();
684/// }
685///
686/// let cfg = CapabilityScopesConfig::default();
687/// let registry: HashSet<String> = HashSet::new();
688/// let executor = build_scoped_executor(Noop, &cfg, &registry).expect("build failed");
689/// ```
690pub 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    // The default initial scope is full (no-op) unless a named default_scope is configured.
699    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 a default_scope is configured and registered, activate it.
722    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            &registry,
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            &registry,
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            &registry,
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            &registry,
908            PatternStrictness::Strict,
909            false, // not general scope
910        );
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            &registry,
925            PatternStrictness::Strict,
926            true, // is_general_scope = true
927        );
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            &registry,
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            &registry,
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            &registry,
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        // Built-in tools dispatch with unqualified ids (e.g. "bash").
994        // ScopedToolExecutor must normalize "bash" → "builtin:bash" before the admits check.
995        let registry = make_registry(&["builtin:bash", "builtin:read"]);
996        let (scope, _) = ToolScope::try_compile(
997            "narrow",
998            &["builtin:bash".to_owned()],
999            &registry,
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        // "bash" (unqualified) must be admitted because admitted set contains "builtin:bash".
1009        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        // "read" is not in the narrow scope, so it must be rejected.
1016        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        // registry_ids in runner.rs are pre-qualified; build_scoped_executor must not
1027        // reject unqualified ids itself (caller responsibility).
1028        let cfg = CapabilityScopesConfig::default();
1029        let registry = make_registry(&["shell"]); // no namespace — still accepted
1030        let inner = NullExecutor { defs: vec![] };
1031        let result = build_scoped_executor(inner, &cfg, &registry);
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, &registry);
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            &registry,
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"); // unqualified; not in narrow scope
1073        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        // Built-in tool defs have unqualified ids; filtering must still work via builtin: prefix.
1083        let registry = make_registry(&["builtin:bash", "builtin:read"]);
1084        let (scope, _) = ToolScope::try_compile(
1085            "narrow",
1086            &["builtin:read".to_owned()],
1087            &registry,
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            &registry,
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        // Initial registry: two tools so builtin:* does not accidentally cover everything.
1132        // Use a specific pattern to keep the test simple.
1133        let registry = make_registry(&["builtin:read", "mcp:server/tool"]);
1134        let (scope, _) = ToolScope::try_compile(
1135            "narrow",
1136            &["builtin:read".to_owned()],
1137            &registry,
1138            PatternStrictness::Strict,
1139            false,
1140        )
1141        .unwrap();
1142        assert!(scope.admits("builtin:read"));
1143        assert!(!scope.admits("builtin:write"));
1144
1145        // After re-resolve with a new registry entry the pattern still only matches "builtin:read".
1146        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        // "builtin:write" is not in the original pattern, so it remains excluded.
1151        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, &registry).unwrap();
1197        // narrow scope should be registered
1198        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}