zeph-tools 0.22.4

Tool executor trait with shell, web scrape, and composite executors for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Composite executor that chains two [`ToolExecutor`] implementations.

use crate::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput};
use crate::registry::ToolDef;

/// Chains two [`ToolExecutor`] implementations with first-match-wins dispatch.
///
/// For each method, `first` is tried first. If it returns `Ok(None)` (i.e. it does not
/// handle the input), `second` is tried. If `first` returns an `Err`, the error propagates
/// immediately without consulting `second`.
///
/// Use this to compose a chain of specialized executors at startup instead of a dynamic
/// `Vec<Box<dyn ...>>`. Nest multiple `CompositeExecutor`s to handle more than two backends.
///
/// Tool definitions from both executors are merged, with `first` taking precedence when
/// both define a tool with the same ID.
///
/// # Example
///
/// ```rust
/// use zeph_tools::{
///     CompositeExecutor, ShellExecutor, WebScrapeExecutor, ShellConfig, ScrapeConfig,
/// };
///
/// let shell = ShellExecutor::new(&ShellConfig::default());
/// let scrape = WebScrapeExecutor::new(&ScrapeConfig::default());
/// let executor = CompositeExecutor::new(shell, scrape);
/// // executor handles both bash blocks and scrape/fetch tool calls.
/// ```
#[derive(Debug)]
pub struct CompositeExecutor<A: ToolExecutor, B: ToolExecutor> {
    first: A,
    second: B,
}

impl<A: ToolExecutor, B: ToolExecutor> CompositeExecutor<A, B> {
    /// Create a new `CompositeExecutor` wrapping `first` and `second`.
    #[must_use]
    pub fn new(first: A, second: B) -> Self {
        Self { first, second }
    }
}

impl<A: ToolExecutor, B: ToolExecutor> ToolExecutor for CompositeExecutor<A, B> {
    async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        if let Some(output) = self.first.execute(response).await? {
            return Ok(Some(output));
        }
        self.second.execute(response).await
    }

    async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        if let Some(output) = self.first.execute_confirmed(response).await? {
            return Ok(Some(output));
        }
        self.second.execute_confirmed(response).await
    }

    fn tool_definitions(&self) -> Vec<ToolDef> {
        let mut defs = self.first.tool_definitions();
        let seen: std::collections::HashSet<String> =
            defs.iter().map(|d| d.id.to_string()).collect();
        for def in self.second.tool_definitions() {
            if !seen.contains(def.id.as_ref()) {
                defs.push(def);
            }
        }
        defs
    }

    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        if let Some(output) = self.first.execute_tool_call(call).await? {
            return Ok(Some(output));
        }
        self.second.execute_tool_call(call).await
    }

    async fn execute_tool_call_confirmed(
        &self,
        call: &ToolCall,
    ) -> Result<Option<ToolOutput>, ToolError> {
        if let Some(output) = self.first.execute_tool_call_confirmed(call).await? {
            return Ok(Some(output));
        }
        self.second.execute_tool_call_confirmed(call).await
    }

    fn is_tool_retryable(&self, tool_id: &str) -> bool {
        self.first.is_tool_retryable(tool_id) || self.second.is_tool_retryable(tool_id)
    }

    fn is_tool_speculatable(&self, tool_id: &str) -> bool {
        self.first.is_tool_speculatable(tool_id) || self.second.is_tool_speculatable(tool_id)
    }

    /// Return `true` when either inner executor requires confirmation for `call`.
    ///
    /// Mirrors the OR-forwarding used by [`Self::is_tool_retryable`] and
    /// [`Self::is_tool_speculatable`] — without this override the base
    /// [`ToolExecutor::requires_confirmation`] default (`false`) silently bypasses
    /// confirmation gating for any executor composed under `CompositeExecutor`. See #5900.
    fn requires_confirmation(&self, call: &ToolCall) -> bool {
        self.first.requires_confirmation(call) || self.second.requires_confirmation(call)
    }

    /// Forward the active skill's env injection to BOTH inner executors.
    ///
    /// The base [`ToolExecutor::set_skill_env`] is a no-op, so without this override the
    /// composition tree built in `agent_setup` silently swallows env injection — the
    /// underlying `ShellExecutor` never sees `GITHUB_TOKEN` etc. Each layer ignores the call
    /// if it does not own a `skill_env` slot; layers that do (e.g. `ShellExecutor`) update
    /// their state. See #3869.
    fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
        self.first.set_skill_env(env.clone());
        self.second.set_skill_env(env);
    }

    /// Forward the active skill's trust level to BOTH inner executors.
    ///
    /// Mirrors [`Self::set_skill_env`]: without this override, `TrustGateExecutor` never
    /// observes a non-`Trusted` level when composed under `CompositeExecutor`, leaving
    /// quarantine enforcement effectively bypassed. See #3869.
    fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
        self.first.set_effective_trust(level);
        self.second.set_effective_trust(level);
    }

    /// Delegate undo to the first inner executor that supports checkpoints.
    fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
        let result = self.first.checkpoint_undo(n);
        if result.supported {
            return result;
        }
        self.second.checkpoint_undo(n)
    }

    /// Delegate redo to the first inner executor that supports checkpoints.
    fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
        let result = self.first.checkpoint_redo();
        if result.supported {
            return result;
        }
        self.second.checkpoint_redo()
    }

    /// Delegate list to the first inner executor that supports checkpoints.
    fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
        let result = self.first.checkpoint_list();
        if result.supported {
            return result;
        }
        self.second.checkpoint_list()
    }
}

