zeph-tools 0.18.2

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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::fmt;

/// Data for rendering file diffs in the TUI.
#[derive(Debug, Clone)]
pub struct DiffData {
    pub file_path: String,
    pub old_content: String,
    pub new_content: String,
}

/// Structured tool invocation from LLM.
#[derive(Debug, Clone)]
pub struct ToolCall {
    pub tool_id: String,
    pub params: serde_json::Map<String, serde_json::Value>,
}

/// Cumulative filter statistics for a single tool execution.
#[derive(Debug, Clone, Default)]
pub struct FilterStats {
    pub raw_chars: usize,
    pub filtered_chars: usize,
    pub raw_lines: usize,
    pub filtered_lines: usize,
    pub confidence: Option<crate::FilterConfidence>,
    pub command: Option<String>,
    pub kept_lines: Vec<usize>,
}

impl FilterStats {
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn savings_pct(&self) -> f64 {
        if self.raw_chars == 0 {
            return 0.0;
        }
        (1.0 - self.filtered_chars as f64 / self.raw_chars as f64) * 100.0
    }

    #[must_use]
    pub fn estimated_tokens_saved(&self) -> usize {
        self.raw_chars.saturating_sub(self.filtered_chars) / 4
    }

    #[must_use]
    pub fn format_inline(&self, tool_name: &str) -> String {
        let cmd_label = self
            .command
            .as_deref()
            .map(|c| {
                let trimmed = c.trim();
                if trimmed.len() > 60 {
                    format!(" `{}…`", &trimmed[..57])
                } else {
                    format!(" `{trimmed}`")
                }
            })
            .unwrap_or_default();
        format!(
            "[{tool_name}]{cmd_label} {} lines \u{2192} {} lines, {:.1}% filtered",
            self.raw_lines,
            self.filtered_lines,
            self.savings_pct()
        )
    }
}

/// Provenance of a tool execution result.
///
/// Set by each executor at `ToolOutput` construction time. Used by the sanitizer bridge
/// in `zeph-core` to select the appropriate `ContentSourceKind` and trust level.
/// `None` means the source is unspecified (pass-through code, mocks, tests).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaimSource {
    /// Local shell command execution.
    Shell,
    /// Local file system read/write.
    FileSystem,
    /// HTTP web scrape.
    WebScrape,
    /// MCP server tool response.
    Mcp,
    /// A2A agent message.
    A2a,
    /// Code search (LSP or semantic).
    CodeSearch,
    /// Agent diagnostics (internal).
    Diagnostics,
    /// Memory retrieval (semantic search).
    Memory,
}

/// Structured result from tool execution.
#[derive(Debug, Clone)]
pub struct ToolOutput {
    pub tool_name: String,
    pub summary: String,
    pub blocks_executed: u32,
    pub filter_stats: Option<FilterStats>,
    pub diff: Option<DiffData>,
    /// Whether this tool already streamed its output via `ToolEvent` channel.
    pub streamed: bool,
    /// Terminal ID when the tool was executed via IDE terminal (ACP terminal/* protocol).
    pub terminal_id: Option<String>,
    /// File paths touched by this tool call, for IDE follow-along (e.g. `ToolCallLocation`).
    pub locations: Option<Vec<String>>,
    /// Structured tool response payload for ACP intermediate `tool_call_update` notifications.
    pub raw_response: Option<serde_json::Value>,
    /// Provenance of this tool result. Set by the executor at construction time.
    /// `None` in pass-through wrappers, mocks, and tests.
    pub claim_source: Option<ClaimSource>,
}

impl fmt::Display for ToolOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.summary)
    }
}

pub const MAX_TOOL_OUTPUT_CHARS: usize = 30_000;

/// Truncate tool output that exceeds `MAX_TOOL_OUTPUT_CHARS` using head+tail split.
#[must_use]
pub fn truncate_tool_output(output: &str) -> String {
    truncate_tool_output_at(output, MAX_TOOL_OUTPUT_CHARS)
}

/// Truncate tool output that exceeds `max_chars` using head+tail split.
#[must_use]
pub fn truncate_tool_output_at(output: &str, max_chars: usize) -> String {
    if output.len() <= max_chars {
        return output.to_string();
    }

    let half = max_chars / 2;
    let head_end = output.floor_char_boundary(half);
    let tail_start = output.ceil_char_boundary(output.len() - half);
    let head = &output[..head_end];
    let tail = &output[tail_start..];
    let truncated = output.len() - head_end - (output.len() - tail_start);

    format!(
        "{head}\n\n... [truncated {truncated} chars, showing first and last ~{half} chars] ...\n\n{tail}"
    )
}

