zam 0.5.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
//! Search engine for zam
//!
//! This module provides advanced search capabilities for command history,
//! including fuzzy search, filtering, ranking, and result highlighting.

use crate::error::Result;
use crate::history::HistoryEntry;
use regex::Regex;
use std::collections::HashMap;

/// Result of a match operation: (is_match, match_ranges, score)
type MatchResult = (bool, Vec<(usize, usize)>, f64);

/// Search engine for history entries
#[derive(Debug, Clone)]
pub struct SearchEngine {
    /// Whether to enable fuzzy search by default
    pub fuzzy_search: bool,
    /// Whether to enable case-sensitive search by default
    pub case_sensitive: bool,
    /// Whether to include directory information in search results
    pub include_directory: bool,
    /// Whether to include timestamps in search results
    pub include_timestamps: bool,
    /// Maximum number of search results to return
    pub max_results: usize,
    /// Whether to highlight matches in search results
    pub highlight_matches: bool,
}

/// Search query with various filters and options
#[derive(Debug, Clone)]
pub struct SearchQuery {
    /// The search term
    pub term: String,
    /// Optional directory filter
    pub directory: Option<String>,
    /// Optional time range filter (start, end)
    pub time_range: Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>,
    /// Whether to use fuzzy matching
    pub fuzzy: bool,
    /// Whether to use case-sensitive matching
    pub case_sensitive: bool,
    /// Whether to use regex matching
    pub regex: bool,
    /// Whether to search only in redacted commands
    pub redacted_only: bool,
    /// Maximum number of results to return
    pub limit: Option<usize>,
}

/// Search result with metadata
#[derive(Debug, Clone)]
pub struct SearchResult {
    /// The history entry
    pub entry: HistoryEntry,
    /// Relevance score (higher is better)
    pub score: f64,
    /// Highlighted command (if highlighting is enabled)
    pub highlighted: Option<String>,
    /// Match positions in the command
    pub matches: Vec<(usize, usize)>,
}

impl SearchEngine {
    /// Create a new search engine with default settings
    pub fn new() -> Self {
        Self {
            fuzzy_search: true,
            case_sensitive: false,
            include_directory: true,
            include_timestamps: false,
            max_results: 1000,
            highlight_matches: true,
        }
    }

    /// Create a new search engine with custom settings
    pub fn with_config(
        fuzzy_search: bool,
        case_sensitive: bool,
        include_directory: bool,
        include_timestamps: bool,
        max_results: usize,
        highlight_matches: bool,
    ) -> Self {
        Self {
            fuzzy_search,
            case_sensitive,
            include_directory,
            include_timestamps,
            max_results,
            highlight_matches,
        }
    }

    /// Search through history entries with a simple query
    pub fn search(&self, entries: &[HistoryEntry], query: &str) -> Result<Vec<SearchResult>> {
        let search_query = SearchQuery {
            term: query.to_string(),
            directory: None,
            time_range: None,
            fuzzy: self.fuzzy_search,
            case_sensitive: self.case_sensitive,
            regex: false,
            redacted_only: false,
            limit: Some(self.max_results),
        };

        self.search_with_query(entries, &search_query)
    }

