terraphim_agent 1.20.5

Terraphim AI Agent CLI - Command-line interface with interactive REPL and ASCII graph visualization
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
//! Hook input types and parser for AI agent integration.
//!
//! This module provides types for parsing JSON input from AI agent hooks
//! (Claude Code, Codex, opencode) and extracting failed commands for
//! learning capture.
//!
//! # Usage
//!
//! ```rust,ignore
//! use terraphim_agent::learnings::HookInput;
//!
//! let json = r#"{ "tool_name": "Bash", "tool_input": {"command": "git push"}, "tool_result": {"exit_code": 1, "stdout": "", "stderr": "rejected"} }"#;
//! let input = HookInput::from_json(json)?;
//!
//! if input.should_capture() {
//!     // Capture learning from failed command
//! }
//! ```

use std::collections::HashMap;
use std::path::PathBuf;

use serde::Deserialize;
use thiserror::Error;

use crate::learnings::{
    LearningCaptureConfig, LearningError, capture_failed_command, redact_secrets,
};

/// Hook type for multi-hook pipeline.
#[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)]
pub enum LearnHookType {
    /// Pre-tool-use: warn if command matches past failure patterns
    PreToolUse,
    /// Post-tool-use: capture failed commands (existing behavior)
    PostToolUse,
    /// User prompt submit: capture user corrections inline
    UserPromptSubmit,
}

/// Capture learning from hook input.
///
/// Extracts the command, error output, and exit code from the hook input
/// and delegates to `capture_failed_command` for storage.
///
/// # Arguments
///
/// * `input` - The parsed hook input
///
/// # Returns
///
/// Path to the saved learning file, or error if capture failed/ignored.
pub fn capture_from_hook(input: &HookInput) -> Result<PathBuf, LearningError> {
    let command = input
        .command()
        .ok_or_else(|| LearningError::Ignored("No command in input".to_string()))?;

    let error_output = input.error_output();
    let exit_code = input.tool_result.exit_code;

    let config = LearningCaptureConfig::default();
    capture_failed_command(command, &error_output, exit_code, &config)
}

/// Process hook input with an explicit hook type.
///
/// Routes to the appropriate handler based on the hook type:
/// - PreToolUse: checks command against known error patterns, warns if similar to past failure
/// - PostToolUse: captures failed commands (original behavior)
/// - UserPromptSubmit: captures user corrections inline
///
/// All hook types maintain fail-open behavior: errors are logged but
/// never block the pipeline.
pub async fn process_hook_input_with_type(hook_type: LearnHookType) -> Result<(), HookError> {
    process_hook_with_streams(hook_type, tokio::io::stdin(), tokio::io::stdout()).await
}

/// Core hook processing logic with injectable I/O streams.
///
/// Reads from `reader`, dispatches to the hook handler, unconditionally redacts
/// any secrets from the input buffer, then writes the redacted output to `writer`.
/// Secrets are never forwarded to `writer`.
pub(crate) async fn process_hook_with_streams<R, W>(
    hook_type: LearnHookType,
    mut reader: R,
    mut writer: W,
) -> Result<(), HookError>
where
    R: tokio::io::AsyncRead + Unpin,
    W: tokio::io::AsyncWrite + Unpin,
{
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    // Read full input
    let mut buffer = String::new();
    reader
        .read_to_string(&mut buffer)
        .await
        .map_err(HookError::Stdin)?;

    match hook_type {
        LearnHookType::PreToolUse => {
            process_pre_tool_use(&buffer);
        }
        LearnHookType::PostToolUse => {
            // Parse JSON and capture failures (existing behavior)
            match HookInput::from_json(&buffer) {
                Ok(input) => {
                    if input.should_capture()
                        && let Err(e) = capture_from_hook(&input)
                    {
                        log::debug!("Hook capture failed: {}", e);
                    }
                }
                Err(e) => {
                    log::debug!("Hook parse failed (fail-open): {}", e);
                }
            }
        }
        LearnHookType::UserPromptSubmit => {
            process_user_prompt_submit(&buffer);
        }
    }

    // Unconditionally redact secrets before passing through to the output stream.
    // The previous contains_secrets() fast-path was removed because its pattern
    // set did not cover GitHub PATs (ghp_*), Slack tokens (xox*), or connection
    // strings, allowing those secrets to bypass redaction entirely.
    let output = redact_secrets(&buffer);

    writer
        .write_all(output.as_bytes())
        .await
        .map_err(HookError::Stdin)?;

    Ok(())
}