/// Event emitted during tool execution for real-time UI updates.
#[derive(Debug, Clone)]
pub enum ToolEvent {
    Started {
        tool_name: String,
        command: String,
    },
    OutputChunk {
        tool_name: String,
        command: String,
        chunk: String,
    },
    Completed {
        tool_name: String,
        command: String,
        output: String,
        success: bool,
        filter_stats: Option<FilterStats>,
        diff: Option<DiffData>,
    },
    Rollback {
        tool_name: String,
        command: String,
        restored_count: usize,
        deleted_count: usize,
    },
}

pub type ToolEventTx = tokio::sync::mpsc::UnboundedSender<ToolEvent>;

/// Classifies a tool error as transient (retryable) or permanent (abort immediately).
///
/// Transient errors may succeed on retry (network blips, race conditions).
/// Permanent errors will not succeed regardless of retries (policy, bad args, not found).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum ErrorKind {
    Transient,
    Permanent,
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Transient => f.write_str("transient"),
            Self::Permanent => f.write_str("permanent"),
        }
    }
}

/// Errors that can occur during tool execution.
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    #[error("command blocked by policy: {command}")]
    Blocked { command: String },

    #[error("path not allowed by sandbox: {path}")]
    SandboxViolation { path: String },

    #[error("command requires confirmation: {command}")]
    ConfirmationRequired { command: String },

    #[error("command timed out after {timeout_secs}s")]
    Timeout { timeout_secs: u64 },

    #[error("operation cancelled")]
    Cancelled,

    #[error("invalid tool parameters: {message}")]
    InvalidParams { message: String },

    #[error("execution failed: {0}")]
    Execution(#[from] std::io::Error),

    /// HTTP or API error with status code for fine-grained classification.
    ///
    /// Used by `WebScrapeExecutor` and other HTTP-based tools to preserve the status
    /// code for taxonomy classification. Scope: HTTP tools only (MCP uses a separate path).
    #[error("HTTP error {status}: {message}")]
    Http { status: u16, message: String },

    /// Shell execution error with explicit exit code and pre-classified category.
    ///
    /// Used by `ShellExecutor` when the exit code or stderr content maps to a known
    /// taxonomy category (e.g., exit 126 → `PolicyBlocked`, exit 127 → `PermanentFailure`).
    /// Preserves the exit code for audit logging and the category for skill evolution.
    #[error("shell error (exit {exit_code}): {message}")]
    Shell {
        exit_code: i32,
        category: crate::error_taxonomy::ToolErrorCategory,
        message: String,
    },

    #[error("snapshot failed: {reason}")]
    SnapshotFailed { reason: String },
}

impl ToolError {
    /// Fine-grained error classification using the 12-category taxonomy.
    ///
    /// Prefer `category()` over `kind()` for new code. `kind()` is preserved for
    /// backward compatibility and delegates to `category().error_kind()`.
    #[must_use]
    pub fn category(&self) -> crate::error_taxonomy::ToolErrorCategory {
        use crate::error_taxonomy::{ToolErrorCategory, classify_http_status, classify_io_error};
        match self {
            Self::Blocked { .. } | Self::SandboxViolation { .. } => {
                ToolErrorCategory::PolicyBlocked
            }
            Self::ConfirmationRequired { .. } => ToolErrorCategory::ConfirmationRequired,
            Self::Timeout { .. } => ToolErrorCategory::Timeout,
            Self::Cancelled => ToolErrorCategory::Cancelled,
            Self::InvalidParams { .. } => ToolErrorCategory::InvalidParameters,
            Self::Http { status, .. } => classify_http_status(*status),
            Self::Execution(io_err) => classify_io_error(io_err),
            Self::Shell { category, .. } => *category,
            Self::SnapshotFailed { .. } => ToolErrorCategory::PermanentFailure,
        }
    }

