zam 0.8.0

Enhanced shell history manager with sensitive data redaction
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
//! History management for zam
//!
//! This module provides comprehensive history management functionality,
//! including logging, importing, searching, and maintaining command history
//! with automatic redaction and deduplication.

use crate::config::Config;
use crate::error::{Error, Result};
use crate::redaction::{RedactionEngine, RedactionStats};
use chrono::{DateTime, Utc};
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::PathBuf;

/// Represents a single command entry in the history
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct HistoryEntry {
    /// The command that was executed
    pub command: String,
    /// Timestamp when the command was executed
    pub timestamp: DateTime<Utc>,
    /// Working directory where the command was executed
    pub directory: String,
    /// Whether this command was redacted
    pub redacted: bool,
    /// Original command before redaction (for debugging, if enabled)
    pub original: Option<String>,
    /// Whether this entry is marked as deleted
    pub deleted: bool,
}

/// Statistics about the history
#[derive(Debug, Clone, Default)]
pub struct HistoryStats {
    /// Total number of entries
    pub total_entries: usize,
    /// Number of redacted entries
    pub redacted_entries: usize,
    /// Number of unique commands
    pub unique_commands: usize,
    /// Number of duplicate commands filtered
    pub duplicates_filtered: usize,
    /// Most common directories
    pub common_directories: HashMap<String, usize>,
    /// Redaction statistics
    pub redaction_stats: RedactionStats,
}

/// Main history manager
pub struct HistoryManager {
    config: Config,
    redaction_engine: RedactionEngine,
    history_file: PathBuf,
    stats: HistoryStats,
}

impl HistoryManager {
    /// Create a new history manager with the given configuration
    #[must_use = "History manager must be used to log commands"]
    pub fn new(config: Config) -> Result<Self> {
        let redaction_engine = RedactionEngine::with_config(
            config.redaction.use_builtin_patterns,
            config.redaction.custom_patterns.clone(),
            config.redaction.exclude_patterns.clone(),
            config.redaction.placeholder.clone(),
            config.redaction.min_redaction_length,
            config.custom_env_vars.clone(),
            config.redaction.redact_env_vars,
        )?;

        let history_file = config.history_file.clone();

        // Create history file if it doesn't exist
        if !history_file.exists() {
            if let Some(parent) = history_file.parent() {
                std::fs::create_dir_all(parent)?;
            }
            File::create(&history_file)?;
        }

        let mut manager = Self {
            config,
            redaction_engine,
            history_file,
            stats: HistoryStats::default(),
        };

        // Load initial statistics
        manager.update_stats()?;

        Ok(manager)
    }

    /// Log a command to the history
    pub fn log_command(&mut self, command: &str) -> Result<()> {
        self.log_command_with_timestamp(command, None)
    }

    /// Log a command with a specific timestamp
    pub fn log_command_with_timestamp(
        &mut self,
        command: &str,
        timestamp: Option<DateTime<Utc>>,
    ) -> Result<()> {
        // Check if we should exclude this command
        if self.config.should_exclude_command(command) {
            return Ok(());
        }

        let timestamp = timestamp.unwrap_or_else(Utc::now);
        let directory = env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("<unknown>"))
            .to_string_lossy()
            .to_string();

        // Redact sensitive information
        let (redacted_command, was_redacted) =
            if self.config.enable_redaction && !self.config.should_skip_redaction(command) {
                let original = command.to_string();
                let redacted = self
                    .redaction_engine
                    .redact_with_stats(command, &mut self.stats.redaction_stats)?;
                (redacted.clone(), redacted != original)
            } else {
                (command.to_string(), false)
            };

        let entry = HistoryEntry {
            command: redacted_command,
            timestamp,
            directory,
            redacted: was_redacted,
            original: if was_redacted && self.config.logging.log_redacted_commands {
                Some(command.to_string())
            } else {
                None
            },
            deleted: false,
        };

        // Check for duplicates if configured
        if !self.config.shell_integration.log_duplicates && self.is_duplicate(&entry)? {
            self.stats.duplicates_filtered += 1;
            return Ok(());
        }

        self.write_entry(&entry)?;
        self.update_stats_for_entry(&entry);

        // Trim history if it exceeds max entries
        if self.config.max_entries > 0 && self.stats.total_entries > self.config.max_entries {
            self.trim_history()?;
        }