/// Pre-tool-use handler: check if the command matches known failure patterns.
///
/// Reads the command from the JSON input and queries past learnings for
/// similar commands. If a match is found (especially one with a correction),
/// emits a warning to stderr. Never blocks execution.
fn process_pre_tool_use(json: &str) {
    let input = match HookInput::from_json(json) {
        Ok(i) => i,
        Err(_) => return, // fail-open
    };

    let command = match input.command() {
        Some(c) => c,
        None => return, // not a Bash tool, nothing to check
    };

    let config = LearningCaptureConfig::default();
    let storage_dir = config.storage_location();

    // Query past learnings for similar commands
    let base_cmd = command.split_whitespace().next().unwrap_or(command);
    let learnings = match crate::learnings::capture::query_learnings(&storage_dir, base_cmd, false)
    {
        Ok(l) => l,
        Err(_) => return,
    };

    if learnings.is_empty() {
        return;
    }

    // Find the best match: prefer one with a correction
    let best = learnings
        .iter()
        .find(|l| l.correction.is_some())
        .or(learnings.first());

    if let Some(learning) = best {
        let mut warning = format!(
            "Warning: similar command failed before (exit {}): {}",
            learning.exit_code, learning.command
        );
        if let Some(ref correction) = learning.correction {
            warning.push_str(&format!("\n  Suggested: {}", correction));
        }
        eprintln!("{}", warning);
    }
}

/// User-prompt-submit handler: capture user corrections inline.
///
/// Expects JSON with "user_prompt" field. Looks for correction patterns
/// like "use X instead of Y" and captures them as correction events.
/// Never blocks execution.
fn process_user_prompt_submit(json: &str) {
    let value: serde_json::Value = match serde_json::from_str(json) {
        Ok(v) => v,
        Err(_) => return, // fail-open
    };

    let prompt = match value.get("user_prompt").and_then(|v| v.as_str()) {
        Some(p) => p,
        None => return,
    };

    // Look for correction patterns: "use X instead of Y", "use X not Y", "prefer X over Y"
    if let Some((original, corrected)) = parse_correction_pattern(prompt) {
        let config = LearningCaptureConfig::default();
        if let Err(e) = crate::learnings::capture_correction(
            crate::learnings::CorrectionType::ToolPreference,
            &original,
            &corrected,
            &format!("Auto-captured from user prompt: {}", prompt),
            &config,
        ) {
            log::debug!("User prompt correction capture failed: {}", e);
        }
    }
}

/// Try to parse a correction pattern from user text.
///
/// Supports patterns:
/// - "use X instead of Y"  -> (Y, X)
/// - "use X not Y"         -> (Y, X)
/// - "prefer X over Y"     -> (Y, X)
///
/// Returns None if no pattern matches.
fn parse_correction_pattern(text: &str) -> Option<(String, String)> {
    let lower = text.to_lowercase();
    let trimmed = lower.trim_start();

    // "use X instead of Y" (must start with "use")
    if let Some(use_idx) = trimmed.find("use ")
        && use_idx == 0
    {
        let text_after_use = &text[text.to_lowercase().trim_start().find("use ").unwrap() + 4..];
        let lower_after_use = text_after_use.to_lowercase();
        if let Some(instead_idx) = lower_after_use.find(" instead of ") {
            let corrected = text_after_use[..instead_idx].trim().to_string();
            let original = text_after_use[instead_idx + 12..]
                .trim()
                .trim_end_matches('.')
                .to_string();
            if !corrected.is_empty() && !original.is_empty() {
                return Some((original, corrected));
            }
        }
        // "use X not Y"
        if let Some(not_idx) = lower_after_use.find(" not ") {
            let corrected = text_after_use[..not_idx].trim().to_string();
            let original = text_after_use[not_idx + 5..]
                .trim()
                .trim_end_matches('.')
                .to_string();
            if !corrected.is_empty() && !original.is_empty() {
                return Some((original, corrected));
            }
        }
    }

    // "prefer X over Y" (must start with "prefer")
    if let Some(prefer_idx) = trimmed.find("prefer ")
        && prefer_idx == 0
    {
        let text_after_prefer =
            &text[text.to_lowercase().trim_start().find("prefer ").unwrap() + 7..];
        let lower_after_prefer = text_after_prefer.to_lowercase();
        if let Some(over_idx) = lower_after_prefer.find(" over ") {
            let corrected = text_after_prefer[..over_idx].trim().to_string();
            let original = text_after_prefer[over_idx + 6..]
                .trim()
                .trim_end_matches('.')
                .to_string();
            if !corrected.is_empty() && !original.is_empty() {
                return Some((original, corrected));
            }
        }
    }

    None
}

