kkachi 0.1.8

High-performance, zero-copy library for optimizing language model prompts and programs
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
// Copyright © 2025 lituus-io <spicyzhug@gmail.com>
// All Rights Reserved.
// Licensed under PolyForm Noncommercial 1.0.0

//! CLI-based validation for external tool integration.
//!
//! This module provides the [`Cli`] builder for creating validators that
//! execute external commands to validate generated content.
//!
//! # Examples
//!
//! ```rust,ignore
//! use kkachi::recursive::cli;
//!
//! // Single command
//! let v = cli("rustfmt").arg("--check").ext("rs");
//!
//! // Multi-stage pipeline
//! let v = cli("rustfmt").arg("--check")
//!     .then("rustc").arg("--emit=metadata").required()
//!     .then("clippy")
//!     .ext("rs");
//!
//! // With environment variables
//! let v = cli("pulumi").arg("preview")
//!     .env_from("GOOGLE_APPLICATION_CREDENTIALS")
//!     .capture();
//! ```

use crate::error::{Error, Result};
use crate::recursive::executor::{CodeExecutor, ExecutionResult};
use crate::recursive::tool::Tool;
use crate::recursive::validate::{Score, Validate};
use smallvec::SmallVec;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// Create a new CLI validator builder.
///
/// This is the entry point for building CLI-based validators.
#[inline]
pub fn cli(command: &str) -> Cli {
    Cli::new(command)
}

/// Captured output from a CLI command.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CliCapture {
    /// Stage name.
    pub stage: String,
    /// Command that was run.
    pub command: String,
    /// Standard output.
    pub stdout: String,
    /// Standard error.
    pub stderr: String,
    /// Whether the command succeeded.
    pub success: bool,
    /// Exit code.
    pub exit_code: Option<i32>,
    /// Execution duration in milliseconds.
    pub duration_ms: u64,
}

/// A structured error extracted from CLI output.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CliError {
    /// Error severity: "error", "warning", or "note".
    pub severity: &'static str,
    /// The error message text.
    pub message: String,
    /// Optional line number (if parseable from output).
    pub line: Option<u32>,
}

impl CliCapture {
    /// Get combined output (stdout + stderr).
    pub fn combined(&self) -> String {
        if self.stderr.is_empty() {
            self.stdout.clone()
        } else if self.stdout.is_empty() {
            self.stderr.clone()
        } else {
            format!("{}\n{}", self.stdout, self.stderr)
        }
    }

    /// Get error lines from stderr.
    pub fn errors(&self) -> Vec<&str> {
        self.stderr
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect()
    }

    /// Extract structured errors from stderr output.
    ///
    /// Parses common error formats from compilers and linters:
    /// - `error[E0308]: ...`
    /// - `file.rs:12:5: error: ...`
    /// - `Error: ...`
    /// - `warning: ...`
    pub fn extract_errors(&self) -> SmallVec<[CliError; 4]> {
        let mut errors = SmallVec::new();
        let source = if self.stderr.trim().is_empty() {
            &self.stdout
        } else {
            &self.stderr
        };

        for line in source.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }

            let lower = trimmed.to_lowercase();
            let severity = if lower.starts_with("error") || lower.contains(": error") {
                "error"
            } else if lower.starts_with("warning") || lower.contains(": warning") {
                "warning"
            } else if lower.starts_with("note") || lower.contains(": note") {
                "note"
            } else {
                continue;
            };

            // Try to extract line number from patterns like "file.rs:12:5:"
            let line_num = trimmed
                .split(':')
                .nth(1)
                .and_then(|s| s.trim().parse::<u32>().ok());

            errors.push(CliError {
                severity,
                message: trimmed.to_string(),
                line: line_num,
            });
        }

        errors
    }
}

/// A single CLI stage in the validation pipeline.
#[derive(Clone)]
struct Stage {
    command: String,
    args: SmallVec<[String; 8]>,
    weight: f64,
    required: bool,
}

