coding-agent-search 0.6.2

Unified TUI search over local coding agent histories
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
//! Password strength validation and visual feedback.
//!
//! Provides real-time password strength validation with consistent behavior
//! between CLI (Rust) and browser (JavaScript) implementations.
//!
//! # Strength Levels
//!
//! | Level | Entropy | Requirements |
//! |-------|---------|--------------|
//! | Weak | <20 bits | Missing multiple requirements |
//! | Fair | 20-40 bits | Missing some requirements |
//! | Good | 40-60 bits | Most requirements met |
//! | Strong | ≥60 bits | All requirements met, 12+ chars |

use console::{Term, style};
use std::io::Write;

/// Password strength levels with associated colors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PasswordStrength {
    Weak,
    Fair,
    Good,
    Strong,
}

#[derive(Debug, Clone, Copy)]
struct PasswordStrengthVisuals {
    color: &'static str,
    label: &'static str,
    bar: &'static str,
    percent: u8,
}

impl PasswordStrength {
    fn visuals(self) -> PasswordStrengthVisuals {
        match self {
            Self::Weak => PasswordStrengthVisuals {
                color: "red",
                label: "Weak",
                bar: "[█░░░]",
                percent: 25,
            },
            Self::Fair => PasswordStrengthVisuals {
                color: "yellow",
                label: "Fair",
                bar: "[██░░]",
                percent: 50,
            },
            Self::Good => PasswordStrengthVisuals {
                color: "blue",
                label: "Good",
                bar: "[███░]",
                percent: 75,
            },
            Self::Strong => PasswordStrengthVisuals {
                color: "green",
                label: "Strong",
                bar: "[████]",
                percent: 100,
            },
        }
    }

    /// Get the ANSI color name for this strength level.
    pub fn color(&self) -> &'static str {
        self.visuals().color
    }

    /// Get a human-readable label.
    pub fn label(&self) -> &'static str {
        self.visuals().label
    }

    /// Get the progress bar representation (4 segments).
    pub fn bar(&self) -> &'static str {
        self.visuals().bar
    }

    /// Get the percentage (0-100) for progress bar width.
    pub fn percent(&self) -> u8 {
        self.visuals().percent
    }
}

impl std::fmt::Display for PasswordStrength {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.label())
    }
}

/// Result of password validation.
#[derive(Debug, Clone)]
pub struct PasswordValidation {
    /// Overall strength level.
    pub strength: PasswordStrength,
    /// Computed entropy score (0-7 based on criteria).
    pub score: u8,
    /// Entropy in bits.
    pub entropy_bits: f64,
    /// List of improvement suggestions.
    pub suggestions: Vec<&'static str>,
    /// Individual requirement checks.
    pub checks: PasswordChecks,
}

/// Individual password requirement checks.
#[derive(Debug, Clone, Copy)]
pub struct PasswordChecks {
    pub has_lowercase: bool,
    pub has_uppercase: bool,
    pub has_digit: bool,
    pub has_special: bool,
    pub length: usize,
    pub meets_min_length: bool,
}

