terraphim_agent 1.16.34

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
//! 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::redaction::contains_secrets;
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,
}

/// AI agent format for hook processing.
#[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)]
#[allow(dead_code)]
pub enum AgentFormat {
    /// Claude Code format
    Claude,
    /// Codex format
    Codex,
    /// Opencode format
    Opencode,
}

/// 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(
    _format: AgentFormat,
    hook_type: LearnHookType,
) -> Result<(), HookError> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    // Read stdin
    let mut buffer = String::new();
    tokio::io::stdin()
        .read_to_string(&mut buffer)
        .await
        .map_err(HookError::StdinError)?;

    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() {
                        if 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);
        }
    }

    // Redact secrets before passing through to stdout
    let output = if contains_secrets(&buffer) {
        log::debug!("Hook passthrough: secrets detected, redacting before stdout");
        redact_secrets(&buffer)
    } else {
        buffer
    };

    tokio::io::stdout()
        .write_all(output.as_bytes())
        .await
        .map_err(HookError::StdinError)?;

    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", "don't use X", "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::Other("user-prompt".to_string()),
            &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)
/// - "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();

    // "use X instead of Y"
    if let Some(use_idx) = lower.find("use ") {
        if let Some(instead_idx) = lower.find(" instead of ") {
            let corrected = text[use_idx + 4..instead_idx].trim().to_string();
            let original = text[instead_idx + 12..]
                .trim()
                .trim_end_matches('.')
                .to_string();
            if !corrected.is_empty() && !original.is_empty() {
                return Some((original, corrected));
            }
        }
    }

    // "prefer X over Y"
    if let Some(prefer_idx) = lower.find("prefer ") {
        if let Some(over_idx) = lower.find(" over ") {
            let corrected = text[prefer_idx + 7..over_idx].trim().to_string();
            let original = text[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.
#[derive(Debug, Error)]
#[allow(dead_code)]
pub enum HookError {
    /// Failed to read from stdin
    #[error("failed to read stdin: {0}")]
    StdinError(#[from] std::io::Error),
    /// Failed to parse hook input JSON
    #[error("failed to parse hook input: {0}")]
    ParseError(#[from] serde_json::Error),
    /// Capture operation failed
    #[error("capture failed: {0}")]
    CaptureError(#[from] LearningError),
}

/// 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"),
        }
    }

    #[test]
    fn test_agent_format_variants() {
        // Verify AgentFormat enum variants exist and are distinct
        assert_ne!(AgentFormat::Claude, AgentFormat::Codex);
        assert_ne!(AgentFormat::Claude, AgentFormat::Opencode);
        assert_ne!(AgentFormat::Codex, AgentFormat::Opencode);
    }

    #[test]
    fn test_hook_passthrough_redacts_aws_key_in_error() {
        use crate::learnings::redact_secrets;
        use crate::learnings::redaction::contains_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 the input contains secrets
        assert!(contains_secrets(&json));

        // 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_no_match() {
        assert!(parse_correction_pattern("hello world").is_none());
        assert!(parse_correction_pattern("this is fine").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
    }
}