impl Stage {
    fn new(command: &str) -> Self {
        Self {
            command: command.to_string(),
            args: SmallVec::new(),
            weight: 1.0,
            required: false,
        }
    }
}

/// CLI validator builder.
///
/// Builds a validator that runs one or more CLI commands to validate content.
/// Commands can be chained with `.then()` to create multi-stage pipelines.
pub struct Cli {
    stages: SmallVec<[Stage; 4]>,
    extension: String,
    inherit_env: bool,
    env_vars: SmallVec<[(String, String); 8]>,
    env_passthrough: SmallVec<[String; 8]>,
    workdir: Option<PathBuf>,
    timeout: Duration,
    capture: bool,
    use_stdin: bool,
    strip_fences: bool,
    /// Captured outputs (populated during validation).
    /// Only allocated when `.capture()` is called. Wrapped in `Arc` so
    /// clones share the same capture store — captures written by a
    /// composed/cloned validator are visible from the original Python
    /// object after `reason().go()` completes.
    captures: Option<std::sync::Arc<std::sync::Mutex<SmallVec<[CliCapture; 4]>>>>,
}

impl Clone for Cli {
    fn clone(&self) -> Self {
        Self {
            stages: self.stages.clone(),
            extension: self.extension.clone(),
            inherit_env: self.inherit_env,
            env_vars: self.env_vars.clone(),
            env_passthrough: self.env_passthrough.clone(),
            workdir: self.workdir.clone(),
            timeout: self.timeout,
            capture: self.capture,
            use_stdin: self.use_stdin,
            strip_fences: self.strip_fences,
            // Share the same capture store across clones
            captures: self.captures.clone(),
        }
    }
}

impl Cli {
    /// Create a new CLI validator with the given command.
    pub fn new(command: &str) -> Self {
        let mut stages = SmallVec::new();
        stages.push(Stage::new(command));

        Self {
            stages,
            extension: "txt".to_string(),
            inherit_env: true,
            env_vars: SmallVec::new(),
            env_passthrough: SmallVec::new(),
            workdir: None,
            timeout: Duration::from_secs(120),
            capture: false,
            use_stdin: false,
            strip_fences: false,
            captures: None,
        }
    }

    /// Add an argument to the current stage.
    pub fn arg(mut self, arg: &str) -> Self {
        if let Some(stage) = self.stages.last_mut() {
            stage.args.push(arg.to_string());
        }
        self
    }

    /// Add multiple arguments to the current stage.
    pub fn args(mut self, args: &[&str]) -> Self {
        if let Some(stage) = self.stages.last_mut() {
            for arg in args {
                stage.args.push((*arg).to_string());
            }
        }
        self
    }

    /// Set the weight for the current stage (for scoring).
    pub fn weight(mut self, w: f64) -> Self {
        if let Some(stage) = self.stages.last_mut() {
            stage.weight = w;
        }
        self
    }

    /// Mark the current stage as required (must pass).
    pub fn required(mut self) -> Self {
        if let Some(stage) = self.stages.last_mut() {
            stage.required = true;
        }
        self
    }

    /// Add another command stage to the pipeline.
    pub fn then(mut self, command: &str) -> Self {
        self.stages.push(Stage::new(command));
        self
    }

    /// Set the file extension for the temp file.
    pub fn ext(mut self, extension: &str) -> Self {
        self.extension = extension.to_string();
        self
    }

    /// Set an environment variable.
    pub fn env(mut self, key: &str, value: &str) -> Self {
        self.env_vars.push((key.to_string(), value.to_string()));
        self
    }

    /// Inherit an environment variable from the current process.
    ///
    /// If the variable is not set, this is a no-op.
    pub fn env_from(mut self, key: &str) -> Self {
        self.env_passthrough.push(key.to_string());
        self
    }

    /// Set whether to inherit the parent's environment.
    ///
    /// Default is true.
    pub fn inherit_env(mut self, inherit: bool) -> Self {
        self.inherit_env = inherit;
        self
    }