    /// Search through history entries with a detailed query
    pub fn search_with_query(
        &self,
        entries: &[HistoryEntry],
        query: &SearchQuery,
    ) -> Result<Vec<SearchResult>> {
        let mut results = Vec::new();
        // Compile regex if needed
        let regex = if query.regex {
            Some(if query.case_sensitive {
                Regex::new(&query.term)?
            } else {
                Regex::new(&format!("(?i){}", query.term))?
            })
        } else {
            None
        };

        // Prepare search term
        let search_term = if query.case_sensitive {
            query.term.clone()
        } else {
            query.term.to_lowercase()
        };

        for entry in entries {
            // Apply filters
            if !self.matches_filters(entry, query) {
                continue;
            }

            // Check for match
            let (is_match, matches, score) = if let Some(ref regex) = regex {
                self.regex_match(&entry.command, regex)?
            } else if query.fuzzy {
                self.fuzzy_match(&entry.command, &search_term, query.case_sensitive)
            } else {
                self.exact_match(&entry.command, &search_term, query.case_sensitive)
            };

            if is_match {
                let highlighted = if self.highlight_matches && !matches.is_empty() {
                    Some(self.highlight_command(&entry.command, &matches))
                } else {
                    None
                };

                results.push(SearchResult {
                    entry: entry.clone(),
                    score,
                    highlighted,
                    matches,
                });
            }
        }

        // Sort by score (descending) and then by timestamp (descending)
        results.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| b.entry.timestamp.cmp(&a.entry.timestamp))
        });

        // Apply limit
        if let Some(limit) = query.limit {
            results.truncate(limit);
        }

        Ok(results)
    }

    /// Search for commands that contain sensitive data
    pub fn search_redacted(&self, entries: &[HistoryEntry]) -> Result<Vec<SearchResult>> {
        let mut results = Vec::new();

        for entry in entries {
            if entry.redacted {
                results.push(SearchResult {
                    entry: entry.clone(),
                    score: 1.0,
                    highlighted: None,
                    matches: Vec::new(),
                });
            }
        }

        // Sort by timestamp (descending)
        results.sort_by(|a, b| b.entry.timestamp.cmp(&a.entry.timestamp));

        if results.len() > self.max_results {
            results.truncate(self.max_results);
        }

        Ok(results)
    }

    /// Search for commands from a specific directory
    pub fn search_by_directory(
        &self,
        entries: &[HistoryEntry],
        directory: &str,
    ) -> Result<Vec<SearchResult>> {
        let mut results = Vec::new();

        for entry in entries {
            if entry.directory.contains(directory) {
                results.push(SearchResult {
                    entry: entry.clone(),
                    score: 1.0,
                    highlighted: None,
                    matches: Vec::new(),
                });
            }
        }

        // Sort by timestamp (descending)
        results.sort_by(|a, b| b.entry.timestamp.cmp(&a.entry.timestamp));

        if results.len() > self.max_results {
            results.truncate(self.max_results);
        }

        Ok(results)
    }

    /// Get the most frequently used commands
    pub fn get_frequent_commands(&self, entries: &[HistoryEntry]) -> Result<Vec<(String, usize)>> {
        let mut command_counts = HashMap::new();

        for entry in entries {
            *command_counts.entry(entry.command.clone()).or_insert(0) += 1;
        }

        let mut sorted_commands: Vec<(String, usize)> = command_counts.into_iter().collect();
        sorted_commands.sort_by(|a, b| b.1.cmp(&a.1));

        if sorted_commands.len() > self.max_results {
            sorted_commands.truncate(self.max_results);
        }

        Ok(sorted_commands)
    }

    /// Get the most frequently used directories
    pub fn get_frequent_directories(
        &self,
        entries: &[HistoryEntry],
    ) -> Result<Vec<(String, usize)>> {
        let mut directory_counts = HashMap::new();

        for entry in entries {
            *directory_counts.entry(entry.directory.clone()).or_insert(0) += 1;
        }

        let mut sorted_directories: Vec<(String, usize)> = directory_counts.into_iter().collect();
        sorted_directories.sort_by(|a, b| b.1.cmp(&a.1));

        if sorted_directories.len() > self.max_results {
            sorted_directories.truncate(self.max_results);
        }

        Ok(sorted_directories)
    }

    /// Check if an entry matches the query filters
    fn matches_filters(&self, entry: &HistoryEntry, query: &SearchQuery) -> bool {
        // Directory filter
        if let Some(ref dir_filter) = query.directory
            && !entry.directory.contains(dir_filter)
        {
            return false;
        }

        // Time range filter
        if let Some((start, end)) = query.time_range
            && (entry.timestamp < start || entry.timestamp > end)
        {
            return false;
        }

        // Redacted filter
        if query.redacted_only && !entry.redacted {
            return false;
        }

        true
    }

    /// Perform exact string matching
    fn exact_match(&self, command: &str, search_term: &str, case_sensitive: bool) -> MatchResult {
        let haystack = if case_sensitive {
            command
        } else {
            &command.to_lowercase()
        };

        let mut matches = Vec::new();
        let mut start = 0;
        let mut match_count = 0;

        while let Some(pos) = haystack[start..].find(search_term) {
            let actual_pos = start + pos;
            matches.push((actual_pos, actual_pos + search_term.len()));
            start = actual_pos + search_term.len();
            match_count += 1;
        }

        let is_match = !matches.is_empty();
        let score = if is_match {
            // Higher score for more matches and exact matches at the beginning
            let base_score = match_count as f64;
            let position_bonus = if matches[0].0 == 0 { 0.5 } else { 0.0 };
            let length_ratio = search_term.len() as f64 / command.len() as f64;
            base_score + position_bonus + length_ratio
        } else {
            0.0
        };

        (is_match, matches, score)
    }

    /// Perform fuzzy matching using a simple algorithm
    fn fuzzy_match(&self, command: &str, search_term: &str, case_sensitive: bool) -> MatchResult {
        let haystack = if case_sensitive {
            command.to_string()
        } else {
            command.to_lowercase()
        };

        let needle = if case_sensitive {
            search_term.to_string()
        } else {
            search_term.to_lowercase()
        };

        // Simple fuzzy matching: check if all characters in search term appear in order
        let mut matches = Vec::new();
        let mut haystack_pos = 0;
        let mut needle_pos = 0;
        let mut match_start = None;

        let haystack_chars: Vec<char> = haystack.chars().collect();
        let needle_chars: Vec<char> = needle.chars().collect();

        while haystack_pos < haystack_chars.len() && needle_pos < needle_chars.len() {
            if haystack_chars[haystack_pos] == needle_chars[needle_pos] {
                if match_start.is_none() {
                    match_start = Some(haystack_pos);
                }
                needle_pos += 1;
                if needle_pos == needle_chars.len() {
                    // Found all characters
                    matches.push((match_start.unwrap(), haystack_pos + 1));
                    break;
                }
            }
            haystack_pos += 1;
        }

        let is_match = needle_pos == needle_chars.len();
        let score = if is_match {
            // Calculate score based on how close the match is to exact
            let match_length = if let Some(start) = match_start {
                haystack_pos - start + 1
            } else {
                haystack.len()
            };
            let exact_ratio = needle.len() as f64 / match_length as f64;
            exact_ratio * 0.8 // Fuzzy matches score lower than exact matches
        } else {
            0.0
        };

        (is_match, matches, score)
    }

    /// Perform regex matching
    fn regex_match(&self, command: &str, regex: &Regex) -> Result<MatchResult> {
        let mut matches = Vec::new();

        for mat in regex.find_iter(command) {
            matches.push((mat.start(), mat.end()));
        }

        let is_match = !matches.is_empty();
        let score = if is_match {
            // Score based on number of matches and total matched length
            let total_matched_length: usize = matches.iter().map(|(s, e)| e - s).sum();
            let match_ratio = total_matched_length as f64 / command.len() as f64;
            matches.len() as f64 + match_ratio
        } else {
            0.0
        };

        Ok((is_match, matches, score))
    }

    /// Highlight matches in a command
    fn highlight_command(&self, command: &str, matches: &[(usize, usize)]) -> String {
        if matches.is_empty() {
            return command.to_string();
        }

        let mut result = String::new();
        let mut last_end = 0;

        for &(start, end) in matches {
            // Add text before match
            if start > last_end {
                result.push_str(&command[last_end..start]);
            }

            // Add highlighted match
            result.push_str("\x1b[1;33m"); // Bold yellow
            result.push_str(&command[start..end]);
            result.push_str("\x1b[0m"); // Reset

            last_end = end;
        }

        // Add remaining text
        if last_end < command.len() {
            result.push_str(&command[last_end..]);
        }

        result
    }
}