        Ok(())
    }

    /// Import history from a shell history file
    pub fn import_from_shell(&mut self, shell: &str, file_path: Option<PathBuf>) -> Result<usize> {
        let history_path = if let Some(path) = file_path {
            path
        } else {
            self.config
                .import
                .shell_history_paths
                .get(shell)
                .ok_or_else(|| Error::import_failed(shell, "shell not configured"))?
                .clone()
        };

        if !history_path.exists() {
            return Err(Error::HistoryFileNotFound { path: history_path });
        }

        let file = File::open(&history_path)?;
        let reader = BufReader::new(file);
        let mut imported_count = 0;
        let mut seen_commands = HashSet::new();

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

            let entry = match shell {
                "zsh" => self.parse_zsh_entry(&line)?,
                "bash" => self.parse_bash_entry(&line)?,
                "fish" => self.parse_fish_entry(&line)?,
                _ => return Err(Error::import_failed(shell, "unsupported shell")),
            };

            if let Some(entry) = entry {
                // Check age limit
                if self.config.import.max_age_days > 0 {
                    let age_limit =
                        Utc::now() - chrono::Duration::days(self.config.import.max_age_days as i64);
                    if entry.timestamp < age_limit {
                        continue;
                    }
                }

                // Check for duplicates if deduplication is enabled
                if self.config.import.deduplicate {
                    let key = format!("{}:{}", entry.command, entry.directory);
                    if !seen_commands.insert(key) {
                        continue;
                    }
                }

                self.write_entry(&entry)?;
                imported_count += 1;
            }
        }

        self.update_stats()?;
        Ok(imported_count)
    }

    /// Get all history entries
    #[must_use = "Query results should be used"]
    pub fn get_entries(&self) -> Result<Vec<HistoryEntry>> {
        let file = File::open(&self.history_file)?;
        let reader = BufReader::new(file);
        let mut entries = Vec::new();

        for line in reader.lines() {
            let line = line?;
            if let Some(entry) = self.parse_entry(&line)? {
                entries.push(entry);
            }
        }

        Ok(entries)
    }

    /// Search history entries
    #[must_use = "Search results should be used"]
    pub fn search(&self, query: &str, directory_filter: Option<&str>) -> Result<Vec<HistoryEntry>> {
        let entries = self.get_entries()?;
        let mut results = Vec::new();

        let query_lower = query.to_lowercase();

        for entry in entries {
            // Apply directory filter if specified
            if let Some(dir_filter) = directory_filter
                && !entry.directory.contains(dir_filter)
            {
                continue;
            }

            // Check if command matches query
            let matches = if self.config.search.case_sensitive {
                entry.command.contains(query)
            } else {
                entry.command.to_lowercase().contains(&query_lower)
            };

            if matches {
                results.push(entry);
            }

            // Limit results
            if results.len() >= self.config.search.max_results {
                break;
            }
        }

        Ok(results)
    }

    /// Get unique commands for fuzzy search
    pub fn get_unique_commands(&self) -> Result<Vec<String>> {
        let entries = self.get_entries()?;
        let mut seen = HashSet::new();
        let mut commands = Vec::new();

        // Reverse iteration to get most recent commands first
        for entry in entries.into_iter().rev() {
            if seen.insert(entry.command.clone()) {
                commands.push(entry.command);
            }
        }

        Ok(commands)
    }

    /// Get history statistics
    pub fn get_stats(&mut self) -> Result<&HistoryStats> {
        self.update_stats()?;
        Ok(&self.stats)
    }

    /// Clear all history
    pub fn clear(&mut self) -> Result<()> {
        std::fs::write(&self.history_file, "")?;
        self.stats = HistoryStats::default();
        Ok(())
    }

    /// Trim history to max entries
    fn trim_history(&mut self) -> Result<()> {
        let entries = self.get_entries()?;
        let keep_count = self.config.max_entries;

        if entries.len() <= keep_count {
            return Ok(());
        }

        // Keep the most recent entries
        let entries_to_keep = &entries[entries.len() - keep_count..];

        // Rewrite the file with only the entries we want to keep
        let file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&self.history_file)?;
        let mut writer = BufWriter::new(file);

        for entry in entries_to_keep {
            writeln!(writer, "{}", self.format_entry(entry))?;
        }

        writer.flush()?;
        self.update_stats()?;

        Ok(())
    }

    /// Write a single entry to the history file
    fn write_entry(&self, entry: &HistoryEntry) -> Result<()> {
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.history_file)?;

        writeln!(file, "{}", self.format_entry(entry))?;
        Ok(())
    }

    /// Format an entry for writing to the log file
    ///
    /// Format: `[ISO8601] dir=/path cmd=command`
    /// Newlines in commands are escaped as `\n`.
    fn format_entry(&self, entry: &HistoryEntry) -> String {
        let timestamp_str = entry
            .timestamp
            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
        let escaped_cmd = entry.command.replace('\\', "\\\\").replace('\n', "\\n");
        let deleted_marker = if entry.deleted { " deleted=true" } else { "" };
        format!(
            "[{}] dir={} cmd={}{}",
            timestamp_str, entry.directory, escaped_cmd, deleted_marker
        )
    }

    /// Parse a line from the log file
    ///
    /// Format: `[ISO8601] dir=/path cmd=command`
    fn parse_entry(&self, line: &str) -> Result<Option<HistoryEntry>> {
        let line = line.trim();
        if !line.starts_with('[') {
            return Ok(None);
        }

        let close_bracket = match line.find("] ") {
            Some(pos) => pos,
            None => return Ok(None),
        };

        let timestamp_str = &line[1..close_bracket];
        let rest = &line[close_bracket + 2..];

        let timestamp: DateTime<Utc> =
            timestamp_str.parse().map_err(|_| Error::InvalidTimestamp {
                timestamp: timestamp_str.to_string(),
            })?;

        let dir_prefix = "dir=";
        if !rest.starts_with(dir_prefix) {
            return Ok(None);
        }

        let after_dir = &rest[dir_prefix.len()..];
        let cmd_marker = " cmd=";
        let cmd_pos = match after_dir.find(cmd_marker) {
            Some(pos) => pos,
            None => return Ok(None),
        };

        let directory = after_dir[..cmd_pos].to_string();
        let mut remaining = after_dir[cmd_pos + cmd_marker.len()..].to_string();

        let was_deleted = remaining.ends_with(" deleted=true");
        if was_deleted {
            remaining = remaining.trim_end_matches(" deleted=true").to_string();
        }

        // Unescape: \\n -> \n, \\\\ -> \\
        let command = remaining.replace("\\n", "\n").replace("\\\\", "\\");
        let was_redacted = command.contains("<redacted>");

        Ok(Some(HistoryEntry {
            command,
            timestamp,
            directory,
            redacted: was_redacted,
            deleted: was_deleted,
            original: None,
        }))
    }

    /// Parse a Zsh history entry
    fn parse_zsh_entry(&self, line: &str) -> Result<Option<HistoryEntry>> {
        // Zsh format: ": 1609786800:0;command"
        let re = regex::Regex::new(r"^: (\d+):\d+;(.*)").unwrap();

        if let Some(caps) = re.captures(line) {
            let timestamp_str = caps.get(1).unwrap().as_str();
            let command = caps.get(2).unwrap().as_str();

            let timestamp = timestamp_str
                .parse::<i64>()
                .map_err(|_| Error::InvalidTimestamp {
                    timestamp: timestamp_str.to_string(),
                })?;

            let datetime =
                DateTime::from_timestamp(timestamp, 0).ok_or_else(|| Error::InvalidTimestamp {
                    timestamp: timestamp_str.to_string(),
                })?;

            let (redacted_command, was_redacted) =
                if self.config.enable_redaction && !self.config.should_skip_redaction(command) {
                    let original = command.to_string();
                    let redacted = self.redaction_engine.redact(command)?;
                    (redacted.clone(), redacted != original)
                } else {
                    (command.to_string(), false)
                };

            Ok(Some(HistoryEntry {
                command: redacted_command,
                timestamp: datetime,
                directory: "<imported>".to_string(),
                redacted: was_redacted,
                deleted: false,
                original: None,
            }))
        } else {
            Ok(None)
        }
    }

    /// Parse a Bash history entry
    fn parse_bash_entry(&self, line: &str) -> Result<Option<HistoryEntry>> {
        // Bash history is usually just the command, no timestamp
        if line.starts_with('#') {
            return Ok(None); // Skip comments
        }

        let (redacted_command, was_redacted) =
            if self.config.enable_redaction && !self.config.should_skip_redaction(line) {
                let original = line.to_string();
                let redacted = self.redaction_engine.redact(line)?;
                (redacted.clone(), redacted != original)
            } else {
                (line.to_string(), false)
            };

        Ok(Some(HistoryEntry {
            command: redacted_command,
            timestamp: Utc::now(), // No timestamp available
            directory: "<imported>".to_string(),
            redacted: was_redacted,
            deleted: false,
            original: None,
        }))
    }

    /// Parse a Fish history entry
    fn parse_fish_entry(&self, line: &str) -> Result<Option<HistoryEntry>> {
        // Fish format: "- cmd: command\n  when: timestamp\n  paths: [...]"
        // This is a simplified parser for the most common case
        if let Some(command) = line.strip_prefix("- cmd: ") {
            let (redacted_command, was_redacted) =
                if self.config.enable_redaction && !self.config.should_skip_redaction(command) {
                    let original = command.to_string();
                    let redacted = self.redaction_engine.redact(command)?;
                    (redacted.clone(), redacted != original)
                } else {
                    (command.to_string(), false)
                };

            Ok(Some(HistoryEntry {
                command: redacted_command,
                timestamp: Utc::now(), // Would need to parse next lines for timestamp
                directory: "<imported>".to_string(),
                redacted: was_redacted,
                deleted: false,
                original: None,
            }))
        } else {
            Ok(None)
        }
    }

    /// Check if an entry is a duplicate
    fn is_duplicate(&self, entry: &HistoryEntry) -> Result<bool> {
        // Read the last few entries to check for duplicates
        let file = File::open(&self.history_file)?;
        let reader = BufReader::new(file);
        let mut recent_commands = Vec::new();

        // Only check the last 100 entries for performance
        let lines: Vec<String> = reader.lines().collect::<std::result::Result<Vec<_>, _>>()?;
        for line in lines.iter().rev().take(100) {
            if let Some(parsed_entry) = self.parse_entry(line)? {
                recent_commands.push(parsed_entry.command);
            }
        }

        Ok(recent_commands.contains(&entry.command))
    }

    /// Update statistics
    fn update_stats(&mut self) -> Result<()> {
        let entries = self.get_entries()?;
        let mut unique_commands = HashSet::new();
        let mut common_directories = HashMap::new();
        let mut redacted_count = 0;

        for entry in &entries {
            unique_commands.insert(entry.command.clone());
            *common_directories
                .entry(entry.directory.clone())
                .or_insert(0) += 1;
            if entry.redacted {
                redacted_count += 1;
            }
        }

        self.stats.total_entries = entries.len();
        self.stats.unique_commands = unique_commands.len();
        self.stats.redacted_entries = redacted_count;
        self.stats.common_directories = common_directories;

        Ok(())
    }

    /// Update statistics for a single entry
    fn update_stats_for_entry(&mut self, entry: &HistoryEntry) {
        self.stats.total_entries += 1;
        if entry.redacted {
            self.stats.redacted_entries += 1;
        }
        *self
            .stats
            .common_directories
            .entry(entry.directory.clone())
            .or_insert(0) += 1;
    }
}