    /// Set the working directory.
    pub fn workdir(mut self, path: &str) -> Self {
        self.workdir = Some(PathBuf::from(path));
        self
    }

    /// Set the timeout in seconds.
    pub fn timeout(mut self, secs: u64) -> Self {
        self.timeout = Duration::from_secs(secs);
        self
    }

    /// Enable output capture.
    pub fn capture(mut self) -> Self {
        self.capture = true;
        if self.captures.is_none() {
            self.captures = Some(std::sync::Arc::new(std::sync::Mutex::new(SmallVec::new())));
        }
        self
    }

    /// Use stdin instead of a temp file.
    pub fn stdin(mut self) -> Self {
        self.use_stdin = true;
        self
    }

    /// Strip markdown code fences from input before passing to CLI.
    ///
    /// When enabled, if the input contains fenced code blocks (e.g. ````bash\n...\n````),
    /// only the inner code is extracted and passed to the CLI command. The language
    /// is matched against the file extension set via `.ext()`.
    ///
    /// This is useful when LLM output wraps code in markdown fences that would
    /// cause the CLI command to fail.
    pub fn strip_fences(mut self) -> Self {
        self.strip_fences = true;
        self
    }

    /// Get captured outputs after validation.
    pub fn get_captures(&self) -> SmallVec<[CliCapture; 4]> {
        match &self.captures {
            Some(arc) => arc.lock().expect("CLI captures lock poisoned").clone(),
            None => SmallVec::new(),
        }
    }

    /// Validate text and return both the score and captured outputs,
    /// without requiring Arc (for pure Rust usage without cloning).
    pub fn validate_capturing(&self, text: &str) -> (Score<'static>, SmallVec<[CliCapture; 4]>) {
        // Strip markdown fences if configured
        let text = if self.strip_fences {
            use crate::recursive::rewrite::extract_code;
            extract_code(text, &self.extension)
                .map(|s| s.to_string())
                .unwrap_or_else(|| text.to_string())
        } else {
            text.to_string()
        };
        let text: &str = &text;

        let temp_dir = std::env::temp_dir();
        let temp_file = temp_dir.join(format!("kkachi_validate.{}", self.extension));

        if !self.use_stdin {
            if let Err(e) = std::fs::write(&temp_file, text) {
                return (
                    Score::with_feedback(0.0, format!("Failed to write temp file: {}", e)),
                    SmallVec::new(),
                );
            }
        }

        let mut total_weight = 0.0f64;
        let mut weighted_score = 0.0f64;
        let mut errors: Vec<String> = Vec::new();
        let mut all_captures: SmallVec<[CliCapture; 4]> = SmallVec::new();
        let mut required_failed = false;

        for stage in &self.stages {
            let capture = match self.execute_stage(stage, text, &temp_file) {
                Ok(c) => c,
                Err(e) => {
                    let _ = std::fs::remove_file(&temp_file);
                    return (Score::with_feedback(0.0, e.to_string()), SmallVec::new());
                }
            };

            let stage_score = if capture.success { 1.0 } else { 0.0 };
            weighted_score += stage_score * stage.weight;
            total_weight += stage.weight;

            if !capture.success {
                if stage.required {
                    required_failed = true;
                }
                let error_source = if capture.stderr.trim().is_empty() {
                    &capture.stdout
                } else {
                    &capture.stderr
                };
                for line in error_source.lines().filter(|l| !l.trim().is_empty()) {
                    errors.push(line.to_string());
                }
            }

            all_captures.push(capture);
        }

        let _ = std::fs::remove_file(&temp_file);

        let final_score = if required_failed {
            0.0
        } else if total_weight > 0.0 {
            weighted_score / total_weight
        } else {
            1.0
        };

        let score = if errors.is_empty() {
            Score::new(final_score)
        } else {
            Score::with_feedback(final_score, errors.join("\n"))
        };

        (score, all_captures)
    }

    // =========================================================================
    // In-place mutation methods for Python bindings (avoids std::mem::replace)
    // =========================================================================

