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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! `AdversarialPolicyGateExecutor`: wraps an inner `ToolExecutor` and runs an LLM-based
//! policy check before delegating any structured tool call.
//!
//! Wiring order (outermost first):
//!   `PolicyGateExecutor` → `AdversarialPolicyGateExecutor` → `TrustGateExecutor` → ...
//!
//! Per CRIT-04 recommendation: declarative `PolicyGateExecutor` is outermost.
//! Adversarial gate only fires for calls that pass declarative policy — no duplication.
//!
//! Per CRIT-06: ALL `ToolExecutor` trait methods are delegated to `self.inner`.
//! Per CRIT-01: fail behavior (allow/deny on LLM error) is controlled by `fail_open` config.
//! Per CRIT-11: params are sanitized and wrapped in code fences before LLM call.

use std::sync::Arc;

use crate::adversarial_policy::{PolicyDecision, PolicyLlmClient, PolicyValidator};
use crate::audit::{AuditEntry, AuditLogger, AuditResult, chrono_now};
use crate::executor::{ClaimSource, ToolCall, ToolError, ToolExecutor, ToolOutput};
use crate::registry::ToolDef;

/// Wraps an inner `ToolExecutor`, running an LLM-based adversarial policy check
/// before delegating structured tool calls.
///
/// Only `execute_tool_call` and `execute_tool_call_confirmed` are intercepted.
/// Legacy `execute` / `execute_confirmed` bypass the check (no structured `tool_id`).
pub struct AdversarialPolicyGateExecutor<T: ToolExecutor> {
    inner: T,
    validator: Arc<PolicyValidator>,
    llm: Arc<dyn PolicyLlmClient>,
    audit: Option<Arc<AuditLogger>>,
}

impl<T: ToolExecutor + std::fmt::Debug> std::fmt::Debug for AdversarialPolicyGateExecutor<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AdversarialPolicyGateExecutor")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<T: ToolExecutor> AdversarialPolicyGateExecutor<T> {
    /// Create a new `AdversarialPolicyGateExecutor`.
    #[must_use]
    pub fn new(inner: T, validator: Arc<PolicyValidator>, llm: Arc<dyn PolicyLlmClient>) -> Self {
        Self {
            inner,
            validator,
            llm,
            audit: None,
        }
    }

    /// Attach an audit logger.
    #[must_use]
    pub fn with_audit(mut self, audit: Arc<AuditLogger>) -> Self {
        self.audit = Some(audit);
        self
    }

    async fn check_policy(&self, call: &ToolCall) -> Result<(), ToolError> {
        tracing::info!(
            tool = %call.tool_id,
            status_spinner = true,
            "Validating tool policy\u{2026}"
        );

        let decision = self
            .validator
            .validate(call.tool_id.as_str(), &call.params, self.llm.as_ref())
            .await;

        match decision {
            PolicyDecision::Allow => {
                tracing::debug!(tool = %call.tool_id, "adversarial policy: allow");
                self.write_audit(call, "allow", AuditResult::Success, None)
                    .await;
                Ok(())
            }
            PolicyDecision::Deny { reason } => {
                tracing::warn!(
                    tool = %call.tool_id,
                    reason = %reason,
                    "adversarial policy: deny"
                );
                self.write_audit(
                    call,
                    &format!("deny:{reason}"),
                    AuditResult::Blocked {
                        reason: reason.clone(),
                    },
                    None,
                )
                .await;
                // MED-03: do NOT surface the LLM reason to the main LLM.
                Err(ToolError::Blocked {
                    command: "[adversarial] Tool call denied by policy".to_owned(),
                })
            }
            PolicyDecision::Error { message, timed_out } => {
                tracing::warn!(
                    tool = %call.tool_id,
                    error = %message,
                    timed_out,
                    fail_open = self.validator.fail_open(),
                    "adversarial policy: LLM error"
                );
                if self.validator.fail_open() {
                    self.write_audit(
                        call,
                        &format!("error:{message}"),
                        AuditResult::Success,
                        None,
                    )
                    .await;
                    Ok(())
                } else {
                    // Operator-facing audit reason distinguishes a timeout (config/latency
                    // problem, actionable) from a genuine LLM/network error — see #5870.
                    // The main LLM never sees this: `ToolError::Blocked` below stays generic.
                    let reason = if timed_out {
                        format!(
                            "adversarial policy check timed out (fail-closed): {message}\
                             raise [tools.adversarial_policy].timeout_ms or point policy_provider \
                             at a faster model"
                        )
                    } else {
                        format!("adversarial policy LLM error (fail-closed): {message}")
                    };
                    self.write_audit(
                        call,
                        &format!("error:{message}"),
                        AuditResult::Blocked { reason },
                        None,
                    )
                    .await;
                    Err(ToolError::Blocked {
                        command: "[adversarial] Tool call denied: policy check failed".to_owned(),
                    })
                }
            }
        }
    }

    async fn write_audit(
        &self,
        call: &ToolCall,
        decision: &str,
        result: AuditResult,
        claim_source: Option<ClaimSource>,
    ) {
        let Some(audit) = &self.audit else { return };
        let entry = AuditEntry {
            source_kind: None,
            trust_level: None,
            timestamp: chrono_now(),
            tool: call.tool_id.clone(),
            command: params_summary(&call.params),
            result,
            duration_ms: 0,
            error_category: None,
            error_domain: None,
            error_phase: None,
            claim_source,
            mcp_server_id: None,
            injection_flagged: false,
            embedding_anomalous: false,
            cross_boundary_mcp_to_acp: false,
            adversarial_policy_decision: Some(decision.to_owned()),
            exit_code: None,
            truncated: false,
            caller_id: call.caller_id.clone(),
            skill_name: call.skill_name.clone(),
            policy_match: None,
            correlation_id: None,
            vigil_risk: None,
            execution_env: None,
            resolved_cwd: None,
            scope_at_definition: None,
            scope_at_dispatch: None,
        };
        audit.log(&entry).await;
    }
}