/// Wraps `Option<T>` so an executor that may fail to construct (disabled by config, or a
/// backend that fails to initialize — e.g. [`WebSearchExecutor::new`](crate::search::WebSearchExecutor::new)
/// returning `None`) can still occupy a fixed slot in a static [`CompositeExecutor`] chain.
///
/// When `None`, every method behaves as "not handled": empty tool definitions, `Ok(None)`
/// from the execute paths, unsupported checkpoints, not retryable/speculatable/confirmed.
/// This lets `build_base_executor_chain`'s concrete nested type stay fixed regardless of
/// whether the wrapped executor was actually constructed at wiring time.
#[derive(Debug)]
pub struct OptionalExecutor<T: ToolExecutor>(pub Option<T>);

impl<T: ToolExecutor> ToolExecutor for OptionalExecutor<T> {
    async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        match &self.0 {
            Some(inner) => inner.execute(response).await,
            None => Ok(None),
        }
    }

    async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        match &self.0 {
            Some(inner) => inner.execute_confirmed(response).await,
            None => Ok(None),
        }
    }

    fn tool_definitions(&self) -> Vec<ToolDef> {
        self.0
            .as_ref()
            .map(ToolExecutor::tool_definitions)
            .unwrap_or_default()
    }

    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        match &self.0 {
            Some(inner) => inner.execute_tool_call(call).await,
            None => Ok(None),
        }
    }

    async fn execute_tool_call_confirmed(
        &self,
        call: &ToolCall,
    ) -> Result<Option<ToolOutput>, ToolError> {
        match &self.0 {
            Some(inner) => inner.execute_tool_call_confirmed(call).await,
            None => Ok(None),
        }
    }

    fn is_tool_retryable(&self, tool_id: &str) -> bool {
        self.0
            .as_ref()
            .is_some_and(|inner| inner.is_tool_retryable(tool_id))
    }

    fn is_tool_speculatable(&self, tool_id: &str) -> bool {
        self.0
            .as_ref()
            .is_some_and(|inner| inner.is_tool_speculatable(tool_id))
    }

    fn requires_confirmation(&self, call: &ToolCall) -> bool {
        self.0
            .as_ref()
            .is_some_and(|inner| inner.requires_confirmation(call))
    }

    fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
        if let Some(inner) = &self.0 {
            inner.set_skill_env(env);
        }
    }

    fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
        if let Some(inner) = &self.0 {
            inner.set_effective_trust(level);
        }
    }

    fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
        self.0.as_ref().map_or_else(
            crate::executor::CheckpointActionResult::unsupported,
            |inner| inner.checkpoint_undo(n),
        )
    }

    fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
        self.0.as_ref().map_or_else(
            crate::executor::CheckpointActionResult::unsupported,
            ToolExecutor::checkpoint_redo,
        )
    }

    fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
        self.0
            .as_ref()
            .map(ToolExecutor::checkpoint_list)
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ToolName;
    use std::assert_matches;

    #[derive(Debug)]
    struct MatchingExecutor;
    impl ToolExecutor for MatchingExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(Some(ToolOutput {
                tool_name: ToolName::new("test"),
                summary: "matched".to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[derive(Debug)]
    struct NoMatchExecutor;
    impl ToolExecutor for NoMatchExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[derive(Debug)]
    struct ErrorExecutor;
    impl ToolExecutor for ErrorExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Err(ToolError::Blocked {
                command: "test".to_owned(),
            })
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[derive(Debug)]
    struct SecondExecutor;
    impl ToolExecutor for SecondExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(Some(ToolOutput {
                tool_name: ToolName::new("test"),
                summary: "second".to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[tokio::test]
    async fn first_matches_returns_first() {
        let composite = CompositeExecutor::new(MatchingExecutor, SecondExecutor);
        let result = composite.execute("anything").await.unwrap();
        assert_eq!(result.unwrap().summary, "matched");
    }

    #[tokio::test]
    async fn first_none_falls_through_to_second() {
        let composite = CompositeExecutor::new(NoMatchExecutor, SecondExecutor);
        let result = composite.execute("anything").await.unwrap();
        assert_eq!(result.unwrap().summary, "second");
    }

    #[tokio::test]
    async fn both_none_returns_none() {
        let composite = CompositeExecutor::new(NoMatchExecutor, NoMatchExecutor);
        let result = composite.execute("anything").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn first_error_propagates_without_trying_second() {
        let composite = CompositeExecutor::new(ErrorExecutor, SecondExecutor);
        let result = composite.execute("anything").await;
        assert_matches!(result, Err(ToolError::Blocked { .. }));
    }

    #[tokio::test]
    async fn second_error_propagates_when_first_none() {
        let composite = CompositeExecutor::new(NoMatchExecutor, ErrorExecutor);
        let result = composite.execute("anything").await;
        assert_matches!(result, Err(ToolError::Blocked { .. }));
    }

    #[tokio::test]
    async fn execute_confirmed_first_matches() {
        let composite = CompositeExecutor::new(MatchingExecutor, SecondExecutor);
        let result = composite.execute_confirmed("anything").await.unwrap();
        assert_eq!(result.unwrap().summary, "matched");
    }

    #[tokio::test]
    async fn execute_confirmed_falls_through() {
        let composite = CompositeExecutor::new(NoMatchExecutor, SecondExecutor);
        let result = composite.execute_confirmed("anything").await.unwrap();
        assert_eq!(result.unwrap().summary, "second");
    }

    #[test]
    fn composite_debug() {
        let composite = CompositeExecutor::new(MatchingExecutor, SecondExecutor);
        let debug = format!("{composite:?}");
        assert!(debug.contains("CompositeExecutor"));
    }

    /// Regression test for #5938: `execute_tool_call_confirmed` must reach the inner
    /// executor's own `execute_tool_call_confirmed` override, not fall through to the
    /// trait default (which re-dispatches via `execute_tool_call` and re-runs checks
    /// the confirmed path is meant to bypass).
    #[derive(Debug, Default)]
    struct ConfirmedSpy {
        confirmed_called: std::sync::Mutex<bool>,
        unconfirmed_called: std::sync::Mutex<bool>,
    }
    impl ToolExecutor for ConfirmedSpy {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        async fn execute_tool_call(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            *self.unconfirmed_called.lock().unwrap() = true;
            Ok(Some(ToolOutput {
                tool_name: call.tool_id.clone(),
                summary: "unconfirmed".to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }
        async fn execute_tool_call_confirmed(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            *self.confirmed_called.lock().unwrap() = true;
            Ok(Some(ToolOutput {
                tool_name: call.tool_id.clone(),
                summary: "confirmed".to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        fn checkpoint_undo(&self, _n: usize) -> crate::CheckpointActionResult {
            crate::CheckpointActionResult::unsupported()
        }
        fn checkpoint_redo(&self) -> crate::CheckpointActionResult {
            crate::CheckpointActionResult::unsupported()
        }
        fn checkpoint_list(&self) -> crate::CheckpointListResult {
            crate::CheckpointListResult::default()
        }
        fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
            false
        }
        fn requires_confirmation(&self, _call: &ToolCall) -> bool {
            false
        }
    }

    #[tokio::test]
    async fn execute_tool_call_confirmed_bypasses_unconfirmed_dispatch() {
        let spy = ConfirmedSpy::default();
        let composite = CompositeExecutor::new(spy, NoMatchExecutor);
        let call = ToolCall {
            tool_id: ToolName::new("read"),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,
            tool_call_id: String::new(),
            skill_name: None,
        };
        let result = composite
            .execute_tool_call_confirmed(&call)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(result.summary, "confirmed");
        assert!(
            *composite.first.confirmed_called.lock().unwrap(),
            "execute_tool_call_confirmed must reach the inner executor's confirmed override"
        );
        assert!(
            !*composite.first.unconfirmed_called.lock().unwrap(),
            "execute_tool_call_confirmed must NOT re-dispatch through execute_tool_call"
        );
    }

    #[tokio::test]
    async fn execute_tool_call_confirmed_falls_through_to_second() {
        let composite = CompositeExecutor::new(NoMatchExecutor, ConfirmedSpy::default());
        let call = ToolCall {
            tool_id: ToolName::new("read"),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,
            tool_call_id: String::new(),
            skill_name: None,
        };
        let result = composite
            .execute_tool_call_confirmed(&call)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(result.summary, "confirmed");
        assert!(*composite.second.confirmed_called.lock().unwrap());
    }

    #[derive(Debug)]
    struct FileToolExecutor;
    impl ToolExecutor for FileToolExecutor {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        async fn execute_tool_call(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            if call.tool_id == "read" || call.tool_id == "write" {
                Ok(Some(ToolOutput {
                    tool_name: call.tool_id.clone(),
                    summary: "file_handler".to_owned(),
                    blocks_executed: 1,
                    filter_stats: None,
                    diff: None,
                    streamed: false,
                    terminal_id: None,
                    locations: None,
                    raw_response: None,
                    claim_source: None,
                    ..Default::default()
                }))
            } else {
                Ok(None)
            }
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[derive(Debug)]
    struct ShellToolExecutor;
    impl ToolExecutor for ShellToolExecutor {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        async fn execute_tool_call(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            if call.tool_id == "bash" {
                Ok(Some(ToolOutput {
                    tool_name: ToolName::new("bash"),
                    summary: "shell_handler".to_owned(),
                    blocks_executed: 1,
                    filter_stats: None,
                    diff: None,
                    streamed: false,
                    terminal_id: None,
                    locations: None,
                    raw_response: None,
                    claim_source: None,
                    ..Default::default()
                }))
            } else {
                Ok(None)
            }
        }

        crate::tool_executor_no_inner_defaults!();
    }

    #[tokio::test]
    async fn tool_call_routes_to_file_executor() {
        let composite = CompositeExecutor::new(FileToolExecutor, ShellToolExecutor);
        let call = ToolCall {
            tool_id: ToolName::new("read"),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,

            tool_call_id: String::new(),
            skill_name: None,
        };
        let result = composite.execute_tool_call(&call).await.unwrap().unwrap();
        assert_eq!(result.summary, "file_handler");
    }

    #[tokio::test]
    async fn tool_call_routes_to_shell_executor() {
        let composite = CompositeExecutor::new(FileToolExecutor, ShellToolExecutor);
        let call = ToolCall {
            tool_id: ToolName::new("bash"),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,

            tool_call_id: String::new(),
            skill_name: None,
        };
        let result = composite.execute_tool_call(&call).await.unwrap().unwrap();
        assert_eq!(result.summary, "shell_handler");
    }

    #[tokio::test]
    async fn tool_call_unhandled_returns_none() {
        let composite = CompositeExecutor::new(FileToolExecutor, ShellToolExecutor);
        let call = ToolCall {
            tool_id: ToolName::new("unknown"),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,

            tool_call_id: String::new(),
            skill_name: None,
        };
        let result = composite.execute_tool_call(&call).await.unwrap();
        assert!(result.is_none());
    }

    /// Regression test for #3869: state-mutating setters MUST reach both inner executors,
    /// even across nested compositions. Prior to the fix, `set_skill_env` and
    /// `set_effective_trust` fell through to the default no-op `ToolExecutor` impls and
    /// were silently dropped at the `CompositeExecutor` boundary — breaking skill secret
    /// env injection (`x-requires-secrets`) and quarantine trust enforcement.
    mod state_forwarding {
        use super::*;
        use crate::SkillTrustLevel;
        use std::sync::Mutex;

        #[derive(Debug, Default)]
        struct SpyExecutor {
            last_env: Mutex<Option<std::collections::HashMap<String, String>>>,
            last_trust: Mutex<Option<SkillTrustLevel>>,
        }
        impl ToolExecutor for SpyExecutor {
            async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
                Ok(None)
            }
            fn set_skill_env(&self, env: Option<std::collections::HashMap<String, String>>) {
                *self.last_env.lock().unwrap() = env;
            }
            fn set_effective_trust(&self, level: SkillTrustLevel) {
                *self.last_trust.lock().unwrap() = Some(level);
            }

            crate::tool_executor_no_inner_defaults!();
        }

        /// Regression test for #5900: `CompositeExecutor::requires_confirmation` must
        /// OR-forward to both inner executors, mirroring `is_tool_retryable` and
        /// `is_tool_speculatable`. Before the fix it fell through to the base
        /// `ToolExecutor::requires_confirmation` default (`false`), silently dropping
        /// any confirmation requirement declared by either leaf.
        #[derive(Debug)]
        struct FixedConfirmation(bool);
        impl ToolExecutor for FixedConfirmation {
            async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
                Ok(None)
            }
            fn requires_confirmation(&self, _call: &ToolCall) -> bool {
                self.0
            }

            async fn execute_tool_call_confirmed(
                &self,
                call: &ToolCall,
            ) -> Result<Option<ToolOutput>, ToolError> {
                self.execute_tool_call(call).await
            }
            fn checkpoint_undo(&self, _n: usize) -> crate::CheckpointActionResult {
                crate::CheckpointActionResult::unsupported()
            }
            fn checkpoint_redo(&self) -> crate::CheckpointActionResult {
                crate::CheckpointActionResult::unsupported()
            }
            fn checkpoint_list(&self) -> crate::CheckpointListResult {
                crate::CheckpointListResult::default()
            }
            fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
                false
            }
        }

        fn confirmation_call() -> ToolCall {
            ToolCall {
                tool_id: ToolName::new("shell"),
                params: serde_json::Map::new(),
                caller_id: None,
                context: None,
                tool_call_id: String::new(),
                skill_name: None,
            }
        }

        #[test]
        fn requires_confirmation_false_when_both_leaves_false() {
            let composite =
                CompositeExecutor::new(FixedConfirmation(false), FixedConfirmation(false));
            assert!(!composite.requires_confirmation(&confirmation_call()));
        }

        #[test]
        fn requires_confirmation_true_when_first_leaf_true() {
            let composite =
                CompositeExecutor::new(FixedConfirmation(true), FixedConfirmation(false));
            assert!(composite.requires_confirmation(&confirmation_call()));
        }

        #[test]
        fn requires_confirmation_true_when_second_leaf_true() {
            let composite =
                CompositeExecutor::new(FixedConfirmation(false), FixedConfirmation(true));
            assert!(composite.requires_confirmation(&confirmation_call()));
        }

        #[test]
        fn requires_confirmation_or_forwards_across_nested_composition() {
            let nested = CompositeExecutor::new(FixedConfirmation(false), FixedConfirmation(true));
            let outer = CompositeExecutor::new(nested, FixedConfirmation(false));
            assert!(
                outer.requires_confirmation(&confirmation_call()),
                "a confirmation requirement on a nested leaf must reach the outer composite"
            );
        }

        #[test]
        fn set_skill_env_reaches_both_inner_executors_in_nested_composition() {
            // Mirrors the production wiring shape: a tree of CompositeExecutor with
            // multiple leaves. All leaves must observe the call.
            let leaf_a = SpyExecutor::default();
            let leaf_b = SpyExecutor::default();
            let leaf_c = SpyExecutor::default();
            let nested = CompositeExecutor::new(leaf_a, leaf_b);
            let outer = CompositeExecutor::new(nested, leaf_c);

            let mut env = std::collections::HashMap::new();
            env.insert("GITHUB_TOKEN".to_owned(), "tok".to_owned());
            outer.set_skill_env(Some(env.clone()));

            // first.first (leaf_a)
            assert_eq!(
                outer.first.first.last_env.lock().unwrap().as_ref(),
                Some(&env)
            );
            // first.second (leaf_b)
            assert_eq!(
                outer.first.second.last_env.lock().unwrap().as_ref(),
                Some(&env)
            );
            // second (leaf_c)
            assert_eq!(outer.second.last_env.lock().unwrap().as_ref(), Some(&env));
        }

        #[test]
        fn set_effective_trust_reaches_both_inner_executors_in_nested_composition() {
            let leaf_a = SpyExecutor::default();
            let leaf_b = SpyExecutor::default();
            let outer = CompositeExecutor::new(leaf_a, leaf_b);

            outer.set_effective_trust(SkillTrustLevel::Quarantined);

            assert_eq!(
                *outer.first.last_trust.lock().unwrap(),
                Some(SkillTrustLevel::Quarantined)
            );
            assert_eq!(
                *outer.second.last_trust.lock().unwrap(),
                Some(SkillTrustLevel::Quarantined)
            );
        }
    }

    mod optional_executor {
        use super::*;

        #[tokio::test]
        async fn none_execute_returns_ok_none() {
            let wrapped: OptionalExecutor<MatchingExecutor> = OptionalExecutor(None);
            assert!(wrapped.execute("anything").await.unwrap().is_none());
        }

        #[tokio::test]
        async fn some_execute_delegates_to_inner() {
            let wrapped = OptionalExecutor(Some(MatchingExecutor));
            let result = wrapped.execute("anything").await.unwrap();
            assert_eq!(result.unwrap().summary, "matched");
        }

        #[tokio::test]
        async fn none_execute_tool_call_returns_ok_none() {
            let wrapped: OptionalExecutor<FileToolExecutor> = OptionalExecutor(None);
            let call = ToolCall {
                tool_id: ToolName::new("read"),
                params: serde_json::Map::new(),
                caller_id: None,
                context: None,
                tool_call_id: String::new(),
                skill_name: None,
            };
            assert!(wrapped.execute_tool_call(&call).await.unwrap().is_none());
        }

        #[tokio::test]
        async fn some_execute_tool_call_delegates_to_inner() {
            let wrapped = OptionalExecutor(Some(FileToolExecutor));
            let call = ToolCall {
                tool_id: ToolName::new("read"),
                params: serde_json::Map::new(),
                caller_id: None,
                context: None,
                tool_call_id: String::new(),
                skill_name: None,
            };
            let result = wrapped.execute_tool_call(&call).await.unwrap();
            assert_eq!(result.unwrap().summary, "file_handler");
        }

        #[test]
        fn none_tool_definitions_is_empty() {
            let wrapped: OptionalExecutor<MatchingExecutor> = OptionalExecutor(None);
            assert!(wrapped.tool_definitions().is_empty());
        }

        #[test]
        fn none_checkpoint_undo_unsupported() {
            let wrapped: OptionalExecutor<MatchingExecutor> = OptionalExecutor(None);
            assert!(!wrapped.checkpoint_undo(1).supported);
            assert!(!wrapped.checkpoint_redo().supported);
            assert!(!wrapped.checkpoint_list().supported);
        }

        #[test]
        fn none_not_retryable_or_speculatable() {
            let wrapped: OptionalExecutor<MatchingExecutor> = OptionalExecutor(None);
            assert!(!wrapped.is_tool_retryable("anything"));
            assert!(!wrapped.is_tool_speculatable("anything"));
        }

        #[test]
        fn none_requires_confirmation_false() {
            let wrapped: OptionalExecutor<MatchingExecutor> = OptionalExecutor(None);
            let call = ToolCall {
                tool_id: ToolName::new("anything"),
                params: serde_json::Map::new(),
                caller_id: None,
                context: None,
                tool_call_id: String::new(),
                skill_name: None,
            };
            assert!(!wrapped.requires_confirmation(&call));
        }
    }
}