    /// Add an argument to the current stage (in-place).
    pub fn push_arg(&mut self, arg: &str) {
        if let Some(stage) = self.stages.last_mut() {
            stage.args.push(arg.to_string());
        }
    }

    /// Add multiple arguments to the current stage (in-place).
    pub fn push_args(&mut self, args: &[&str]) {
        if let Some(stage) = self.stages.last_mut() {
            for arg in args {
                stage.args.push((*arg).to_string());
            }
        }
    }

    /// Set the weight for the current stage (in-place).
    pub fn set_weight(&mut self, w: f64) {
        if let Some(stage) = self.stages.last_mut() {
            stage.weight = w;
        }
    }

    /// Mark the current stage as required (in-place).
    pub fn set_required(&mut self) {
        if let Some(stage) = self.stages.last_mut() {
            stage.required = true;
        }
    }

    /// Add another command stage to the pipeline (in-place).
    pub fn push_stage(&mut self, command: &str) {
        self.stages.push(Stage::new(command));
    }

    /// Set the file extension (in-place).
    pub fn set_ext(&mut self, extension: &str) {
        self.extension = extension.to_string();
    }

    /// Set an environment variable (in-place).
    pub fn push_env(&mut self, key: &str, value: &str) {
        self.env_vars.push((key.to_string(), value.to_string()));
    }

    /// Inherit an environment variable from the current process (in-place).
    pub fn push_env_from(&mut self, key: &str) {
        self.env_passthrough.push(key.to_string());
    }

    /// Set the working directory (in-place).
    pub fn set_workdir(&mut self, path: &str) {
        self.workdir = Some(PathBuf::from(path));
    }

    /// Set the timeout in seconds (in-place).
    pub fn set_timeout(&mut self, secs: u64) {
        self.timeout = Duration::from_secs(secs);
    }

    /// Enable output capture (in-place).
    pub fn set_capture(&mut self) {
        self.capture = true;
        if self.captures.is_none() {
            self.captures = Some(std::sync::Arc::new(std::sync::Mutex::new(SmallVec::new())));
        }
    }

    /// Enable strip-fences mode (in-place).
    pub fn set_strip_fences(&mut self) {
        self.strip_fences = true;
    }

    /// Execute a single stage.
    fn execute_stage(
        &self,
        stage: &Stage,
        content: &str,
        temp_file: &std::path::Path,
    ) -> Result<CliCapture> {
        let start = Instant::now();

        let mut cmd = Command::new(&stage.command);

        // Add arguments
        for arg in &stage.args {
            cmd.arg(arg);
        }

        // Add temp file path if not using stdin
        if !self.use_stdin {
            cmd.arg(temp_file);
        }

        // Environment
        if !self.inherit_env {
            cmd.env_clear();
        }

        for (key, value) in &self.env_vars {
            cmd.env(key, value);
        }

        for key in &self.env_passthrough {
            if let Ok(value) = std::env::var(key) {
                cmd.env(key, value);
            }
        }

        // Working directory
        if let Some(ref dir) = self.workdir {
            cmd.current_dir(dir);
        }

        // Set up I/O
        if self.use_stdin {
            cmd.stdin(Stdio::piped());
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        // Execute
        let output = if self.use_stdin {
            let mut child = cmd
                .spawn()
                .map_err(|e| Error::Other(format!("Failed to spawn '{}': {}", stage.command, e)))?;

            if let Some(mut stdin) = child.stdin.take() {
                stdin
                    .write_all(content.as_bytes())
                    .map_err(|e| Error::Other(format!("Failed to write to stdin: {}", e)))?;
            }

            child.wait_with_output().map_err(|e| {
                Error::Other(format!("Failed to wait for '{}': {}", stage.command, e))
            })?
        } else {
            cmd.output().map_err(|e| {
                Error::Other(format!("Failed to execute '{}': {}", stage.command, e))
            })?
        };

        let duration = start.elapsed();

        Ok(CliCapture {
            stage: stage.command.clone(),
            command: format!("{} {}", stage.command, stage.args.join(" ")),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
            duration_ms: duration.as_millis() as u64,
        })
    }
}

impl Validate for Cli {
    fn validate(&self, text: &str) -> Score<'static> {
        // Strip markdown fences if configured
        let text = if self.strip_fences {
            use crate::recursive::rewrite::extract_code;
            extract_code(text, &self.extension)
                .map(|s| s.to_string())
                .unwrap_or_else(|| text.to_string())
        } else {
            text.to_string()
        };
        let text: &str = &text;