/// Errors that can occur during hook processing.
///
/// Only `Stdin` is currently produced: JSON-parse and capture failures are
/// handled inline (fail-open, logged) rather than propagated, so no further
/// variants are constructed.
#[derive(Debug, Error)]
pub enum HookError {
    /// Failed to read from stdin
    #[error("failed to read stdin: {0}")]
    Stdin(#[from] std::io::Error),
}

/// Input from AI agent hook.
///
/// This struct represents the JSON payload sent by AI agents
/// when a tool is executed. It contains the tool name, input parameters,
/// and execution result.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct HookInput {
    /// Tool name (e.g., "Bash", "Write", "Edit")
    pub tool_name: String,
    /// Tool input parameters
    pub tool_input: ToolInput,
    /// Tool execution result
    pub tool_result: ToolResult,
}

/// Tool input parameters.
///
/// For Bash tools, this contains the command string.
/// For other tools, additional fields are captured via the `extra` map.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct ToolInput {
    /// Command to execute (for Bash tool)
    pub command: Option<String>,
    /// Additional fields for other tool types
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Tool execution result.
///
/// Contains the exit code and captured output from the tool execution.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct ToolResult {
    /// Exit code (0 = success, non-zero = failure)
    pub exit_code: i32,
    /// Standard output captured from the tool
    #[serde(default)]
    pub stdout: String,
    /// Standard error captured from the tool
    #[serde(default)]
    pub stderr: String,
}

#[allow(dead_code)]
impl HookInput {
    /// Parse hook input from a JSON string.
    ///
    /// # Arguments
    ///
    /// * `json` - The JSON string to parse
    ///
    /// # Returns
    ///
    /// Ok(HookInput) if parsing succeeds, Err(serde_json::Error) otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use terraphim_agent::learnings::HookInput;
    ///
    /// let json = r#"{
    ///     "tool_name": "Bash",
    ///     "tool_input": {"command": "git status"},
    ///     "tool_result": {"exit_code": 128, "stdout": "", "stderr": "fatal: not a git repository"}
    /// }"#;
    ///
    /// let input = HookInput::from_json(json).unwrap();
    /// assert_eq!(input.tool_name, "Bash");
    /// ```
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Check if this input should be captured as a learning.
    ///
    /// Returns true if:
    /// - The tool is "Bash" (command execution)
    /// - The exit code is non-zero (failure)
    ///
    /// # Returns
    ///
    /// true if the failed command should be captured, false otherwise.
    pub fn should_capture(&self) -> bool {
        self.tool_name == "Bash" && self.tool_result.exit_code != 0
    }

    /// Get combined error output (stdout + stderr).
    ///
    /// Combines stdout and stderr with a newline separator if both are present.
    /// Useful for capturing the full error context for learning.
    ///
    /// # Returns
    ///
    /// Combined output string.
    pub fn error_output(&self) -> String {
        let mut output = String::new();
        if !self.tool_result.stdout.is_empty() {
            output.push_str(&self.tool_result.stdout);
        }
        if !self.tool_result.stderr.is_empty() {
            if !output.is_empty() {
                output.push('\n');
            }
            output.push_str(&self.tool_result.stderr);
        }
        output
    }