    /// Coarse classification for backward compatibility. Delegates to `category().error_kind()`.
    ///
    /// For `Execution(io::Error)`, the classification inspects `io::Error::kind()`:
    /// - Transient: `TimedOut`, `WouldBlock`, `Interrupted`, `ConnectionReset`,
    ///   `ConnectionAborted`, `BrokenPipe` — these may succeed on retry.
    /// - Permanent: `NotFound`, `PermissionDenied`, `AlreadyExists`, and all other
    ///   I/O error kinds — retrying would waste time with no benefit.
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        self.category().error_kind()
    }
}

/// Deserialize tool call params from a `serde_json::Map<String, Value>` into a typed struct.
///
/// # Errors
///
/// Returns `ToolError::InvalidParams` when deserialization fails.
pub fn deserialize_params<T: serde::de::DeserializeOwned>(
    params: &serde_json::Map<String, serde_json::Value>,
) -> Result<T, ToolError> {
    let obj = serde_json::Value::Object(params.clone());
    serde_json::from_value(obj).map_err(|e| ToolError::InvalidParams {
        message: e.to_string(),
    })
}

/// Async trait for tool execution backends (shell, future MCP, A2A).
///
/// Accepts the full LLM response and returns an optional output.
/// Returns `None` when no tool invocation is detected in the response.
pub trait ToolExecutor: Send + Sync {
    fn execute(
        &self,
        response: &str,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send;

    /// Execute bypassing confirmation checks (called after user approves).
    /// Default: delegates to `execute`.
    fn execute_confirmed(
        &self,
        response: &str,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        self.execute(response)
    }

    /// Return tool definitions this executor can handle.
    fn tool_definitions(&self) -> Vec<crate::registry::ToolDef> {
        vec![]
    }

    /// Execute a structured tool call. Returns `None` if `tool_id` is not handled.
    fn execute_tool_call(
        &self,
        _call: &ToolCall,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        std::future::ready(Ok(None))
    }

    /// Execute a structured tool call bypassing confirmation checks.
    ///
    /// Called after the user has explicitly approved the tool invocation.
    /// Default implementation delegates to `execute_tool_call`.
    fn execute_tool_call_confirmed(
        &self,
        call: &ToolCall,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        self.execute_tool_call(call)
    }

    /// Inject environment variables for the currently active skill. No-op by default.
    fn set_skill_env(&self, _env: Option<std::collections::HashMap<String, String>>) {}

    /// Set the effective trust level for the currently active skill. No-op by default.
    fn set_effective_trust(&self, _level: crate::TrustLevel) {}

    /// Whether the executor can safely retry this tool call on a transient error.
    ///
    /// Only idempotent operations (e.g. read-only HTTP GET) should return `true`.
    /// Shell commands and other non-idempotent operations must keep the default `false`
    /// to prevent double-execution of side-effectful commands.
    fn is_tool_retryable(&self, _tool_id: &str) -> bool {
        false
    }
}

/// Object-safe erased version of [`ToolExecutor`] using boxed futures.
///
/// Implemented automatically for all `T: ToolExecutor + 'static`.
/// Use `Box<dyn ErasedToolExecutor>` when dynamic dispatch is required.
pub trait ErasedToolExecutor: Send + Sync {
    fn execute_erased<'a>(
        &'a self,
        response: &'a str,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>;

    fn execute_confirmed_erased<'a>(
        &'a self,
        response: &'a str,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>;

    fn tool_definitions_erased(&self) -> Vec<crate::registry::ToolDef>;

    fn execute_tool_call_erased<'a>(
        &'a self,
        call: &'a ToolCall,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>;

    fn execute_tool_call_confirmed_erased<'a>(
        &'a self,
        call: &'a ToolCall,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
    {
        // TrustGateExecutor overrides ToolExecutor::execute_tool_call_confirmed; the blanket
        // impl for T: ToolExecutor routes this call through it via execute_tool_call_confirmed_erased.
        // Other implementors fall back to execute_tool_call_erased (normal enforcement path).
        self.execute_tool_call_erased(call)
    }

    /// Inject environment variables for the currently active skill. No-op by default.
    fn set_skill_env(&self, _env: Option<std::collections::HashMap<String, String>>) {}

    /// Set the effective trust level for the currently active skill. No-op by default.
    fn set_effective_trust(&self, _level: crate::TrustLevel) {}

    /// Whether the executor can safely retry this tool call on a transient error.
    fn is_tool_retryable_erased(&self, tool_id: &str) -> bool;
}

impl<T: ToolExecutor> ErasedToolExecutor for T {
    fn execute_erased<'a>(
        &'a self,
        response: &'a str,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
    {
        Box::pin(self.execute(response))
    }