/// Validate a password and return strength assessment with suggestions.
///
/// # Algorithm
///
/// 1. Check for presence of lowercase, uppercase, digits, and special characters
/// 2. Compute length score: 0 (0-7), 1 (8-11), 2 (12-15), 3 (16+)
/// 3. Sum all criteria to get score (0-7)
/// 4. Map score to strength level
///
/// # Example
///
/// ```
/// use coding_agent_search::pages::password::{PasswordStrength, validate_password};
///
/// let result = validate_password("MySecureP@ssw0rd!");
/// assert_eq!(result.strength, PasswordStrength::Strong);
/// assert!(result.suggestions.is_empty());
/// ```
pub fn validate_password(password: &str) -> PasswordValidation {
    let length = password.chars().count();
    let has_upper = password.chars().any(|c| c.is_ascii_uppercase());
    let has_lower = password.chars().any(|c| c.is_ascii_lowercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());

    // Length scoring (0-3 points)
    let length_score: u8 = match length {
        0..=7 => 0,
        8..=11 => 1,
        12..=15 => 2,
        _ => 3,
    };

    // Total score (0-7)
    let score =
        length_score + has_upper as u8 + has_lower as u8 + has_digit as u8 + has_special as u8;

    // Collect improvement suggestions
    let mut suggestions = Vec::new();
    if length < 12 {
        suggestions.push("Use at least 12 characters");
    }
    if !has_upper {
        suggestions.push("Add uppercase letters");
    }
    if !has_lower {
        suggestions.push("Add lowercase letters");
    }
    if !has_digit {
        suggestions.push("Add numbers");
    }
    if !has_special {
        suggestions.push("Add special characters (!@#$%^&*)");
    }

    // Map score to strength
    let strength = match score {
        0..=2 => PasswordStrength::Weak,
        3..=4 => PasswordStrength::Fair,
        5..=6 => PasswordStrength::Good,
        _ => PasswordStrength::Strong,
    };

    // Calculate entropy bits for compatibility with confirmation.rs
    let entropy_bits = estimate_entropy(password);

    PasswordValidation {
        strength,
        score,
        entropy_bits,
        suggestions,
        checks: PasswordChecks {
            has_lowercase: has_lower,
            has_uppercase: has_upper,
            has_digit,
            has_special,
            length,
            meets_min_length: length >= 12,
        },
    }
}

/// Calculate password entropy using character class analysis.
///
/// This mirrors the algorithm in `confirmation.rs::estimate_password_entropy`
/// for consistency.
fn estimate_entropy(password: &str) -> f64 {
    if password.is_empty() {
        return 0.0;
    }

    let has_lower = password.chars().any(|c| c.is_ascii_lowercase());
    let has_upper = password.chars().any(|c| c.is_ascii_uppercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());

    let mut pool_size = 0u32;
    if has_lower {
        pool_size += 26;
    }
    if has_upper {
        pool_size += 26;
    }
    if has_digit {
        pool_size += 10;
    }
    if has_special {
        pool_size += 32;
    }

    if pool_size == 0 {
        pool_size = 26; // Assume lowercase if nothing else
    }

    let bits_per_char = (pool_size as f64).log2();
    let length = password.chars().count() as f64;

    bits_per_char * length
}

/// Display password strength in the terminal with colored progress bar.
///
/// Clears the current line and writes:
/// ```text
/// Strength: [████] Strong
///   • Add special characters (!@#$%^&*)
/// ```
pub fn display_strength(term: &mut Term, validation: &PasswordValidation) -> std::io::Result<()> {
    let strength = &validation.strength;

    // Choose color based on strength
    let colored_bar = match strength {
        PasswordStrength::Weak => style(strength.bar()).red(),
        PasswordStrength::Fair => style(strength.bar()).yellow(),
        PasswordStrength::Good => style(strength.bar()).blue(),
        PasswordStrength::Strong => style(strength.bar()).green(),
    };

    let colored_label = match strength {
        PasswordStrength::Weak => style(strength.label()).red().bold(),
        PasswordStrength::Fair => style(strength.label()).yellow().bold(),
        PasswordStrength::Good => style(strength.label()).blue().bold(),
        PasswordStrength::Strong => style(strength.label()).green().bold(),
    };

    // Clear line and write strength indicator
    term.clear_line()?;
    write!(term, "Strength: {} {}", colored_bar, colored_label)?;

    // Show suggestions if any
    if !validation.suggestions.is_empty() {
        writeln!(term)?;
        for suggestion in &validation.suggestions {
            writeln!(term, "  {} {}", style("").dim(), style(suggestion).dim())?;
        }
    }

    term.flush()?;
    Ok(())
}