impl<T: ToolExecutor> ToolExecutor for AdversarialPolicyGateExecutor<T> {
    // Legacy dispatch bypasses adversarial check — no structured tool_id available.
    async fn execute(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        self.inner.execute(response).await
    }

    async fn execute_confirmed(&self, response: &str) -> Result<Option<ToolOutput>, ToolError> {
        self.inner.execute_confirmed(response).await
    }

    // CRIT-06: delegate all pass-through methods to inner executor.
    fn tool_definitions(&self) -> Vec<ToolDef> {
        self.inner.tool_definitions()
    }

    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        self.check_policy(call).await?;
        let output = self.inner.execute_tool_call(call).await?;
        if let Some(ref out) = output {
            self.write_audit(
                call,
                "allow:executed",
                AuditResult::Success,
                out.claim_source,
            )
            .await;
        }
        Ok(output)
    }

    // MED-04: policy also enforced on confirmed calls.
    async fn execute_tool_call_confirmed(
        &self,
        call: &ToolCall,
    ) -> Result<Option<ToolOutput>, ToolError> {
        self.check_policy(call).await?;
        let output = self.inner.execute_tool_call_confirmed(call).await?;
        if let Some(ref out) = output {
            self.write_audit(
                call,
                "allow:executed",
                AuditResult::Success,
                out.claim_source,
            )
            .await;
        }
        Ok(output)
    }

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

    fn set_effective_trust(&self, level: crate::SkillTrustLevel) {
        self.inner.set_effective_trust(level);
    }

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

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

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

    fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
        self.inner.checkpoint_undo(n)
    }

    fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
        self.inner.checkpoint_redo()
    }

    fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
        self.inner.checkpoint_list()
    }
}