    fn execute_confirmed_erased<'a>(
        &'a self,
        response: &'a str,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
    {
        Box::pin(self.execute_confirmed(response))
    }

    fn tool_definitions_erased(&self) -> Vec<crate::registry::ToolDef> {
        self.tool_definitions()
    }

    fn execute_tool_call_erased<'a>(
        &'a self,
        call: &'a ToolCall,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
    {
        Box::pin(self.execute_tool_call(call))
    }

    fn execute_tool_call_confirmed_erased<'a>(
        &'a self,
        call: &'a ToolCall,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<ToolOutput>, ToolError>> + Send + 'a>>
    {
        Box::pin(self.execute_tool_call_confirmed(call))
    }

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

    fn set_effective_trust(&self, level: crate::TrustLevel) {
        ToolExecutor::set_effective_trust(self, level);
    }

    fn is_tool_retryable_erased(&self, tool_id: &str) -> bool {
        ToolExecutor::is_tool_retryable(self, tool_id)
    }
}

/// Wraps `Arc<dyn ErasedToolExecutor>` so it can be used as a concrete `ToolExecutor`.
///
/// Enables dynamic composition of tool executors at runtime without static type chains.
pub struct DynExecutor(pub std::sync::Arc<dyn ErasedToolExecutor>);

impl ToolExecutor for DynExecutor {
    fn execute(
        &self,
        response: &str,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        // Clone data to satisfy the 'static-ish bound: erased futures must not borrow self.
        let inner = std::sync::Arc::clone(&self.0);
        let response = response.to_owned();
        async move { inner.execute_erased(&response).await }
    }

    fn execute_confirmed(
        &self,
        response: &str,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        let inner = std::sync::Arc::clone(&self.0);
        let response = response.to_owned();
        async move { inner.execute_confirmed_erased(&response).await }
    }

    fn tool_definitions(&self) -> Vec<crate::registry::ToolDef> {
        self.0.tool_definitions_erased()
    }

    fn execute_tool_call(
        &self,
        call: &ToolCall,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        let inner = std::sync::Arc::clone(&self.0);
        let call = call.clone();
        async move { inner.execute_tool_call_erased(&call).await }
    }

    fn execute_tool_call_confirmed(
        &self,
        call: &ToolCall,
    ) -> impl Future<Output = Result<Option<ToolOutput>, ToolError>> + Send {
        let inner = std::sync::Arc::clone(&self.0);
        let call = call.clone();
        async move { inner.execute_tool_call_confirmed_erased(&call).await }
    }

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

    fn set_effective_trust(&self, level: crate::TrustLevel) {
        ErasedToolExecutor::set_effective_trust(self.0.as_ref(), level);
    }

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

/// Extract fenced code blocks with the given language marker from text.
///
/// Searches for `` ```{lang} `` … `` ``` `` pairs, returning trimmed content.
#[must_use]
pub fn extract_fenced_blocks<'a>(text: &'a str, lang: &str) -> Vec<&'a str> {
    let marker = format!("```{lang}");
    let marker_len = marker.len();
    let mut blocks = Vec::new();
    let mut rest = text;

    let mut search_from = 0;
    while let Some(rel) = rest[search_from..].find(&marker) {
        let start = search_from + rel;
        let after = &rest[start + marker_len..];
        // Word-boundary check: the character immediately after the marker must be
        // whitespace, end-of-string, or a non-word character (not alphanumeric / _ / -).
        // This prevents "```bash" from matching "```bashrc".
        let boundary_ok = after
            .chars()
            .next()
            .is_none_or(|c| !c.is_alphanumeric() && c != '_' && c != '-');
        if !boundary_ok {
            search_from = start + marker_len;
            continue;
        }
        if let Some(end) = after.find("```") {
            blocks.push(after[..end].trim());
            rest = &after[end + 3..];
            search_from = 0;
        } else {
            break;
        }
    }

    blocks
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tool_output_display() {
        let output = ToolOutput {
            tool_name: "bash".to_owned(),
            summary: "$ echo hello\nhello".to_owned(),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: None,
            locations: None,
            raw_response: None,
            claim_source: None,
        };
        assert_eq!(output.to_string(), "$ echo hello\nhello");
    }

    #[test]
    fn tool_error_blocked_display() {
        let err = ToolError::Blocked {
            command: "rm -rf /".to_owned(),
        };
        assert_eq!(err.to_string(), "command blocked by policy: rm -rf /");
    }