impl HistoryEntry {
    /// Create a new history entry
    pub fn new(command: String, timestamp: DateTime<Utc>, directory: String) -> Self {
        Self {
            command,
            timestamp,
            directory,
            redacted: false,
            original: None,
            deleted: false,
        }
    }

    /// Get the command as a string for display
    pub fn display_command(&self) -> &str {
        &self.command
    }

    /// Get formatted timestamp
    pub fn formatted_timestamp(&self) -> String {
        self.timestamp.format("%Y-%m-%d %H:%M:%S").to_string()
    }

    /// Get relative directory (basename)
    pub fn relative_directory(&self) -> String {
        PathBuf::from(&self.directory)
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string()
    }
}

/// Conversion from database CommandEntry to HistoryEntry
impl From<crate::database::CommandEntry> for HistoryEntry {
    fn from(cmd: crate::database::CommandEntry) -> Self {
        Self {
            command: cmd.command,
            timestamp: cmd.timestamp,
            directory: cmd.directory,
            redacted: cmd.redacted,
            original: None,
            deleted: false, // Database entries aren't deleted by default
        }
    }
}

/// Implementation of HistoryProvider trait for file-based backend
impl crate::backend::HistoryProvider for HistoryManager {
    fn get_entries(&self) -> Result<Vec<HistoryEntry>> {
        self.get_entries()
    }