        // Create temp file
        let temp_dir = std::env::temp_dir();
        let temp_file = temp_dir.join(format!("kkachi_validate.{}", self.extension));

        // Write content to temp file if not using stdin
        if !self.use_stdin {
            if let Err(e) = std::fs::write(&temp_file, text) {
                return Score::with_feedback(0.0, format!("Failed to write temp file: {}", e));
            }
        }

        let mut total_weight = 0.0f64;
        let mut weighted_score = 0.0f64;
        let mut errors: Vec<String> = Vec::new();
        let mut all_captures: SmallVec<[CliCapture; 4]> = SmallVec::new();
        let mut required_failed = false;

        // Execute each stage
        for stage in &self.stages {
            let capture = match self.execute_stage(stage, text, &temp_file) {
                Ok(c) => c,
                Err(e) => {
                    // Cleanup
                    let _ = std::fs::remove_file(&temp_file);
                    return Score::with_feedback(0.0, e.to_string());
                }
            };

            let stage_score = if capture.success { 1.0 } else { 0.0 };
            weighted_score += stage_score * stage.weight;
            total_weight += stage.weight;

            if !capture.success {
                if stage.required {
                    required_failed = true;
                }
                // Collect error lines from stderr; fall back to stdout when
                // stderr is empty (common when commands use 2>&1 redirection).
                let error_source = if capture.stderr.trim().is_empty() {
                    &capture.stdout
                } else {
                    &capture.stderr
                };
                for line in error_source.lines().filter(|l| !l.trim().is_empty()) {
                    errors.push(line.to_string());
                }
            }

            if self.capture {
                all_captures.push(capture);
            }
        }

        // Cleanup temp file
        let _ = std::fs::remove_file(&temp_file);

        // Append captures (accumulate across iterations so earlier errors
        // are preserved for documentation / README generation).
        if self.capture {
            if let Some(ref arc) = self.captures {
                arc.lock()
                    .expect("CLI captures lock poisoned")
                    .extend(all_captures);
            }
        }

        // Calculate final score
        let final_score = if required_failed {
            0.0
        } else if total_weight > 0.0 {
            weighted_score / total_weight
        } else {
            1.0
        };

        if errors.is_empty() {
            Score::new(final_score)
        } else {
            Score::with_feedback(final_score, errors.join("\n"))
        }
    }

    fn name(&self) -> &'static str {
        "cli"
    }
}

// ============================================================================
// CodeExecutor: CLI-as-Executor adapter
// ============================================================================

impl CodeExecutor for Cli {
    type ExecuteFut<'a>
        = std::future::Ready<ExecutionResult>
    where
        Self: 'a;

    fn language(&self) -> &str {
        self.stages
            .first()
            .map(|s| s.command.as_str())
            .unwrap_or("bash")
    }

    fn extension(&self) -> &str {
        &self.extension
    }

    fn execute<'a>(&'a self, code: &'a str) -> Self::ExecuteFut<'a> {
        std::future::ready(self.execute_code(code))
    }
}