    #[test]
    fn tool_error_sandbox_violation_display() {
        let err = ToolError::SandboxViolation {
            path: "/etc/shadow".to_owned(),
        };
        assert_eq!(err.to_string(), "path not allowed by sandbox: /etc/shadow");
    }

    #[test]
    fn tool_error_confirmation_required_display() {
        let err = ToolError::ConfirmationRequired {
            command: "rm -rf /tmp".to_owned(),
        };
        assert_eq!(
            err.to_string(),
            "command requires confirmation: rm -rf /tmp"
        );
    }

    #[test]
    fn tool_error_timeout_display() {
        let err = ToolError::Timeout { timeout_secs: 30 };
        assert_eq!(err.to_string(), "command timed out after 30s");
    }

    #[test]
    fn tool_error_invalid_params_display() {
        let err = ToolError::InvalidParams {
            message: "missing field `command`".to_owned(),
        };
        assert_eq!(
            err.to_string(),
            "invalid tool parameters: missing field `command`"
        );
    }

    #[test]
    fn deserialize_params_valid() {
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct P {
            name: String,
            count: u32,
        }
        let mut map = serde_json::Map::new();
        map.insert("name".to_owned(), serde_json::json!("test"));
        map.insert("count".to_owned(), serde_json::json!(42));
        let p: P = deserialize_params(&map).unwrap();
        assert_eq!(
            p,
            P {
                name: "test".to_owned(),
                count: 42
            }
        );
    }

    #[test]
    fn deserialize_params_missing_required_field() {
        #[derive(Debug, serde::Deserialize)]
        #[allow(dead_code)]
        struct P {
            name: String,
        }
        let map = serde_json::Map::new();
        let err = deserialize_params::<P>(&map).unwrap_err();
        assert!(matches!(err, ToolError::InvalidParams { .. }));
    }

    #[test]
    fn deserialize_params_wrong_type() {
        #[derive(Debug, serde::Deserialize)]
        #[allow(dead_code)]
        struct P {
            count: u32,
        }
        let mut map = serde_json::Map::new();
        map.insert("count".to_owned(), serde_json::json!("not a number"));
        let err = deserialize_params::<P>(&map).unwrap_err();
        assert!(matches!(err, ToolError::InvalidParams { .. }));
    }

    #[test]
    fn deserialize_params_all_optional_empty() {
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct P {
            name: Option<String>,
        }
        let map = serde_json::Map::new();
        let p: P = deserialize_params(&map).unwrap();
        assert_eq!(p, P { name: None });
    }

    #[test]
    fn deserialize_params_ignores_extra_fields() {
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct P {
            name: String,
        }
        let mut map = serde_json::Map::new();
        map.insert("name".to_owned(), serde_json::json!("test"));
        map.insert("extra".to_owned(), serde_json::json!(true));
        let p: P = deserialize_params(&map).unwrap();
        assert_eq!(
            p,
            P {
                name: "test".to_owned()
            }
        );
    }

