Skip to main content

zeph_subagent/
filter.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::collections::HashMap;
5use std::pin::Pin;
6use std::sync::Arc;
7
8use zeph_skills::loader::Skill;
9use zeph_skills::registry::SkillRegistry;
10use zeph_tools::ToolCall;
11use zeph_tools::executor::{ErasedToolExecutor, ToolError, ToolOutput, extract_fenced_blocks};
12use zeph_tools::registry::{InvocationHint, ToolDef};
13
14use super::def::{SkillFilter, ToolPolicy};
15use super::error::SubAgentError;
16
17// ── Helpers ───────────────────────────────────────────────────────────────────
18
19/// Collect all fenced-block language tags from an executor's tool definitions.
20fn collect_fenced_tags(executor: &dyn ErasedToolExecutor) -> Vec<&'static str> {
21    executor
22        .tool_definitions_erased()
23        .into_iter()
24        .filter_map(|def| match def.invocation {
25            InvocationHint::FencedBlock(tag) => Some(tag),
26            InvocationHint::ToolCall => None,
27        })
28        .collect()
29}
30
31// ── Tool filtering ────────────────────────────────────────────────────────────
32
33/// Wraps an [`ErasedToolExecutor`] and enforces a [`ToolPolicy`] plus an optional
34/// additional denylist (`disallowed`).
35///
36/// All calls are checked against the policy and the denylist before being forwarded
37/// to the inner executor. The denylist is evaluated first — a tool in `disallowed`
38/// is blocked even if `policy` would allow it (deny wins). Rejected calls return a
39/// descriptive [`ToolError`].
40pub struct FilteredToolExecutor {
41    inner: Arc<dyn ErasedToolExecutor>,
42    policy: ToolPolicy,
43    disallowed: Vec<String>,
44    /// Fenced-block language tags collected from `inner` at construction time.
45    /// Used to detect actual fenced-block tool invocations in LLM responses.
46    fenced_tags: Vec<&'static str>,
47}
48
49impl FilteredToolExecutor {
50    /// Create a new filtered executor.
51    #[must_use]
52    pub fn new(inner: Arc<dyn ErasedToolExecutor>, policy: ToolPolicy) -> Self {
53        let fenced_tags = collect_fenced_tags(&*inner);
54        Self {
55            inner,
56            policy,
57            disallowed: Vec::new(),
58            fenced_tags,
59        }
60    }
61
62    /// Create a new filtered executor with an additional denylist.
63    ///
64    /// Tools in `disallowed` are blocked regardless of the base `policy`
65    /// (deny wins over allow).
66    #[must_use]
67    pub fn with_disallowed(
68        inner: Arc<dyn ErasedToolExecutor>,
69        policy: ToolPolicy,
70        disallowed: Vec<String>,
71    ) -> Self {
72        let fenced_tags = collect_fenced_tags(&*inner);
73        Self {
74            inner,
75            policy,
76            disallowed,
77            fenced_tags,
78        }
79    }
80
81    /// Return `true` if `response` contains at least one fenced block matching a registered tool.
82    fn has_fenced_tool_invocation(&self, response: &str) -> bool {
83        self.fenced_tags
84            .iter()
85            .any(|tag| !extract_fenced_blocks(response, tag).is_empty())
86    }
87
88    /// Check whether `tool_id` is allowed under the current policy and denylist.
89    ///
90    /// Matching is exact string equality. MCP compound tool IDs (e.g. `mcp__server__tool`)
91    /// must be listed in full in `tools.except` — partial names or prefixes are not matched.
92    fn is_allowed(&self, tool_id: &str) -> bool {
93        if self.disallowed.iter().any(|t| t == tool_id) {
94            return false;
95        }
96        match &self.policy {
97            ToolPolicy::InheritAll => true,
98            ToolPolicy::AllowList(list) => list.iter().any(|t| t == tool_id),
99            ToolPolicy::DenyList(list) => !list.iter().any(|t| t == tool_id),
100        }
101    }
102}
103
104impl ErasedToolExecutor for FilteredToolExecutor {
105    fn execute_erased<'a>(
106        &'a self,
107        response: &'a str,
108    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
109    {
110        // Sub-agents must use structured tool calls (execute_tool_call_erased).
111        // Fenced-block execution is disabled to prevent policy bypass (SEC-03).
112        //
113        // However, this method is also called for plain-text LLM responses that
114        // contain markdown code fences unrelated to tool invocations. Returning
115        // Err unconditionally causes the agent loop to treat every text response
116        // as a failed tool call and exhaust all turns without producing output.
117        //
118        // Only block when the response actually contains a fenced block that
119        // matches a registered fenced-block tool language tag.
120        if self.has_fenced_tool_invocation(response) {
121            tracing::warn!("sub-agent attempted fenced-block tool invocation — blocked by policy");
122            return Box::pin(std::future::ready(Err(ToolError::Blocked {
123                command: "fenced-block".into(),
124            })));
125        }
126        Box::pin(std::future::ready(Ok(None)))
127    }
128
129    fn execute_confirmed_erased<'a>(
130        &'a self,
131        response: &'a str,
132    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
133    {
134        // Same policy as execute_erased: only block actual fenced-block invocations.
135        if self.has_fenced_tool_invocation(response) {
136            tracing::warn!(
137                "sub-agent attempted confirmed fenced-block tool invocation — blocked by policy"
138            );
139            return Box::pin(std::future::ready(Err(ToolError::Blocked {
140                command: "fenced-block".into(),
141            })));
142        }
143        Box::pin(std::future::ready(Ok(None)))
144    }
145
146    fn tool_definitions_erased(&self) -> Vec<ToolDef> {
147        // Filter the visible tool definitions according to the policy.
148        self.inner
149            .tool_definitions_erased()
150            .into_iter()
151            .filter(|def| self.is_allowed(&def.id))
152            .collect()
153    }
154
155    fn execute_tool_call_erased<'a>(
156        &'a self,
157        call: &'a ToolCall,
158    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
159    {
160        if !self.is_allowed(&call.tool_id) {
161            tracing::warn!(
162                tool_id = %call.tool_id,
163                "sub-agent tool call rejected by policy"
164            );
165            return Box::pin(std::future::ready(Err(ToolError::Blocked {
166                command: call.tool_id.clone(),
167            })));
168        }
169        Box::pin(self.inner.execute_tool_call_erased(call))
170    }
171
172    fn set_skill_env(&self, env: Option<HashMap<String, String>>) {
173        self.inner.set_skill_env(env);
174    }
175
176    fn is_tool_retryable_erased(&self, tool_id: &str) -> bool {
177        self.inner.is_tool_retryable_erased(tool_id)
178    }
179}
180
181// ── Plan mode executor ────────────────────────────────────────────────────────
182
183/// Wraps an [`ErasedToolExecutor`] for `Plan` permission mode.
184///
185/// Exposes the real tool catalog via `tool_definitions_erased()` so the LLM can
186/// reference existing tools in its plan, but blocks all execution methods with
187/// [`ToolError::Blocked`]. This implements read-only planning: the agent sees what
188/// tools exist but cannot invoke them.
189pub struct PlanModeExecutor {
190    inner: Arc<dyn ErasedToolExecutor>,
191}
192
193impl PlanModeExecutor {
194    /// Wrap `inner` with plan-mode restrictions.
195    #[must_use]
196    pub fn new(inner: Arc<dyn ErasedToolExecutor>) -> Self {
197        Self { inner }
198    }
199}
200
201impl ErasedToolExecutor for PlanModeExecutor {
202    fn execute_erased<'a>(
203        &'a self,
204        _response: &'a str,
205    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
206    {
207        Box::pin(std::future::ready(Err(ToolError::Blocked {
208            command: "plan_mode".into(),
209        })))
210    }
211
212    fn execute_confirmed_erased<'a>(
213        &'a self,
214        _response: &'a str,
215    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
216    {
217        Box::pin(std::future::ready(Err(ToolError::Blocked {
218            command: "plan_mode".into(),
219        })))
220    }
221
222    fn tool_definitions_erased(&self) -> Vec<ToolDef> {
223        self.inner.tool_definitions_erased()
224    }
225
226    fn execute_tool_call_erased<'a>(
227        &'a self,
228        call: &'a ToolCall,
229    ) -> Pin<Box<dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
230    {
231        tracing::debug!(
232            tool_id = %call.tool_id,
233            "tool execution blocked in plan mode"
234        );
235        Box::pin(std::future::ready(Err(ToolError::Blocked {
236            command: call.tool_id.clone(),
237        })))
238    }
239
240    fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
241        self.inner.set_skill_env(env);
242    }
243
244    fn is_tool_retryable_erased(&self, _tool_id: &str) -> bool {
245        false
246    }
247}
248
249// ── Skill filtering ───────────────────────────────────────────────────────────
250
251/// Filter skills from a registry according to a [`SkillFilter`].
252///
253/// Include patterns are glob-matched against skill names. If `include` is empty,
254/// all skills pass (unless excluded). Exclude patterns always take precedence.
255///
256/// # Errors
257///
258/// Returns [`SubAgentError::Invalid`] if any glob pattern is syntactically invalid.
259pub fn filter_skills(
260    registry: &SkillRegistry,
261    filter: &SkillFilter,
262) -> Result<Vec<Skill>, SubAgentError> {
263    let compiled_include = compile_globs(&filter.include)?;
264    let compiled_exclude = compile_globs(&filter.exclude)?;
265
266    let all: Vec<Skill> = registry
267        .all_meta()
268        .into_iter()
269        .filter(|meta| {
270            let name = &meta.name;
271            let included =
272                compiled_include.is_empty() || compiled_include.iter().any(|p| glob_match(p, name));
273            let excluded = compiled_exclude.iter().any(|p| glob_match(p, name));
274            included && !excluded
275        })
276        .filter_map(|meta| registry.get_skill(&meta.name).ok())
277        .collect();
278
279    Ok(all)
280}
281
282/// Compiled glob pattern: literal prefix + optional `*` wildcard suffix.
283struct GlobPattern {
284    raw: String,
285    prefix: String,
286    suffix: Option<String>,
287    is_star: bool,
288}
289
290fn compile_globs(patterns: &[String]) -> Result<Vec<GlobPattern>, SubAgentError> {
291    patterns.iter().map(|p| compile_glob(p)).collect()
292}
293
294fn compile_glob(pattern: &str) -> Result<GlobPattern, SubAgentError> {
295    // Simple glob: supports `*` as a wildcard anywhere in the string.
296    // For MVP we only need prefix-star patterns like "git-*" or "*".
297    if pattern.contains("**") {
298        return Err(SubAgentError::Invalid(format!(
299            "glob pattern '{pattern}' uses '**' which is not supported"
300        )));
301    }
302
303    let is_star = pattern == "*";
304
305    let (prefix, suffix) = if let Some(pos) = pattern.find('*') {
306        let before = pattern[..pos].to_owned();
307        let after = pattern[pos + 1..].to_owned();
308        (before, Some(after))
309    } else {
310        (pattern.to_owned(), None)
311    };
312
313    Ok(GlobPattern {
314        raw: pattern.to_owned(),
315        prefix,
316        suffix,
317        is_star,
318    })
319}
320
321fn glob_match(pattern: &GlobPattern, name: &str) -> bool {
322    if pattern.is_star {
323        return true;
324    }
325
326    match &pattern.suffix {
327        None => name == pattern.raw,
328        Some(suf) => {
329            name.starts_with(&pattern.prefix) && name.ends_with(suf.as_str()) && {
330                // Ensure the wildcard section isn't negative-length.
331                name.len() >= pattern.prefix.len() + suf.len()
332            }
333        }
334    }
335}
336
337// ── Tests ─────────────────────────────────────────────────────────────────────
338
339#[cfg(test)]
340mod tests {
341    #![allow(clippy::default_trait_access)]
342
343    use super::*;
344    use crate::def::ToolPolicy;
345
346    // ── FilteredToolExecutor tests ─────────────────────────────────────────
347
348    struct StubExecutor {
349        tools: Vec<&'static str>,
350    }
351
352    /// Stub executor that exposes tools with `InvocationHint::FencedBlock(tag)`.
353    struct StubFencedExecutor {
354        tag: &'static str,
355    }
356
357    impl ErasedToolExecutor for StubFencedExecutor {
358        fn execute_erased<'a>(
359            &'a self,
360            _response: &'a str,
361        ) -> Pin<
362            Box<
363                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
364            >,
365        > {
366            Box::pin(std::future::ready(Ok(None)))
367        }
368
369        fn execute_confirmed_erased<'a>(
370            &'a self,
371            _response: &'a str,
372        ) -> Pin<
373            Box<
374                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
375            >,
376        > {
377            Box::pin(std::future::ready(Ok(None)))
378        }
379
380        fn tool_definitions_erased(&self) -> Vec<ToolDef> {
381            use zeph_tools::registry::InvocationHint;
382            vec![ToolDef {
383                id: self.tag.into(),
384                description: "fenced stub".into(),
385                schema: schemars::Schema::default(),
386                invocation: InvocationHint::FencedBlock(self.tag),
387            }]
388        }
389
390        fn execute_tool_call_erased<'a>(
391            &'a self,
392            call: &'a ToolCall,
393        ) -> Pin<
394            Box<
395                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
396            >,
397        > {
398            let result = Ok(Some(ToolOutput {
399                tool_name: call.tool_id.clone(),
400                summary: "ok".into(),
401                blocks_executed: 1,
402                filter_stats: None,
403                diff: None,
404                streamed: false,
405                terminal_id: None,
406                locations: None,
407                raw_response: None,
408                claim_source: None,
409            }));
410            Box::pin(std::future::ready(result))
411        }
412
413        fn is_tool_retryable_erased(&self, _tool_id: &str) -> bool {
414            false
415        }
416    }
417
418    fn fenced_stub_box(tag: &'static str) -> Arc<dyn ErasedToolExecutor> {
419        Arc::new(StubFencedExecutor { tag })
420    }
421
422    impl ErasedToolExecutor for StubExecutor {
423        fn execute_erased<'a>(
424            &'a self,
425            _response: &'a str,
426        ) -> Pin<
427            Box<
428                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
429            >,
430        > {
431            Box::pin(std::future::ready(Ok(None)))
432        }
433
434        fn execute_confirmed_erased<'a>(
435            &'a self,
436            _response: &'a str,
437        ) -> Pin<
438            Box<
439                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
440            >,
441        > {
442            Box::pin(std::future::ready(Ok(None)))
443        }
444
445        fn tool_definitions_erased(&self) -> Vec<ToolDef> {
446            // Return stub definitions for each tool name.
447            use zeph_tools::registry::InvocationHint;
448            self.tools
449                .iter()
450                .map(|id| ToolDef {
451                    id: (*id).into(),
452                    description: "stub".into(),
453                    schema: schemars::Schema::default(),
454                    invocation: InvocationHint::ToolCall,
455                })
456                .collect()
457        }
458
459        fn execute_tool_call_erased<'a>(
460            &'a self,
461            call: &'a ToolCall,
462        ) -> Pin<
463            Box<
464                dyn std::future::Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a,
465            >,
466        > {
467            let result = Ok(Some(ToolOutput {
468                tool_name: call.tool_id.clone(),
469                summary: "ok".into(),
470                blocks_executed: 1,
471                filter_stats: None,
472                diff: None,
473                streamed: false,
474                terminal_id: None,
475                locations: None,
476                raw_response: None,
477                claim_source: None,
478            }));
479            Box::pin(std::future::ready(result))
480        }
481
482        fn is_tool_retryable_erased(&self, _tool_id: &str) -> bool {
483            false
484        }
485    }
486
487    fn stub_box(tools: &[&'static str]) -> Arc<dyn ErasedToolExecutor> {
488        Arc::new(StubExecutor {
489            tools: tools.to_vec(),
490        })
491    }
492
493    #[tokio::test]
494    async fn allow_list_permits_listed_tool() {
495        let exec = FilteredToolExecutor::new(
496            stub_box(&["shell", "web"]),
497            ToolPolicy::AllowList(vec!["shell".into()]),
498        );
499        let call = ToolCall {
500            tool_id: "shell".into(),
501            params: serde_json::Map::default(),
502        };
503        let res = exec.execute_tool_call_erased(&call).await.unwrap();
504        assert!(res.is_some());
505    }
506
507    #[tokio::test]
508    async fn allow_list_blocks_unlisted_tool() {
509        let exec = FilteredToolExecutor::new(
510            stub_box(&["shell", "web"]),
511            ToolPolicy::AllowList(vec!["shell".into()]),
512        );
513        let call = ToolCall {
514            tool_id: "web".into(),
515            params: serde_json::Map::default(),
516        };
517        let res = exec.execute_tool_call_erased(&call).await;
518        assert!(res.is_err());
519    }
520
521    #[tokio::test]
522    async fn deny_list_blocks_listed_tool() {
523        let exec = FilteredToolExecutor::new(
524            stub_box(&["shell", "web"]),
525            ToolPolicy::DenyList(vec!["shell".into()]),
526        );
527        let call = ToolCall {
528            tool_id: "shell".into(),
529            params: serde_json::Map::default(),
530        };
531        let res = exec.execute_tool_call_erased(&call).await;
532        assert!(res.is_err());
533    }
534
535    #[tokio::test]
536    async fn inherit_all_permits_any_tool() {
537        let exec = FilteredToolExecutor::new(stub_box(&["shell"]), ToolPolicy::InheritAll);
538        let call = ToolCall {
539            tool_id: "shell".into(),
540            params: serde_json::Map::default(),
541        };
542        let res = exec.execute_tool_call_erased(&call).await.unwrap();
543        assert!(res.is_some());
544    }
545
546    #[test]
547    fn tool_definitions_filtered_by_allow_list() {
548        let exec = FilteredToolExecutor::new(
549            stub_box(&["shell", "web"]),
550            ToolPolicy::AllowList(vec!["shell".into()]),
551        );
552        let defs = exec.tool_definitions_erased();
553        assert_eq!(defs.len(), 1);
554        assert_eq!(defs[0].id, "shell");
555    }
556
557    // ── glob_match tests ───────────────────────────────────────────────────
558
559    fn matches(pattern: &str, name: &str) -> bool {
560        let p = compile_glob(pattern).unwrap();
561        glob_match(&p, name)
562    }
563
564    #[test]
565    fn glob_star_matches_all() {
566        assert!(matches("*", "anything"));
567        assert!(matches("*", ""));
568    }
569
570    #[test]
571    fn glob_prefix_star() {
572        assert!(matches("git-*", "git-commit"));
573        assert!(matches("git-*", "git-status"));
574        assert!(!matches("git-*", "rust-fmt"));
575    }
576
577    #[test]
578    fn glob_literal_exact_match() {
579        assert!(matches("shell", "shell"));
580        assert!(!matches("shell", "shell-extra"));
581    }
582
583    #[test]
584    fn glob_star_suffix() {
585        assert!(matches("*-review", "code-review"));
586        assert!(!matches("*-review", "code-reviewer"));
587    }
588
589    #[test]
590    fn glob_double_star_is_error() {
591        assert!(compile_glob("**").is_err());
592    }
593
594    #[test]
595    fn glob_mid_string_wildcard() {
596        // "a*b" — prefix="a", suffix=Some("b")
597        assert!(matches("a*b", "axb"));
598        assert!(matches("a*b", "aXYZb"));
599        assert!(!matches("a*b", "ab-extra"));
600        assert!(!matches("a*b", "xab"));
601    }
602
603    // ── FilteredToolExecutor additional tests ──────────────────────────────
604
605    #[tokio::test]
606    async fn deny_list_permits_unlisted_tool() {
607        let exec = FilteredToolExecutor::new(
608            stub_box(&["shell", "web"]),
609            ToolPolicy::DenyList(vec!["shell".into()]),
610        );
611        let call = ToolCall {
612            tool_id: "web".into(), // not in deny list → allowed
613            params: serde_json::Map::default(),
614        };
615        let res = exec.execute_tool_call_erased(&call).await.unwrap();
616        assert!(res.is_some());
617    }
618
619    #[test]
620    fn tool_definitions_filtered_by_deny_list() {
621        let exec = FilteredToolExecutor::new(
622            stub_box(&["shell", "web"]),
623            ToolPolicy::DenyList(vec!["shell".into()]),
624        );
625        let defs = exec.tool_definitions_erased();
626        assert_eq!(defs.len(), 1);
627        assert_eq!(defs[0].id, "web");
628    }
629
630    #[test]
631    fn tool_definitions_inherit_all_returns_all() {
632        let exec = FilteredToolExecutor::new(stub_box(&["shell", "web"]), ToolPolicy::InheritAll);
633        let defs = exec.tool_definitions_erased();
634        assert_eq!(defs.len(), 2);
635    }
636
637    // ── fenced-block detection tests (fix for #1432) ──────────────────────
638
639    #[tokio::test]
640    async fn fenced_block_matching_tag_is_blocked() {
641        // Executor has a FencedBlock("bash") tool; response contains ```bash block.
642        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
643        let res = exec.execute_erased("```bash\nls\n```").await;
644        assert!(
645            res.is_err(),
646            "actual fenced-block invocation must be blocked"
647        );
648    }
649
650    #[tokio::test]
651    async fn fenced_block_matching_tag_confirmed_is_blocked() {
652        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
653        let res = exec.execute_confirmed_erased("```bash\nls\n```").await;
654        assert!(
655            res.is_err(),
656            "actual fenced-block invocation (confirmed) must be blocked"
657        );
658    }
659
660    #[tokio::test]
661    async fn no_fenced_tools_plain_text_returns_ok_none() {
662        // No fenced-block tools registered → plain text must return Ok(None).
663        let exec = FilteredToolExecutor::new(stub_box(&["shell"]), ToolPolicy::InheritAll);
664        let res = exec.execute_erased("This is a plain text response.").await;
665        assert!(
666            res.unwrap().is_none(),
667            "plain text must not be treated as a tool call"
668        );
669    }
670
671    #[tokio::test]
672    async fn markdown_non_tool_fence_returns_ok_none() {
673        // Response has a ```rust fence but no FencedBlock tool with tag "rust" is registered.
674        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
675        let res = exec
676            .execute_erased("Here is some code:\n```rust\nfn main() {}\n```")
677            .await;
678        assert!(
679            res.unwrap().is_none(),
680            "non-tool code fence must not trigger blocking"
681        );
682    }
683
684    #[tokio::test]
685    async fn no_fenced_tools_plain_text_confirmed_returns_ok_none() {
686        let exec = FilteredToolExecutor::new(stub_box(&["shell"]), ToolPolicy::InheritAll);
687        let res = exec
688            .execute_confirmed_erased("Plain response without any fences.")
689            .await;
690        assert!(res.unwrap().is_none());
691    }
692
693    /// Regression test for #1432: fenced executor + plain text (no fences at all) must return
694    /// Ok(None) so the agent loop can break. Previously this returned Err(Blocked)
695    /// unconditionally, exhausting all sub-agent turns.
696    #[tokio::test]
697    async fn fenced_executor_plain_text_returns_ok_none() {
698        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
699        let res = exec
700            .execute_erased("Here is my analysis of the code. No shell commands needed.")
701            .await;
702        assert!(
703            res.unwrap().is_none(),
704            "plain text with fenced executor must not be treated as a tool call"
705        );
706    }
707
708    /// Unclosed fence (no closing ```) must not trigger blocking — it is not an executable
709    /// tool invocation. Verified by debugger as an intentional false-negative.
710    #[tokio::test]
711    async fn unclosed_fenced_block_returns_ok_none() {
712        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
713        let res = exec.execute_erased("```bash\nls -la\n").await;
714        assert!(
715            res.unwrap().is_none(),
716            "unclosed fenced block must not be treated as a tool invocation"
717        );
718    }
719
720    /// Multiple fenced blocks where one matches a registered tag — must block.
721    #[tokio::test]
722    async fn multiple_fences_one_matching_tag_is_blocked() {
723        let exec = FilteredToolExecutor::new(fenced_stub_box("bash"), ToolPolicy::InheritAll);
724        let response = "Here is an example:\n```python\nprint('hello')\n```\nAnd the fix:\n```bash\nrm -rf /tmp/old\n```";
725        let res = exec.execute_erased(response).await;
726        assert!(
727            res.is_err(),
728            "response containing a matching fenced block must be blocked"
729        );
730    }
731
732    // ── disallowed_tools (tools.except) tests ─────────────────────────────
733
734    #[tokio::test]
735    async fn disallowed_blocks_tool_from_allow_list() {
736        let exec = FilteredToolExecutor::with_disallowed(
737            stub_box(&["shell", "web"]),
738            ToolPolicy::AllowList(vec!["shell".into(), "web".into()]),
739            vec!["shell".into()],
740        );
741        let call = ToolCall {
742            tool_id: "shell".into(),
743            params: serde_json::Map::default(),
744        };
745        let res = exec.execute_tool_call_erased(&call).await;
746        assert!(
747            res.is_err(),
748            "disallowed tool must be blocked even if in allow list"
749        );
750    }
751
752    #[tokio::test]
753    async fn disallowed_allows_non_disallowed_tool() {
754        let exec = FilteredToolExecutor::with_disallowed(
755            stub_box(&["shell", "web"]),
756            ToolPolicy::AllowList(vec!["shell".into(), "web".into()]),
757            vec!["shell".into()],
758        );
759        let call = ToolCall {
760            tool_id: "web".into(),
761            params: serde_json::Map::default(),
762        };
763        let res = exec.execute_tool_call_erased(&call).await;
764        assert!(res.is_ok(), "non-disallowed tool must be allowed");
765    }
766
767    #[test]
768    fn disallowed_empty_list_no_change() {
769        let exec = FilteredToolExecutor::with_disallowed(
770            stub_box(&["shell", "web"]),
771            ToolPolicy::InheritAll,
772            vec![],
773        );
774        let defs = exec.tool_definitions_erased();
775        assert_eq!(defs.len(), 2);
776    }
777
778    #[test]
779    fn tool_definitions_filters_disallowed_tools() {
780        let exec = FilteredToolExecutor::with_disallowed(
781            stub_box(&["shell", "web", "dangerous"]),
782            ToolPolicy::InheritAll,
783            vec!["dangerous".into()],
784        );
785        let defs = exec.tool_definitions_erased();
786        assert_eq!(defs.len(), 2);
787        assert!(!defs.iter().any(|d| d.id == "dangerous"));
788    }
789
790    // ── #1184: PlanModeExecutor + disallowed_tools catalog test ───────────
791
792    #[test]
793    fn plan_mode_with_disallowed_excludes_from_catalog() {
794        // FilteredToolExecutor wrapping PlanModeExecutor must exclude disallowed tools from
795        // tool_definitions_erased(), verifying that deny-list is enforced in plan mode catalog.
796        let inner = Arc::new(PlanModeExecutor::new(stub_box(&["shell", "web"])));
797        let exec = FilteredToolExecutor::with_disallowed(
798            inner,
799            ToolPolicy::InheritAll,
800            vec!["shell".into()],
801        );
802        let defs = exec.tool_definitions_erased();
803        assert!(
804            !defs.iter().any(|d| d.id == "shell"),
805            "shell must be excluded from catalog"
806        );
807        assert!(
808            defs.iter().any(|d| d.id == "web"),
809            "web must remain in catalog"
810        );
811    }
812
813    // ── PlanModeExecutor tests ─────────────────────────────────────────────
814
815    #[tokio::test]
816    async fn plan_mode_blocks_execute_erased() {
817        let exec = PlanModeExecutor::new(stub_box(&["shell"]));
818        let res = exec.execute_erased("response").await;
819        assert!(res.is_err());
820    }
821
822    #[tokio::test]
823    async fn plan_mode_blocks_execute_confirmed_erased() {
824        let exec = PlanModeExecutor::new(stub_box(&["shell"]));
825        let res = exec.execute_confirmed_erased("response").await;
826        assert!(res.is_err());
827    }
828
829    #[tokio::test]
830    async fn plan_mode_blocks_tool_call() {
831        let exec = PlanModeExecutor::new(stub_box(&["shell"]));
832        let call = ToolCall {
833            tool_id: "shell".into(),
834            params: serde_json::Map::default(),
835        };
836        let res = exec.execute_tool_call_erased(&call).await;
837        assert!(res.is_err(), "plan mode must block all tool execution");
838    }
839
840    #[test]
841    fn plan_mode_exposes_real_tool_definitions() {
842        let exec = PlanModeExecutor::new(stub_box(&["shell", "web"]));
843        let defs = exec.tool_definitions_erased();
844        // Real tool catalog exposed — LLM can reference tools in its plan.
845        assert_eq!(defs.len(), 2);
846        assert!(defs.iter().any(|d| d.id == "shell"));
847        assert!(defs.iter().any(|d| d.id == "web"));
848    }
849
850    // ── filter_skills tests ────────────────────────────────────────────────
851
852    #[test]
853    fn filter_skills_empty_registry_returns_empty() {
854        let registry = zeph_skills::registry::SkillRegistry::load(&[] as &[&str]);
855        let filter = SkillFilter::default();
856        let result = filter_skills(&registry, &filter).unwrap();
857        assert!(result.is_empty());
858    }
859
860    #[test]
861    fn filter_skills_empty_include_passes_all() {
862        // Empty include list means "include everything".
863        // With an empty registry, result is still empty — logic is correct.
864        let registry = zeph_skills::registry::SkillRegistry::load(&[] as &[&str]);
865        let filter = SkillFilter {
866            include: vec![],
867            exclude: vec![],
868        };
869        let result = filter_skills(&registry, &filter).unwrap();
870        assert!(result.is_empty());
871    }
872
873    #[test]
874    fn filter_skills_double_star_pattern_is_error() {
875        let registry = zeph_skills::registry::SkillRegistry::load(&[] as &[&str]);
876        let filter = SkillFilter {
877            include: vec!["**".into()],
878            exclude: vec![],
879        };
880        let err = filter_skills(&registry, &filter).unwrap_err();
881        assert!(matches!(err, SubAgentError::Invalid(_)));
882    }
883
884    mod proptest_glob {
885        use proptest::prelude::*;
886
887        use super::{compile_glob, glob_match};
888
889        proptest! {
890            #![proptest_config(proptest::test_runner::Config::with_cases(500))]
891
892            /// glob_match must never panic for any valid (non-**) pattern and any name string.
893            #[test]
894            fn glob_match_never_panics(
895                pattern in "[a-z*-]{1,10}",
896                name in "[a-z-]{0,15}",
897            ) {
898                // Skip patterns with ** (those are compile errors by design).
899                if !pattern.contains("**")
900                    && let Ok(p) = compile_glob(&pattern)
901                {
902                    let _ = glob_match(&p, &name);
903                }
904            }
905
906            /// A literal pattern (no `*`) must match only exact strings.
907            #[test]
908            fn glob_literal_matches_only_exact(
909                name in "[a-z-]{1,10}",
910            ) {
911                // A literal pattern equal to `name` must match.
912                let p = compile_glob(&name).unwrap();
913                prop_assert!(glob_match(&p, &name));
914
915                // A different name must not match.
916                let other = format!("{name}-x");
917                prop_assert!(!glob_match(&p, &other));
918            }
919
920            /// The `*` pattern must match every input.
921            #[test]
922            fn glob_star_matches_everything(name in ".*") {
923                let p = compile_glob("*").unwrap();
924                prop_assert!(glob_match(&p, &name));
925            }
926        }
927    }
928}