    fn get_recent(&self, count: usize) -> Result<Vec<HistoryEntry>> {
        let mut entries = self.get_entries()?;
        entries.reverse();
        entries.truncate(count);
        Ok(entries)
    }

    fn search(&self, query: &str) -> Result<Vec<HistoryEntry>> {
        self.search(query, None)
    }

    fn log_command(&mut self, command: &str) -> Result<()> {
        self.log_command(command)
    }

    fn clear(&mut self) -> Result<()> {
        self.clear()
    }

    fn delete_entries(&mut self, indices: &[usize]) -> Result<usize> {
        if indices.is_empty() {
            return Ok(0);
        }

        // Read all entries
        let mut entries = self.get_entries()?;
        let mut deleted_count = 0;

        // Mark entries as deleted
        for &idx in indices {
            if let Some(entry) = entries.get_mut(idx)
                && !entry.deleted
            {
                entry.deleted = true;
                deleted_count += 1;
            }
        }

        // Rewrite the history file with deleted markers
        let file = File::create(&self.history_file)?;
        let mut writer = BufWriter::new(file);

        for entry in &entries {
            writeln!(writer, "{}", self.format_entry(entry))?;
        }
        writer.flush()?;

        Ok(deleted_count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use tempfile::NamedTempFile;

    fn test_config() -> Config {
        let temp_file = NamedTempFile::new().unwrap();
        let mut config = Config {
            history_file: temp_file.path().to_path_buf(),
            max_entries: 1000,
            ..Default::default()
        };
        config.shell_integration.exclude_commands.clear(); // Don't exclude any commands in tests
        config
    }

    #[test]
    fn test_history_manager_creation() {
        let config = test_config();
        let manager = HistoryManager::new(config);
        assert!(manager.is_ok());
    }

    #[test]
    fn test_log_command() {
        let config = test_config();
        let mut manager = HistoryManager::new(config).unwrap();

        let result = manager.log_command("echo hello world");
        assert!(result.is_ok());

        let entries = manager.get_entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].command, "echo hello world");
    }