fn params_summary(params: &serde_json::Map<String, serde_json::Value>) -> String {
    let s = serde_json::to_string(params).unwrap_or_default();
    if s.chars().count() > 500 {
        let truncated: String = s.chars().take(497).collect();
        format!("{truncated}\u{2026}")
    } else {
        s
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    use super::*;
    use crate::adversarial_policy::{PolicyMessage, PolicyValidator};
    use crate::executor::{ToolCall, ToolOutput};

    // --- Mock LLM client ---

    struct MockLlm {
        response: String,
        call_count: Arc<AtomicUsize>,
    }

    impl MockLlm {
        fn new(response: impl Into<String>) -> (Arc<AtomicUsize>, Self) {
            let counter = Arc::new(AtomicUsize::new(0));
            let client = Self {
                response: response.into(),
                call_count: Arc::clone(&counter),
            };
            (counter, client)
        }
    }

    impl PolicyLlmClient for MockLlm {
        fn chat<'a>(
            &'a self,
            _messages: &'a [PolicyMessage],
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
            self.call_count.fetch_add(1, Ordering::SeqCst);
            let resp = self.response.clone();
            Box::pin(async move { Ok(resp) })
        }
    }

    // --- Mock inner executor ---

    #[derive(Debug)]
    struct MockInner {
        call_count: Arc<AtomicUsize>,
    }

    impl MockInner {
        fn new() -> (Arc<AtomicUsize>, Self) {
            let counter = Arc::new(AtomicUsize::new(0));
            let exec = Self {
                call_count: Arc::clone(&counter),
            };
            (counter, exec)
        }
    }

    impl ToolExecutor for MockInner {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }

        async fn execute_tool_call(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            self.call_count.fetch_add(1, Ordering::SeqCst);
            Ok(Some(ToolOutput {
                tool_name: call.tool_id.clone(),
                summary: "ok".into(),
                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!();
    }

    fn make_call(tool_id: &str) -> ToolCall {
        ToolCall {
            tool_id: tool_id.into(),
            params: serde_json::Map::new(),
            caller_id: None,
            context: None,

            tool_call_id: String::new(),
            skill_name: None,
        }
    }

    fn make_validator(fail_open: bool) -> Arc<PolicyValidator> {
        Arc::new(PolicyValidator::new(
            vec!["test policy".to_owned()],
            Duration::from_millis(500),
            fail_open,
            Vec::new(),
        ))
    }

    #[tokio::test]
    async fn allow_path_delegates_to_inner() {
        let (llm_count, llm) = MockLlm::new("ALLOW");
        let (inner_count, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let result = gate.execute_tool_call(&make_call("shell")).await;
        assert!(result.is_ok());
        assert_eq!(
            llm_count.load(Ordering::SeqCst),
            1,
            "LLM must be called once"
        );
        assert_eq!(
            inner_count.load(Ordering::SeqCst),
            1,
            "inner executor must be called on allow"
        );
    }

    #[tokio::test]
    async fn deny_path_blocks_and_does_not_call_inner() {
        let (llm_count, llm) = MockLlm::new("DENY: unsafe command");
        let (inner_count, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let result = gate.execute_tool_call(&make_call("shell")).await;
        assert_matches!(result, Err(ToolError::Blocked { .. }));
        assert_eq!(llm_count.load(Ordering::SeqCst), 1);
        assert_eq!(
            inner_count.load(Ordering::SeqCst),
            0,
            "inner must NOT be called on deny"
        );
    }

    #[tokio::test]
    async fn error_message_is_opaque() {
        // MED-03: error returned to main LLM must not contain the LLM denial reason.
        let (_, llm) = MockLlm::new("DENY: secret internal policy rule XYZ");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let err = gate
            .execute_tool_call(&make_call("shell"))
            .await
            .unwrap_err();
        if let ToolError::Blocked { command } = err {
            assert!(
                !command.contains("secret internal policy rule XYZ"),
                "LLM denial reason must not leak to main LLM"
            );
        } else {
            panic!("expected Blocked error");
        }
    }

    #[tokio::test]
    async fn fail_closed_blocks_on_llm_error() {
        struct FailingLlm;
        impl PolicyLlmClient for FailingLlm {
            fn chat<'a>(
                &'a self,
                _: &'a [PolicyMessage],
            ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
                Box::pin(async { Err("network error".to_owned()) })
            }
        }

        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(
            inner,
            make_validator(false), // fail_open = false
            Arc::new(FailingLlm),
        );
        let err = gate
            .execute_tool_call(&make_call("shell"))
            .await
            .unwrap_err();
        // #5870/MED-03: the timed_out=false (genuine error) branch must produce the exact
        // same LLM-visible message as the timed_out=true branch (see
        // audit_entry_distinguishes_timeout_from_generic_error) — the main LLM must never be
        // able to distinguish an infra error from a policy error via this string.
        assert_matches!(
            err,
            ToolError::Blocked { ref command } if command == "[adversarial] Tool call denied: policy check failed"
        );
    }

    #[tokio::test]
    async fn fail_open_allows_on_llm_error() {
        struct FailingLlm;
        impl PolicyLlmClient for FailingLlm {
            fn chat<'a>(
                &'a self,
                _: &'a [PolicyMessage],
            ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
                Box::pin(async { Err("network error".to_owned()) })
            }
        }

        let (inner_count, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(
            inner,
            make_validator(true), // fail_open = true
            Arc::new(FailingLlm),
        );
        let result = gate.execute_tool_call(&make_call("shell")).await;
        assert!(result.is_ok(), "fail-open must allow on LLM error");
        assert_eq!(inner_count.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn confirmed_also_enforces_policy() {
        let (_, llm) = MockLlm::new("DENY: blocked");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let result = gate.execute_tool_call_confirmed(&make_call("shell")).await;
        assert!(
            matches!(result, Err(ToolError::Blocked { .. })),
            "confirmed path must also enforce adversarial policy"
        );
    }

    #[tokio::test]
    async fn legacy_execute_bypasses_policy() {
        let (llm_count, llm) = MockLlm::new("DENY: anything");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let result = gate.execute("```shell\necho hi\n```").await;
        assert!(
            result.is_ok(),
            "legacy execute must bypass adversarial policy"
        );
        assert_eq!(
            llm_count.load(Ordering::SeqCst),
            0,
            "LLM must NOT be called for legacy dispatch"
        );
    }

    #[tokio::test]
    async fn delegation_set_skill_env() {
        // Verify that set_skill_env reaches the inner executor without panic.
        let (_, llm) = MockLlm::new("ALLOW");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        gate.set_skill_env(None);
    }

    #[tokio::test]
    async fn delegation_set_effective_trust() {
        use crate::SkillTrustLevel;
        let (_, llm) = MockLlm::new("ALLOW");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        gate.set_effective_trust(SkillTrustLevel::Trusted);
    }

    #[tokio::test]
    async fn delegation_is_tool_retryable() {
        let (_, llm) = MockLlm::new("ALLOW");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let retryable = gate.is_tool_retryable("shell");
        assert!(!retryable, "MockInner returns false for is_tool_retryable");
    }

    /// Regression test for #5900: `is_tool_speculatable` must be forwarded to `self.inner`.
    /// Before the fix it fell through to the base `ToolExecutor` default (`false`) regardless
    /// of the inner executor's actual value.
    #[derive(Debug)]
    struct SpeculatableInner;
    impl ToolExecutor for SpeculatableInner {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
            true
        }

        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::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult::unsupported()
        }
        fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult::unsupported()
        }
        fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
            crate::executor::CheckpointListResult::default()
        }
        fn requires_confirmation(&self, _call: &ToolCall) -> bool {
            false
        }
    }

    #[tokio::test]
    async fn delegation_is_tool_speculatable() {
        let (_, llm) = MockLlm::new("ALLOW");
        let gate = AdversarialPolicyGateExecutor::new(
            SpeculatableInner,
            make_validator(false),
            Arc::new(llm),
        );
        assert!(
            gate.is_tool_speculatable("fetch"),
            "is_tool_speculatable must be forwarded to the inner executor's non-default value"
        );
    }

    /// Regression test for #5931: `requires_confirmation` must be forwarded to `self.inner`.
    /// Before the fix it fell through to the base `ToolExecutor` default (`false`) regardless
    /// of the inner executor's actual policy.
    #[derive(Debug)]
    struct ConfirmationRequiredInner;
    impl ToolExecutor for ConfirmationRequiredInner {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        fn requires_confirmation(&self, _call: &ToolCall) -> bool {
            true
        }

        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::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult::unsupported()
        }
        fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult::unsupported()
        }
        fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
            crate::executor::CheckpointListResult::default()
        }
        fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
            false
        }
    }

    #[tokio::test]
    async fn delegation_requires_confirmation() {
        let (_, llm) = MockLlm::new("ALLOW");
        let gate = AdversarialPolicyGateExecutor::new(
            ConfirmationRequiredInner,
            make_validator(false),
            Arc::new(llm),
        );
        assert!(
            gate.requires_confirmation(&make_call("shell")),
            "requires_confirmation must be forwarded to the inner executor's non-default value"
        );
    }

    #[derive(Debug)]
    struct CheckpointingInner;

    impl ToolExecutor for CheckpointingInner {
        async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        async fn execute_tool_call(&self, _: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }
        fn checkpoint_undo(&self, n: usize) -> crate::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult {
                supported: true,
                message: "stub".into(),
                reverted_commands: n,
                ..Default::default()
            }
        }
        fn checkpoint_redo(&self) -> crate::executor::CheckpointActionResult {
            crate::executor::CheckpointActionResult {
                supported: true,
                message: "stub".into(),
                ..Default::default()
            }
        }
        fn checkpoint_list(&self) -> crate::executor::CheckpointListResult {
            crate::executor::CheckpointListResult {
                supported: true,
                ..Default::default()
            }
        }

        async fn execute_tool_call_confirmed(
            &self,
            call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            self.execute_tool_call(call).await
        }
        fn is_tool_speculatable(&self, _tool_id: &str) -> bool {
            false
        }
        fn requires_confirmation(&self, _call: &ToolCall) -> bool {
            false
        }
    }

    #[tokio::test]
    async fn delegation_checkpoint_methods() {
        let (_, llm) = MockLlm::new("ALLOW");
        let gate = AdversarialPolicyGateExecutor::new(
            CheckpointingInner,
            make_validator(false),
            Arc::new(llm),
        );
        let undo_result = gate.checkpoint_undo(7);
        assert!(undo_result.supported);
        assert_eq!(
            undo_result.reverted_commands, 7,
            "n must be forwarded, not hardcoded"
        );
        assert!(gate.checkpoint_redo().supported);
        assert!(gate.checkpoint_list().supported);
    }

    #[tokio::test]
    async fn delegation_tool_definitions() {
        let (_, llm) = MockLlm::new("ALLOW");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm));
        let defs = gate.tool_definitions();
        assert!(defs.is_empty(), "MockInner returns empty tool definitions");
    }

    #[tokio::test]
    async fn audit_entry_contains_adversarial_decision() {
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let log_path = dir.path().join("audit.log");
        let audit_config = crate::config::AuditConfig {
            enabled: true,
            destination: crate::config::AuditDestination::File(log_path.clone()),
            ..Default::default()
        };
        let audit_logger = Arc::new(
            crate::audit::AuditLogger::from_config(&audit_config, false)
                .await
                .unwrap(),
        );

        let (_, llm) = MockLlm::new("ALLOW");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm))
            .with_audit(Arc::clone(&audit_logger));

        gate.execute_tool_call(&make_call("shell")).await.unwrap();

        let content = tokio::fs::read_to_string(&log_path).await.unwrap();
        assert!(
            content.contains("adversarial_policy_decision"),
            "audit entry must contain adversarial_policy_decision field"
        );
        assert!(
            content.contains("\"allow\""),
            "allow decision must be recorded"
        );
    }

    #[tokio::test]
    async fn audit_entry_deny_contains_decision() {
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let log_path = dir.path().join("audit.log");
        let audit_config = crate::config::AuditConfig {
            enabled: true,
            destination: crate::config::AuditDestination::File(log_path.clone()),
            ..Default::default()
        };
        let audit_logger = Arc::new(
            crate::audit::AuditLogger::from_config(&audit_config, false)
                .await
                .unwrap(),
        );

        let (_, llm) = MockLlm::new("DENY: test denial");
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, make_validator(false), Arc::new(llm))
            .with_audit(Arc::clone(&audit_logger));

        let _ = gate.execute_tool_call(&make_call("shell")).await;

        let content = tokio::fs::read_to_string(&log_path).await.unwrap();
        assert!(
            content.contains("deny:"),
            "deny decision must be recorded in audit"
        );
    }

    #[tokio::test]
    async fn audit_entry_distinguishes_timeout_from_generic_error() {
        // #5870: the operator-facing audit reason must tell a policy-LLM timeout apart
        // from a genuine deny/error, with an actionable hint — while the LLM-visible
        // ToolError stays generic (see error_message_is_opaque).
        use tempfile::TempDir;

        struct SlowLlm;
        impl PolicyLlmClient for SlowLlm {
            fn chat<'a>(
                &'a self,
                _: &'a [PolicyMessage],
            ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
                Box::pin(async {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                    Ok("ALLOW".to_owned())
                })
            }
        }

        let dir = TempDir::new().unwrap();
        let log_path = dir.path().join("audit.log");
        let audit_config = crate::config::AuditConfig {
            enabled: true,
            destination: crate::config::AuditDestination::File(log_path.clone()),
            ..Default::default()
        };
        let audit_logger = Arc::new(
            crate::audit::AuditLogger::from_config(&audit_config, false)
                .await
                .unwrap(),
        );

        let validator = Arc::new(PolicyValidator::new(
            vec!["test policy".to_owned()],
            Duration::from_millis(20), // shorter than SlowLlm's 200ms response
            false,                     // fail-closed
            Vec::new(),
        ));
        let (_, inner) = MockInner::new();
        let gate = AdversarialPolicyGateExecutor::new(inner, validator, Arc::new(SlowLlm))
            .with_audit(Arc::clone(&audit_logger));

        let err = gate
            .execute_tool_call(&make_call("shell"))
            .await
            .unwrap_err();

        // LLM-visible error stays generic (MED-03).
        assert_matches!(
            err,
            ToolError::Blocked { ref command } if command == "[adversarial] Tool call denied: policy check failed"
        );

        let content = tokio::fs::read_to_string(&log_path).await.unwrap();
        assert!(
            content.contains("timed out"),
            "operator-facing audit reason must say the check timed out, not a generic error: {content}"
        );
        assert!(
            content.contains("timeout_ms"),
            "operator-facing audit reason must hint at raising timeout_ms: {content}"
        );
    }

    #[tokio::test]
    async fn audit_entry_propagates_claim_source() {
        use tempfile::TempDir;

        #[derive(Debug)]
        struct InnerWithClaimSource;

        impl ToolExecutor for InnerWithClaimSource {
            async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
                Ok(None)
            }

            async fn execute_tool_call(
                &self,
                call: &ToolCall,
            ) -> Result<Option<ToolOutput>, ToolError> {
                Ok(Some(ToolOutput {
                    tool_name: call.tool_id.clone(),
                    summary: "ok".into(),
                    blocks_executed: 1,
                    filter_stats: None,
                    diff: None,
                    streamed: false,
                    terminal_id: None,
                    locations: None,
                    raw_response: None,
                    claim_source: Some(crate::executor::ClaimSource::Shell),
                    ..Default::default()
                }))
            }

            crate::tool_executor_no_inner_defaults!();
        }

        let dir = TempDir::new().unwrap();
        let log_path = dir.path().join("audit.log");
        let audit_config = crate::config::AuditConfig {
            enabled: true,
            destination: crate::config::AuditDestination::File(log_path.clone()),
            ..Default::default()
        };
        let audit_logger = Arc::new(
            crate::audit::AuditLogger::from_config(&audit_config, false)
                .await
                .unwrap(),
        );

        let (_, llm) = MockLlm::new("ALLOW");
        let gate = AdversarialPolicyGateExecutor::new(
            InnerWithClaimSource,
            make_validator(false),
            Arc::new(llm),
        )
        .with_audit(Arc::clone(&audit_logger));

        gate.execute_tool_call(&make_call("shell")).await.unwrap();

        let content = tokio::fs::read_to_string(&log_path).await.unwrap();
        assert!(
            content.contains("\"shell\""),
            "claim_source must be propagated into the post-execution audit entry"
        );
    }
}