    /// Get the command string from tool input.
    ///
    /// # Returns
    ///
    /// Some(&str) if a command is present, None otherwise.
    pub fn command(&self) -> Option<&str> {
        self.tool_input.command.as_deref()
    }
}

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

    #[test]
    fn test_hook_input_parse() {
        let json = r#"{
            "tool_name": "Bash",
            "tool_input": {"command": "git push -f"},
            "tool_result": {"exit_code": 1, "stdout": "", "stderr": "rejected"}
        }"#;

        let input = HookInput::from_json(json).unwrap();
        assert_eq!(input.tool_name, "Bash");
        assert_eq!(input.command(), Some("git push -f"));
        assert_eq!(input.tool_result.exit_code, 1);
        assert_eq!(input.tool_result.stdout, "");
        assert_eq!(input.tool_result.stderr, "rejected");
    }

    #[test]
    fn test_should_capture_failed_bash() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert!(input.should_capture());
    }

    #[test]
    fn test_should_not_capture_success() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert!(!input.should_capture());
    }

    #[test]
    fn test_should_not_capture_edit() {
        let input = HookInput {
            tool_name: "Edit".to_string(),
            tool_input: ToolInput {
                command: None,
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert!(!input.should_capture());
    }

    #[test]
    fn test_error_output_combining() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: "output line 1".to_string(),
                stderr: "error line 1".to_string(),
            },
        };
        assert_eq!(input.error_output(), "output line 1\nerror line 1");
    }

    #[test]
    fn test_command_extraction() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("git push origin main".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert_eq!(input.command(), Some("git push origin main"));
    }

    #[test]
    fn test_command_extraction_none() {
        let input = HookInput {
            tool_name: "Edit".to_string(),
            tool_input: ToolInput {
                command: None,
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert_eq!(input.command(), None);
    }

    #[test]
    fn test_parse_with_extra_fields() {
        let json = r#"{
            "tool_name": "Write",
            "tool_input": {
                "path": "/tmp/test.txt",
                "content": "hello world"
            },
            "tool_result": {"exit_code": 0, "stdout": "", "stderr": ""}
        }"#;

        let input = HookInput::from_json(json).unwrap();
        assert_eq!(input.tool_name, "Write");
        assert!(input.tool_input.command.is_none());
        assert!(input.tool_input.extra.contains_key("path"));
        assert!(input.tool_input.extra.contains_key("content"));
    }

    #[test]
    fn test_error_output_stdout_only() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: "some output".to_string(),
                stderr: String::new(),
            },
        };
        assert_eq!(input.error_output(), "some output");
    }

    #[test]
    fn test_error_output_stderr_only() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: String::new(),
                stderr: "some error".to_string(),
            },
        };
        assert_eq!(input.error_output(), "some error");
    }

    #[test]
    fn test_error_output_empty() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("cmd".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: String::new(),
                stderr: String::new(),
            },
        };
        assert_eq!(input.error_output(), "");
    }

    #[test]
    fn test_parse_invalid_json() {
        let json = "not valid json";
        let result = HookInput::from_json(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_should_not_capture_bash_with_exit_zero() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("echo hello".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: "hello".to_string(),
                stderr: String::new(),
            },
        };
        assert!(!input.should_capture());
    }

    #[test]
    fn test_should_capture_bash_with_negative_exit_code() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("kill -9 $$".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: -1,
                stdout: String::new(),
                stderr: "Killed".to_string(),
            },
        };
        assert!(input.should_capture());
    }

    #[test]
    fn test_should_not_capture_non_bash_even_if_failed() {
        let input = HookInput {
            tool_name: "Write".to_string(),
            tool_input: ToolInput {
                command: None,
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: String::new(),
                stderr: "Permission denied".to_string(),
            },
        };
        assert!(!input.should_capture());
    }

    #[test]
    fn test_capture_from_hook_success() {
        let input = HookInput {
            tool_name: "Bash".to_string(),
            tool_input: ToolInput {
                command: Some("git push".to_string()),
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 1,
                stdout: String::new(),
                stderr: "rejected".to_string(),
            },
        };

        // Should succeed and return a path
        let result = capture_from_hook(&input);
        // Note: This may fail if global dir is not writable, so we check it's not Ignored
        // for having no command
        if let Err(LearningError::Ignored(msg)) = &result {
            assert_ne!(msg, "No command in input");
        }
    }

    #[test]
    fn test_capture_from_hook_no_command() {
        let input = HookInput {
            tool_name: "Edit".to_string(),
            tool_input: ToolInput {
                command: None,
                extra: HashMap::new(),
            },
            tool_result: ToolResult {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            },
        };

        let result = capture_from_hook(&input);
        assert!(result.is_err());
        match result.unwrap_err() {
            LearningError::Ignored(msg) => assert_eq!(msg, "No command in input"),
            _ => panic!("Expected Ignored error"),
        }
    }

    /// Verify secrets are stripped from the full process_hook_with_streams pipeline.
    ///
    /// This is the end-to-end test for AC#3: secrets present in hook input must
    /// not appear in the output written to stdout.
    ///
    /// Uses `&[u8]` (impl AsyncRead) as stdin and `Vec<u8>` (impl AsyncWrite) as stdout
    /// so the full I/O path is exercised without spawning a subprocess.
    #[tokio::test]
    async fn test_process_hook_with_streams_strips_secrets_from_output() {
        use super::process_hook_with_streams;

        // Build a fake AWS key at runtime to avoid tripping the pre-commit secret scanner.
        let aws_key = format!("AKIA{}", "IOSFODNN7EXAMPLE");

        let json = format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"aws s3 ls"}},"tool_result":{{"exit_code":1,"stdout":"","stderr":"Unable to locate credentials {aws_key}"}}}}"#,
        );

        // &[u8] implements AsyncRead; Vec<u8> implements AsyncWrite.
        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PostToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");

        // The secret must not appear in the output written to stdout.
        assert!(
            !output.contains(&aws_key),
            "AWS key must not appear in stdout output; got: {output}"
        );
        assert!(
            output.contains("[AWS_KEY_REDACTED]"),
            "Redacted placeholder must appear in output; got: {output}"
        );
    }

    /// Verify clean input passes through unchanged (no spurious redaction).
    #[tokio::test]
    async fn test_process_hook_with_streams_clean_input_unchanged() {
        use super::process_hook_with_streams;

        let json = r#"{"tool_name":"Bash","tool_input":{"command":"cargo build"},"tool_result":{"exit_code":0,"stdout":"Compiling","stderr":""}}"#;

        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PostToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");
        assert_eq!(output, json, "Clean input must pass through unchanged");
    }

    /// Verify pre-tool-use hook also redacts secrets (not just post-tool-use).
    #[tokio::test]
    async fn test_process_hook_with_streams_pre_tool_use_also_redacts() {
        use super::process_hook_with_streams;

        let aws_key = format!("AKIA{}", "IOSFODNN7EXAMPLE");
        let json = format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"export AWS_ACCESS_KEY_ID={aws_key}"}},"tool_result":{{"exit_code":0,"stdout":"","stderr":""}}}}"#,
        );

        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PreToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");
        assert!(
            !output.contains(&aws_key),
            "AWS key must not appear in pre-tool-use stdout output; got: {output}"
        );
    }

    #[test]
    fn test_hook_passthrough_redacts_aws_key_in_error() {
        use crate::learnings::redact_secrets;

        // Build a fake AWS key at runtime to avoid tripping the pre-commit secret scanner.
        // The key prefix "AKIA" followed by 16 uppercase alphanumeric chars is the pattern.
        let aws_key = format!("AKIA{}", "IOSFODNN7EXAMPLE");

        let json = format!(
            r#"{{
            "tool_name": "Bash",
            "tool_input": {{"command": "aws s3 ls"}},
            "tool_result": {{
                "exit_code": 1,
                "stdout": "",
                "stderr": "Unable to locate credentials {}"
            }}
        }}"#,
            aws_key
        );

        // Verify redaction removes the AWS key
        let redacted = redact_secrets(&json);
        assert!(!redacted.contains(&aws_key));
        assert!(redacted.contains("[AWS_KEY_REDACTED]"));

        // Verify the redacted output is still valid JSON
        let parsed = HookInput::from_json(&redacted).unwrap();
        assert_eq!(parsed.tool_name, "Bash");
        assert_eq!(parsed.tool_result.exit_code, 1);
        assert!(parsed.tool_result.stderr.contains("[AWS_KEY_REDACTED]"));
    }

    #[test]
    fn test_learn_hook_type_variants() {
        assert_ne!(LearnHookType::PreToolUse, LearnHookType::PostToolUse);
        assert_ne!(LearnHookType::PostToolUse, LearnHookType::UserPromptSubmit);
        assert_ne!(LearnHookType::PreToolUse, LearnHookType::UserPromptSubmit);
    }

    #[test]
    fn test_parse_correction_pattern_use_instead_of() {
        let result = parse_correction_pattern("use bun instead of npm");
        assert_eq!(result, Some(("npm".to_string(), "bun".to_string())));
    }

    #[test]
    fn test_parse_correction_pattern_prefer_over() {
        let result = parse_correction_pattern("prefer cargo over make");
        assert_eq!(result, Some(("make".to_string(), "cargo".to_string())));
    }

    #[test]
    fn test_parse_correction_pattern_with_trailing_period() {
        let result = parse_correction_pattern("use Result<T> instead of unwrap().");
        assert_eq!(
            result,
            Some(("unwrap()".to_string(), "Result<T>".to_string()))
        );
    }

    #[test]
    fn test_parse_correction_pattern_use_not() {
        let result = parse_correction_pattern("use uv not pip");
        assert_eq!(result, Some(("pip".to_string(), "uv".to_string())));
    }

    #[test]
    fn test_parse_correction_pattern_no_match() {
        assert!(parse_correction_pattern("hello world").is_none());
        assert!(parse_correction_pattern("this is fine").is_none());
        // "I prefer tea over coffee" is a preference, not a tool correction
        assert!(parse_correction_pattern("I prefer tea over coffee").is_none());
    }

    #[test]
    fn test_pre_tool_use_no_crash_on_non_bash() {
        // Non-Bash tool should not crash (fail-open)
        let json = r#"{
            "tool_name": "Edit",
            "tool_input": {"path": "/tmp/test.txt"},
            "tool_result": {"exit_code": 0, "stdout": "", "stderr": ""}
        }"#;
        process_pre_tool_use(json);
        // No panic = pass
    }

    #[test]
    fn test_pre_tool_use_no_crash_on_invalid_json() {
        // Invalid JSON should not crash (fail-open)
        process_pre_tool_use("not valid json");
        // No panic = pass
    }

    #[test]
    fn test_user_prompt_submit_no_crash_on_empty() {
        process_user_prompt_submit("{}");
        // No panic = pass
    }

    #[test]
    fn test_user_prompt_submit_no_crash_on_invalid_json() {
        process_user_prompt_submit("invalid");
        // No panic = pass
    }

    /// GitHub PAT bypass: `ghp_` tokens are not in `contains_secrets()` patterns
    /// but ARE matched by `redact_secrets()`. Unconditional redaction must catch them.
    #[tokio::test]
    async fn test_process_hook_github_pat_is_redacted() {
        use super::process_hook_with_streams;

        // Build token at runtime to avoid the pre-commit secret scanner.
        let pat = format!("ghp_{}", "A".repeat(36));
        let json = format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"git push"}},"tool_result":{{"exit_code":1,"stdout":"","stderr":"remote: invalid credentials {pat}"}}}}"#,
        );

        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PostToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");
        assert!(
            !output.contains(&pat),
            "GitHub PAT must not appear in stdout output; got: {output}"
        );
        assert!(
            output.contains("[GITHUB_TOKEN_REDACTED]"),
            "Redacted placeholder must appear in output; got: {output}"
        );
    }

    /// Slack token bypass: `xoxb-` tokens are not in `contains_secrets()` patterns
    /// but ARE matched by `redact_secrets()`. Unconditional redaction must catch them.
    #[tokio::test]
    async fn test_process_hook_slack_token_is_redacted() {
        use super::process_hook_with_streams;

        // Construct at runtime so push-protection scanners do not flag a literal token.
        let slack_token = format!(
            "xoxb-{}-{}-{}",
            "FAKE_TEST_ID_A", "FAKE_TEST_ID_B", "FAKE_TEST_SECRET"
        );
        let json = format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"curl -H 'Authorization: Bearer {slack_token}' https://slack.com/api/chat.postMessage"}},"tool_result":{{"exit_code":0,"stdout":"","stderr":""}}}}"#,
        );

        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PostToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");
        assert!(
            !output.contains(&slack_token),
            "Slack token must not appear in stdout output; got: {output}"
        );
        assert!(
            output.contains("[SLACK_TOKEN_REDACTED]"),
            "Redacted placeholder must appear in output; got: {output}"
        );
    }

    /// Connection string bypass: `postgresql://user:pass@host` is not in
    /// `contains_secrets()` patterns but IS matched by `redact_secrets()`.
    /// Unconditional redaction must catch it.
    #[tokio::test]
    async fn test_process_hook_connection_string_is_redacted() {
        use super::process_hook_with_streams;

        let conn = "postgresql://dbuser:s3cr3tpassword@prod-db.internal:5432/appdb";
        let json = format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"psql {conn}"}},"tool_result":{{"exit_code":1,"stdout":"","stderr":"connection refused"}}}}"#,
        );

        let mut output_buf: Vec<u8> = Vec::new();
        process_hook_with_streams(LearnHookType::PostToolUse, json.as_bytes(), &mut output_buf)
            .await
            .expect("process_hook_with_streams must not fail");

        let output = String::from_utf8(output_buf).expect("output must be valid UTF-8");
        assert!(
            !output.contains("s3cr3tpassword"),
            "Connection string password must not appear in stdout output; got: {output}"
        );
        assert!(
            output.contains("postgresql://[REDACTED]@"),
            "Redacted connection string must appear in output; got: {output}"
        );
    }
}