    #[test]
    fn test_redaction_in_logging() {
        let config = test_config();
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("password=secret123").unwrap();

        let entries = manager.get_entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].command.contains("<redacted>"));
        assert!(!entries[0].command.contains("secret123"));
    }

    #[test]
    fn test_duplicate_filtering() {
        let mut config = test_config();
        config.shell_integration.log_duplicates = false;
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("echo hello").unwrap();
        manager.log_command("echo hello").unwrap(); // Duplicate
        manager.log_command("echo world").unwrap();

        let entries = manager.get_entries().unwrap();
        assert_eq!(entries.len(), 2); // Should have filtered out the duplicate
    }

    #[test]
    fn test_search() {
        let config = test_config();
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("echo hello").unwrap();
        manager.log_command("ls -la").unwrap();
        manager.log_command("echo world").unwrap();

        let results = manager.search("echo", None).unwrap();
        assert_eq!(results.len(), 2);

        let results = manager.search("ls", None).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_zsh_entry_parsing() {
        let config = test_config();
        let manager = HistoryManager::new(config).unwrap();

        let entry = manager
            .parse_zsh_entry(": 1609786800:0;echo hello world")
            .unwrap();
        assert!(entry.is_some());

        let entry = entry.unwrap();
        assert_eq!(entry.command, "echo hello world");
    }

    #[test]
    fn test_history_stats() {
        let config = test_config();
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("echo hello").unwrap();
        manager.log_command("password=secret").unwrap();
        manager.log_command("ls -la").unwrap();

        let stats = manager.get_stats().unwrap();
        assert_eq!(stats.total_entries, 3);
        assert_eq!(stats.redacted_entries, 1);
        assert_eq!(stats.unique_commands, 3);
    }

    #[test]
    fn test_clear_history() {
        let config = test_config();
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("echo hello").unwrap();
        manager.log_command("ls -la").unwrap();

        assert_eq!(manager.get_entries().unwrap().len(), 2);

        manager.clear().unwrap();
        assert_eq!(manager.get_entries().unwrap().len(), 0);
    }

    #[test]
    fn test_trim_history() {
        let mut config = test_config();
        config.max_entries = 2;
        let mut manager = HistoryManager::new(config).unwrap();

        manager.log_command("command1").unwrap();
        manager.log_command("command2").unwrap();
        manager.log_command("command3").unwrap(); // This should trigger trimming

        let entries = manager.get_entries().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].command, "command2");
        assert_eq!(entries[1].command, "command3");
    }
}