impl Cli {
    /// Execute code through this CLI command, returning an [`ExecutionResult`].
    ///
    /// Used by the [`CodeExecutor`] implementation. Pipes code via stdin
    /// (if enabled) or writes to a temp file, then runs the command.
    fn execute_code(&self, code: &str) -> ExecutionResult {
        let start = std::time::Instant::now();

        // Use first stage for execution
        let stage = match self.stages.first() {
            Some(s) => s,
            None => {
                return ExecutionResult {
                    stdout: String::new(),
                    stderr: "No CLI stages configured".to_string(),
                    success: false,
                    exit_code: None,
                    duration: start.elapsed(),
                };
            }
        };

        // Create temp file if not using stdin
        let temp_file = if !self.use_stdin {
            let temp_dir = std::env::temp_dir();
            let file_path = temp_dir.join(format!("kkachi_exec.{}", self.extension));
            if let Err(e) = std::fs::write(&file_path, code) {
                return ExecutionResult {
                    stdout: String::new(),
                    stderr: format!("Failed to write temp file: {}", e),
                    success: false,
                    exit_code: None,
                    duration: start.elapsed(),
                };
            }
            Some(file_path)
        } else {
            None
        };

        let mut cmd = Command::new(&stage.command);
        for arg in &stage.args {
            cmd.arg(arg);
        }

        if let Some(ref file) = temp_file {
            cmd.arg(file);
        } else {
            cmd.stdin(Stdio::piped());
        }

        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        if let Some(ref dir) = self.workdir {
            cmd.current_dir(dir);
        }

        if !self.inherit_env {
            cmd.env_clear();
        }
        for (key, value) in &self.env_vars {
            cmd.env(key, value);
        }
        for key in &self.env_passthrough {
            if let Ok(value) = std::env::var(key) {
                cmd.env(key, value);
            }
        }

        let result = if self.use_stdin {
            match cmd.spawn() {
                Ok(mut child) => {
                    if let Some(mut stdin) = child.stdin.take() {
                        let _ = stdin.write_all(code.as_bytes());
                    }
                    match child.wait_with_output() {
                        Ok(output) => ExecutionResult {
                            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                            success: output.status.success(),
                            exit_code: output.status.code(),
                            duration: start.elapsed(),
                        },
                        Err(e) => ExecutionResult {
                            stdout: String::new(),
                            stderr: format!("Failed to wait for '{}': {}", stage.command, e),
                            success: false,
                            exit_code: None,
                            duration: start.elapsed(),
                        },
                    }
                }
                Err(e) => ExecutionResult {
                    stdout: String::new(),
                    stderr: format!("Failed to spawn '{}': {}", stage.command, e),
                    success: false,
                    exit_code: None,
                    duration: start.elapsed(),
                },
            }
        } else {
            match cmd.output() {
                Ok(output) => ExecutionResult {
                    stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
                    stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                    success: output.status.success(),
                    exit_code: output.status.code(),
                    duration: start.elapsed(),
                },
                Err(e) => ExecutionResult {
                    stdout: String::new(),
                    stderr: format!("Failed to execute '{}': {}", stage.command, e),
                    success: false,
                    exit_code: None,
                    duration: start.elapsed(),
                },
            }
        };

        // Cleanup temp file
        if let Some(file) = temp_file {
            let _ = std::fs::remove_file(file);
        }

        result
    }
}

// ============================================================================
// CliTool: CLI-as-Tool adapter
// ============================================================================

/// A CLI command wrapped as an agent-compatible [`Tool`].
///
/// Created via [`Cli::as_tool`]. The tool pipes agent input to the CLI command
/// via stdin and returns stdout.
///
/// # Examples
///
/// ```rust,ignore
/// use kkachi::recursive::{cli, agent, Llm};
///
/// let calc = cli("bc").stdin().as_tool("calculator", "Evaluate math expressions");
/// let result = agent(&llm, "What is 23 * 47?").tool(&calc).go();
/// ```
pub struct CliTool {
    cli: Cli,
    tool_name: &'static str,
    tool_description: &'static str,
}

impl Cli {
    /// Convert this CLI builder into an agent tool.
    ///
    /// The tool sends the agent's input to the command via stdin and returns
    /// the command's stdout. Automatically enables stdin mode.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use kkachi::recursive::cli;
    ///
    /// let wc = cli("wc").arg("-w").stdin().as_tool("word_count", "Count words");
    /// ```
    pub fn as_tool(mut self, name: &'static str, description: &'static str) -> CliTool {
        self.use_stdin = true;
        CliTool {
            cli: self,
            tool_name: name,
            tool_description: description,
        }
    }
}