impl Default for SearchEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl SearchQuery {
    /// Create a new simple search query
    pub fn new(term: String) -> Self {
        Self {
            term,
            directory: None,
            time_range: None,
            fuzzy: true,
            case_sensitive: false,
            regex: false,
            redacted_only: false,
            limit: None,
        }
    }

    /// Set directory filter
    pub fn with_directory(mut self, directory: String) -> Self {
        self.directory = Some(directory);
        self
    }

    /// Set time range filter
    pub fn with_time_range(
        mut self,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
    ) -> Self {
        self.time_range = Some((start, end));
        self
    }

    /// Enable fuzzy matching
    pub fn fuzzy(mut self) -> Self {
        self.fuzzy = true;
        self
    }

    /// Enable case-sensitive matching
    pub fn case_sensitive(mut self) -> Self {
        self.case_sensitive = true;
        self
    }

    /// Enable regex matching
    pub fn regex(mut self) -> Self {
        self.regex = true;
        self
    }

    /// Search only redacted commands
    pub fn redacted_only(mut self) -> Self {
        self.redacted_only = true;
        self
    }

    /// Set result limit
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }
}

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

    fn create_test_entries() -> Vec<HistoryEntry> {
        vec![
            HistoryEntry {
                command: "echo hello world".to_string(),
                timestamp: Utc::now(),
                directory: "/home/user".to_string(),
                redacted: false,
                original: None,
                deleted: false,
            },
            HistoryEntry {
                command: "ls -la".to_string(),
                timestamp: Utc::now(),
                directory: "/home/user/documents".to_string(),
                redacted: false,
                original: None,
                deleted: false,
            },
            HistoryEntry {
                command: "password=<redacted>".to_string(),
                timestamp: Utc::now(),
                directory: "/home/user".to_string(),
                redacted: true,
                original: Some("password=secret123".to_string()),
                deleted: false,
            },
            HistoryEntry {
                command: "echo Hello World".to_string(),
                timestamp: Utc::now(),
                directory: "/tmp".to_string(),
                redacted: false,
                original: None,
                deleted: false,
            },
        ]
    }

    #[test]
    fn test_basic_search() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let results = engine.search(&entries, "echo").unwrap();
        assert_eq!(results.len(), 2);
        assert!(results[0].entry.command.contains("echo"));
        assert!(results[1].entry.command.contains("echo"));
    }

    #[test]
    fn test_case_sensitive_search() {
        let engine = SearchEngine::with_config(false, true, true, false, 1000, true);
        let entries = create_test_entries();

        let results = engine.search(&entries, "Hello").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].entry.command, "echo Hello World");
    }

    #[test]
    fn test_fuzzy_search() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let results = engine.search(&entries, "eh").unwrap();
        assert!(!results.is_empty());
        // Should match "echo" commands
    }

    #[test]
    fn test_directory_search() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let results = engine.search_by_directory(&entries, "documents").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].entry.command, "ls -la");
    }

    #[test]
    fn test_redacted_search() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let results = engine.search_redacted(&entries).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].entry.redacted);
    }

    #[test]
    fn test_query_with_filters() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let query = SearchQuery::new("echo".to_string())
            .with_directory("/home/user".to_string())
            .limit(1);

        let results = engine.search_with_query(&entries, &query).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].entry.directory.contains("/home/user"));
    }

    #[test]
    fn test_frequent_commands() {
        let engine = SearchEngine::new();
        let mut entries = create_test_entries();
        // Add duplicate commands
        entries.push(HistoryEntry {
            command: "echo hello world".to_string(),
            timestamp: Utc::now(),
            directory: "/home/user".to_string(),
            redacted: false,
            original: None,
            deleted: false,
        });

        let frequent = engine.get_frequent_commands(&entries).unwrap();
        assert!(!frequent.is_empty());
        assert_eq!(frequent[0].0, "echo hello world");
        assert_eq!(frequent[0].1, 2);
    }

    #[test]
    fn test_highlighting() {
        let engine = SearchEngine::new();
        let command = "echo hello world";
        let matches = vec![(0, 4), (5, 10)]; // "echo" and "hello"

        let highlighted = engine.highlight_command(command, &matches);
        assert!(highlighted.contains("\x1b[1;33m")); // Should contain color codes
        assert!(highlighted.contains("\x1b[0m")); // Should contain reset codes
    }

    #[test]
    fn test_regex_search() {
        let engine = SearchEngine::new();
        let entries = create_test_entries();

        let query = SearchQuery::new(r"echo.*world".to_string()).regex();
        let results = engine.search_with_query(&entries, &query).unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_search_scoring() {
        let engine = SearchEngine::new();
        let entries = vec![
            HistoryEntry {
                command: "echo test".to_string(), // Should score higher (exact match at start)
                timestamp: Utc::now(),
                directory: "/home/user".to_string(),
                redacted: false,
                original: None,
                deleted: false,
            },
            HistoryEntry {
                command: "some echo command".to_string(), // Should score lower
                timestamp: Utc::now(),
                directory: "/home/user".to_string(),
                redacted: false,
                original: None,
                deleted: false,
            },
        ];

        let results = engine.search(&entries, "echo").unwrap();
        assert_eq!(results.len(), 2);
        // First result should have higher score
        assert!(results[0].score >= results[1].score);
    }
}