    #[test]
    fn tool_error_execution_display() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "bash not found");
        let err = ToolError::Execution(io_err);
        assert!(err.to_string().starts_with("execution failed:"));
        assert!(err.to_string().contains("bash not found"));
    }

    // ErrorKind classification tests
    #[test]
    fn error_kind_timeout_is_transient() {
        let err = ToolError::Timeout { timeout_secs: 30 };
        assert_eq!(err.kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_blocked_is_permanent() {
        let err = ToolError::Blocked {
            command: "rm -rf /".to_owned(),
        };
        assert_eq!(err.kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_sandbox_violation_is_permanent() {
        let err = ToolError::SandboxViolation {
            path: "/etc/shadow".to_owned(),
        };
        assert_eq!(err.kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_cancelled_is_permanent() {
        assert_eq!(ToolError::Cancelled.kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_invalid_params_is_permanent() {
        let err = ToolError::InvalidParams {
            message: "bad arg".to_owned(),
        };
        assert_eq!(err.kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_confirmation_required_is_permanent() {
        let err = ToolError::ConfirmationRequired {
            command: "rm /tmp/x".to_owned(),
        };
        assert_eq!(err.kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_execution_timed_out_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_interrupted_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::Interrupted, "interrupted");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_connection_reset_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "reset");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_broken_pipe_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe broken");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_would_block_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::WouldBlock, "would block");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_connection_aborted_is_transient() {
        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionAborted, "aborted");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Transient);
    }

    #[test]
    fn error_kind_execution_not_found_is_permanent() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_execution_permission_denied_is_permanent() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_execution_other_is_permanent() {
        let io_err = std::io::Error::other("some other error");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_execution_already_exists_is_permanent() {
        let io_err = std::io::Error::new(std::io::ErrorKind::AlreadyExists, "exists");
        assert_eq!(ToolError::Execution(io_err).kind(), ErrorKind::Permanent);
    }

    #[test]
    fn error_kind_display() {
        assert_eq!(ErrorKind::Transient.to_string(), "transient");
        assert_eq!(ErrorKind::Permanent.to_string(), "permanent");
    }

    #[test]
    fn truncate_tool_output_short_passthrough() {
        let short = "hello world";
        assert_eq!(truncate_tool_output(short), short);
    }

    #[test]
    fn truncate_tool_output_exact_limit() {
        let exact = "a".repeat(MAX_TOOL_OUTPUT_CHARS);
        assert_eq!(truncate_tool_output(&exact), exact);
    }

    #[test]
    fn truncate_tool_output_long_split() {
        let long = "x".repeat(MAX_TOOL_OUTPUT_CHARS + 1000);
        let result = truncate_tool_output(&long);
        assert!(result.contains("truncated"));
        assert!(result.len() < long.len());
    }

    #[test]
    fn truncate_tool_output_notice_contains_count() {
        let long = "y".repeat(MAX_TOOL_OUTPUT_CHARS + 2000);
        let result = truncate_tool_output(&long);
        assert!(result.contains("truncated"));
        assert!(result.contains("chars"));
    }

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

    #[tokio::test]
    async fn execute_tool_call_default_returns_none() {
        let exec = DefaultExecutor;
        let call = ToolCall {
            tool_id: "anything".to_owned(),
            params: serde_json::Map::new(),
        };
        let result = exec.execute_tool_call(&call).await.unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn filter_stats_savings_pct() {
        let fs = FilterStats {
            raw_chars: 1000,
            filtered_chars: 200,
            ..Default::default()
        };
        assert!((fs.savings_pct() - 80.0).abs() < 0.01);
    }

    #[test]
    fn filter_stats_savings_pct_zero() {
        let fs = FilterStats::default();
        assert!((fs.savings_pct()).abs() < 0.01);
    }

    #[test]
    fn filter_stats_estimated_tokens_saved() {
        let fs = FilterStats {
            raw_chars: 1000,
            filtered_chars: 200,
            ..Default::default()
        };
        assert_eq!(fs.estimated_tokens_saved(), 200); // (1000 - 200) / 4
    }

    #[test]
    fn filter_stats_format_inline() {
        let fs = FilterStats {
            raw_chars: 1000,
            filtered_chars: 200,
            raw_lines: 342,
            filtered_lines: 28,
            ..Default::default()
        };
        let line = fs.format_inline("shell");
        assert_eq!(line, "[shell] 342 lines \u{2192} 28 lines, 80.0% filtered");
    }

    #[test]
    fn filter_stats_format_inline_zero() {
        let fs = FilterStats::default();
        let line = fs.format_inline("bash");
        assert_eq!(line, "[bash] 0 lines \u{2192} 0 lines, 0.0% filtered");
    }

    // DynExecutor tests

    struct FixedExecutor {
        tool_id: &'static str,
        output: &'static str,
    }

    impl ToolExecutor for FixedExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(Some(ToolOutput {
                tool_name: self.tool_id.to_owned(),
                summary: self.output.to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
            }))
        }

        fn tool_definitions(&self) -> Vec<crate::registry::ToolDef> {
            vec![]
        }

        async fn execute_tool_call(
            &self,
            _call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            Ok(Some(ToolOutput {
                tool_name: self.tool_id.to_owned(),
                summary: self.output.to_owned(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
            }))
        }
    }

    #[tokio::test]
    async fn dyn_executor_execute_delegates() {
        let inner = std::sync::Arc::new(FixedExecutor {
            tool_id: "bash",
            output: "hello",
        });
        let exec = DynExecutor(inner);
        let result = exec.execute("```bash\necho hello\n```").await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().summary, "hello");
    }

    #[tokio::test]
    async fn dyn_executor_execute_confirmed_delegates() {
        let inner = std::sync::Arc::new(FixedExecutor {
            tool_id: "bash",
            output: "confirmed",
        });
        let exec = DynExecutor(inner);
        let result = exec.execute_confirmed("...").await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().summary, "confirmed");
    }

    #[test]
    fn dyn_executor_tool_definitions_delegates() {
        let inner = std::sync::Arc::new(FixedExecutor {
            tool_id: "my_tool",
            output: "",
        });
        let exec = DynExecutor(inner);
        // FixedExecutor returns empty definitions; verify delegation occurs without panic.
        let defs = exec.tool_definitions();
        assert!(defs.is_empty());
    }

    #[tokio::test]
    async fn dyn_executor_execute_tool_call_delegates() {
        let inner = std::sync::Arc::new(FixedExecutor {
            tool_id: "bash",
            output: "tool_call_result",
        });
        let exec = DynExecutor(inner);
        let call = ToolCall {
            tool_id: "bash".to_owned(),
            params: serde_json::Map::new(),
        };
        let result = exec.execute_tool_call(&call).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().summary, "tool_call_result");
    }

    #[test]
    fn dyn_executor_set_effective_trust_delegates() {
        use std::sync::atomic::{AtomicU8, Ordering};

        struct TrustCapture(AtomicU8);
        impl ToolExecutor for TrustCapture {
            async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
                Ok(None)
            }
            fn set_effective_trust(&self, level: crate::TrustLevel) {
                // encode: Trusted=0, Verified=1, Quarantined=2, Blocked=3
                let v = match level {
                    crate::TrustLevel::Trusted => 0u8,
                    crate::TrustLevel::Verified => 1,
                    crate::TrustLevel::Quarantined => 2,
                    crate::TrustLevel::Blocked => 3,
                };
                self.0.store(v, Ordering::Relaxed);
            }
        }

        let inner = std::sync::Arc::new(TrustCapture(AtomicU8::new(0)));
        let exec =
            DynExecutor(std::sync::Arc::clone(&inner) as std::sync::Arc<dyn ErasedToolExecutor>);
        ToolExecutor::set_effective_trust(&exec, crate::TrustLevel::Quarantined);
        assert_eq!(inner.0.load(Ordering::Relaxed), 2);

        ToolExecutor::set_effective_trust(&exec, crate::TrustLevel::Blocked);
        assert_eq!(inner.0.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn extract_fenced_blocks_no_prefix_match() {
        // ```bashrc must NOT match when searching for "bash"
        assert!(extract_fenced_blocks("```bashrc\nfoo\n```", "bash").is_empty());
        // exact match
        assert_eq!(
            extract_fenced_blocks("```bash\nfoo\n```", "bash"),
            vec!["foo"]
        );
        // trailing space is fine
        assert_eq!(
            extract_fenced_blocks("```bash \nfoo\n```", "bash"),
            vec!["foo"]
        );
    }

    // ── ToolError::category() delegation tests ────────────────────────────────

    #[test]
    fn tool_error_http_400_category_is_invalid_parameters() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 400,
            message: "bad request".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::InvalidParameters);
    }

    #[test]
    fn tool_error_http_401_category_is_policy_blocked() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 401,
            message: "unauthorized".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PolicyBlocked);
    }

    #[test]
    fn tool_error_http_403_category_is_policy_blocked() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 403,
            message: "forbidden".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PolicyBlocked);
    }

    #[test]
    fn tool_error_http_404_category_is_permanent_failure() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 404,
            message: "not found".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PermanentFailure);
    }

    #[test]
    fn tool_error_http_429_category_is_rate_limited() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 429,
            message: "too many requests".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::RateLimited);
    }

    #[test]
    fn tool_error_http_500_category_is_server_error() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 500,
            message: "internal server error".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::ServerError);
    }

    #[test]
    fn tool_error_http_502_category_is_server_error() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 502,
            message: "bad gateway".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::ServerError);
    }

    #[test]
    fn tool_error_http_503_category_is_server_error() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Http {
            status: 503,
            message: "service unavailable".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::ServerError);
    }

    #[test]
    fn tool_error_http_503_is_transient_triggers_phase2_retry() {
        // Phase 2 retry fires when err.kind() == ErrorKind::Transient.
        // Verify the full chain: Http{503} -> ServerError -> is_retryable() -> Transient.
        let err = ToolError::Http {
            status: 503,
            message: "service unavailable".to_owned(),
        };
        assert_eq!(
            err.kind(),
            ErrorKind::Transient,
            "HTTP 503 must be Transient so Phase 2 retry fires"
        );
    }

    #[test]
    fn tool_error_blocked_category_is_policy_blocked() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Blocked {
            command: "rm -rf /".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PolicyBlocked);
    }

    #[test]
    fn tool_error_sandbox_violation_category_is_policy_blocked() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::SandboxViolation {
            path: "/etc/shadow".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PolicyBlocked);
    }

    #[test]
    fn tool_error_confirmation_required_category() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::ConfirmationRequired {
            command: "rm /tmp/x".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::ConfirmationRequired);
    }

    #[test]
    fn tool_error_timeout_category() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Timeout { timeout_secs: 30 };
        assert_eq!(err.category(), ToolErrorCategory::Timeout);
    }

    #[test]
    fn tool_error_cancelled_category() {
        use crate::error_taxonomy::ToolErrorCategory;
        assert_eq!(
            ToolError::Cancelled.category(),
            ToolErrorCategory::Cancelled
        );
    }

    #[test]
    fn tool_error_invalid_params_category() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::InvalidParams {
            message: "missing field".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::InvalidParameters);
    }

    // B2 regression: Execution(NotFound) must NOT produce ToolNotFound.
    #[test]
    fn tool_error_execution_not_found_category_is_permanent_failure() {
        use crate::error_taxonomy::ToolErrorCategory;
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "bash: not found");
        let err = ToolError::Execution(io_err);
        let cat = err.category();
        assert_ne!(
            cat,
            ToolErrorCategory::ToolNotFound,
            "Execution(NotFound) must NOT map to ToolNotFound"
        );
        assert_eq!(cat, ToolErrorCategory::PermanentFailure);
    }

    #[test]
    fn tool_error_execution_timed_out_category_is_timeout() {
        use crate::error_taxonomy::ToolErrorCategory;
        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out");
        assert_eq!(
            ToolError::Execution(io_err).category(),
            ToolErrorCategory::Timeout
        );
    }

    #[test]
    fn tool_error_execution_connection_refused_category_is_network_error() {
        use crate::error_taxonomy::ToolErrorCategory;
        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "refused");
        assert_eq!(
            ToolError::Execution(io_err).category(),
            ToolErrorCategory::NetworkError
        );
    }

    // B4 regression: Http/network/transient categories must NOT be quality failures.
    #[test]
    fn b4_tool_error_http_429_not_quality_failure() {
        let err = ToolError::Http {
            status: 429,
            message: "rate limited".to_owned(),
        };
        assert!(
            !err.category().is_quality_failure(),
            "RateLimited must not be a quality failure"
        );
    }

    #[test]
    fn b4_tool_error_http_503_not_quality_failure() {
        let err = ToolError::Http {
            status: 503,
            message: "service unavailable".to_owned(),
        };
        assert!(
            !err.category().is_quality_failure(),
            "ServerError must not be a quality failure"
        );
    }

    #[test]
    fn b4_tool_error_execution_timed_out_not_quality_failure() {
        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
        assert!(
            !ToolError::Execution(io_err).category().is_quality_failure(),
            "Timeout must not be a quality failure"
        );
    }

    // ── ToolError::Shell category tests ──────────────────────────────────────

    #[test]
    fn tool_error_shell_exit126_is_policy_blocked() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Shell {
            exit_code: 126,
            category: ToolErrorCategory::PolicyBlocked,
            message: "permission denied".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PolicyBlocked);
    }

    #[test]
    fn tool_error_shell_exit127_is_permanent_failure() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Shell {
            exit_code: 127,
            category: ToolErrorCategory::PermanentFailure,
            message: "command not found".to_owned(),
        };
        assert_eq!(err.category(), ToolErrorCategory::PermanentFailure);
        assert!(!err.category().is_retryable());
    }

    #[test]
    fn tool_error_shell_not_quality_failure() {
        use crate::error_taxonomy::ToolErrorCategory;
        let err = ToolError::Shell {
            exit_code: 127,
            category: ToolErrorCategory::PermanentFailure,
            message: "command not found".to_owned(),
        };
        // Shell exit errors are not attributable to LLM output quality.
        assert!(!err.category().is_quality_failure());
    }
}