impl Tool for CliTool {
    type ExecuteFut<'a>
        = std::future::Ready<Result<String>>
    where
        Self: 'a;

    fn name(&self) -> &str {
        self.tool_name
    }

    fn description(&self) -> &str {
        self.tool_description
    }

    fn execute<'a>(&'a self, input: &'a str) -> Self::ExecuteFut<'a> {
        std::future::ready(self.run(input))
    }
}

impl CliTool {
    fn run(&self, input: &str) -> Result<String> {
        // Use the first stage only for tool execution
        let stage = self
            .cli
            .stages
            .first()
            .ok_or_else(|| Error::Other("No CLI stages configured".to_string()))?;

        let capture = self
            .cli
            .execute_stage(stage, input, std::path::Path::new(""))?;

        if capture.success {
            Ok(capture.stdout.trim().to_string())
        } else {
            let err = if capture.stderr.is_empty() {
                format!(
                    "Command '{}' failed with exit code {:?}",
                    capture.command, capture.exit_code
                )
            } else {
                capture.stderr.trim().to_string()
            };
            Err(Error::Other(err))
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_cli_builder() {
        let c = cli("echo").arg("hello").arg("world").ext("txt");

        assert_eq!(c.stages.len(), 1);
        assert_eq!(c.stages[0].command, "echo");
        assert_eq!(c.stages[0].args.len(), 2);
        assert_eq!(c.extension, "txt");
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_multi_stage() {
        let c = cli("echo")
            .arg("1")
            .then("echo")
            .arg("2")
            .required()
            .then("echo")
            .arg("3");

        assert_eq!(c.stages.len(), 3);
        assert!(c.stages[1].required);
    }

    #[test]
    fn test_cli_env() {
        let c = cli("echo").env("FOO", "bar").env_from("PATH");

        assert_eq!(c.env_vars.len(), 1);
        assert_eq!(c.env_passthrough.len(), 1);
    }

    #[test]
    #[ignore] // flaky on CI: echo doesn't read stdin, broken pipe race
    fn test_cli_validate_echo() {
        let v = cli("echo").arg("ok").stdin();
        let score = v.validate("test input");
        assert!(score.is_perfect());
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_validate_false() {
        let v = cli("false");
        let score = v.validate("anything");
        assert!(!score.is_perfect());
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_capture() {
        let v = cli("cat").stdin().capture();
        let _ = v.validate("captured");

        let captures = v.get_captures();
        assert_eq!(captures.len(), 1);
        assert!(captures[0].stdout.contains("captured"));
    }

    #[test]
    fn test_cli_capture_errors() {
        let capture = CliCapture {
            stage: "test".to_string(),
            command: "test".to_string(),
            stdout: String::new(),
            stderr: "error: something failed\nwarning: be careful\n".to_string(),
            success: false,
            exit_code: Some(1),
            duration_ms: 100,
        };

        let errors = capture.errors();
        assert_eq!(errors.len(), 2);
        assert!(errors[0].contains("error"));
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_weighted_stages() {
        let c = cli("true").weight(0.3).then("true").weight(0.7);

        let score = c.validate("test");
        assert!(score.is_perfect());
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_as_tool() {
        let t = cli("cat").stdin().as_tool("cat_tool", "Reads stdin");

        assert_eq!(Tool::name(&t), "cat_tool");
        assert_eq!(Tool::description(&t), "Reads stdin");

        let result = futures::executor::block_on(Tool::execute(&t, "hello"));
        assert!(result.is_ok());
        assert!(result.unwrap().contains("hello"));
    }

    #[test]
    #[cfg(unix)]
    fn test_cli_tool_failure() {
        let t = cli("false").stdin().as_tool("fail", "Always fails");

        let result = futures::executor::block_on(Tool::execute(&t, "input"));
        assert!(result.is_err());
    }
}