/// Format password strength as a simple inline indicator.
///
/// Returns a string like "[████] Strong" with ANSI colors.
pub fn format_strength_inline(validation: &PasswordValidation) -> String {
    let strength = &validation.strength;

    let bar = match strength {
        PasswordStrength::Weak => style(strength.bar()).red(),
        PasswordStrength::Fair => style(strength.bar()).yellow(),
        PasswordStrength::Good => style(strength.bar()).blue(),
        PasswordStrength::Strong => style(strength.bar()).green(),
    };

    let label = match strength {
        PasswordStrength::Weak => style(strength.label()).red().bold(),
        PasswordStrength::Fair => style(strength.label()).yellow().bold(),
        PasswordStrength::Good => style(strength.label()).blue().bold(),
        PasswordStrength::Strong => style(strength.label()).green().bold(),
    };

    format!("{} {}", bar, label)
}

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

    #[test]
    fn test_empty_password() {
        let result = validate_password("");
        assert_eq!(result.strength, PasswordStrength::Weak);
        assert!(!result.suggestions.is_empty());
    }

    #[test]
    fn test_weak_password() {
        let result = validate_password("password");
        assert_eq!(result.strength, PasswordStrength::Weak);
        assert!(result.suggestions.contains(&"Add uppercase letters"));
        assert!(result.suggestions.contains(&"Add numbers"));
        assert!(
            result
                .suggestions
                .contains(&"Add special characters (!@#$%^&*)")
        );
    }

    #[test]
    fn test_fair_password() {
        let result = validate_password("Password1");
        assert_eq!(result.strength, PasswordStrength::Fair);
    }

    #[test]
    fn test_good_password() {
        let result = validate_password("Password1!");
        assert_eq!(result.strength, PasswordStrength::Good);
    }

    #[test]
    fn test_strong_password() {
        let result = validate_password("MySecureP@ssw0rd!");
        assert_eq!(result.strength, PasswordStrength::Strong);
        assert!(result.suggestions.is_empty());
    }

    #[test]
    fn test_long_lowercase_only() {
        // Long but only lowercase - should be fair due to length
        let result = validate_password("averylongpasswordwithnothingelse");
        assert!(matches!(
            result.strength,
            PasswordStrength::Fair | PasswordStrength::Good
        ));
    }

    #[test]
    fn test_strength_bar_rendering() {
        let cases = [
            (PasswordStrength::Weak, "[█░░░]"),
            (PasswordStrength::Fair, "[██░░]"),
            (PasswordStrength::Good, "[███░]"),
            (PasswordStrength::Strong, "[████]"),
        ];

        for (strength, expected_bar) in cases {
            assert_eq!(strength.bar(), expected_bar, "{strength:?}");
        }
    }

    #[test]
    fn test_strength_color_and_label() {
        let cases = [
            (PasswordStrength::Weak, "red", "Weak"),
            (PasswordStrength::Fair, "yellow", "Fair"),
            (PasswordStrength::Good, "blue", "Good"),
            (PasswordStrength::Strong, "green", "Strong"),
        ];

        for (strength, expected_color, expected_label) in cases {
            assert_eq!(strength.color(), expected_color, "{strength:?}");
            assert_eq!(strength.label(), expected_label, "{strength:?}");
            assert_eq!(strength.to_string(), expected_label, "{strength:?}");
        }
    }

    #[test]
    fn test_strength_percent() {
        let cases = [
            (PasswordStrength::Weak, 25),
            (PasswordStrength::Fair, 50),
            (PasswordStrength::Good, 75),
            (PasswordStrength::Strong, 100),
        ];

        for (strength, expected_percent) in cases {
            assert_eq!(strength.percent(), expected_percent, "{strength:?}");
        }
    }

    #[test]
    fn test_checks_populated() {
        let result = validate_password("Test123!");
        assert!(result.checks.has_lowercase);
        assert!(result.checks.has_uppercase);
        assert!(result.checks.has_digit);
        assert!(result.checks.has_special);
        assert_eq!(result.checks.length, 8);
        assert!(!result.checks.meets_min_length);
    }

    #[test]
    fn test_entropy_calculation() {
        // All character classes: pool_size = 26+26+10+32 = 94
        // log2(94) ≈ 6.55 bits per char
        // 16 chars → ~105 bits
        let result = validate_password("MySecureP@ssw0rd");
        assert!(result.entropy_bits > 80.0);
    }

    #[test]
    fn test_unicode_password() {
        // Unicode characters should be handled (treated as special)
        let result = validate_password("Pässwörd123!");
        assert!(result.checks.has_special); // ä and ö are special
        assert!(result.checks.has_uppercase);
        assert!(result.checks.has_digit);
    }
}