aprender-shell 0.31.1

AI-powered shell completion trained on your history
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
//! Corpus management for synthetic shell command training
//!
//! Provides utilities for loading, validating, and managing training corpora
//! for shell completion models. Supports privacy-safe synthetic data generation.

use std::collections::HashSet;
use std::path::Path;

/// Patterns that indicate sensitive data - these should NEVER appear in a public corpus
const SENSITIVE_PATTERNS: &[&str] = &[
    // Credentials (specific patterns to avoid false positives)
    "password=",
    "password:",
    "passwd=",
    "passwd:",
    "PASSWORD",
    "PASSWD",
    // Secret patterns (avoid catching "kubectl create secret")
    "secret=",
    "secret:",
    "SECRET_",
    "_SECRET",
    // API keys
    "api_key",
    "apikey",
    "api-key",
    "bearer",
    // Auth patterns (more specific to avoid --author false positive)
    "auth_token",
    "auth=",
    "AUTH_",
    "authorization:",
    // AWS
    "AKIA",
    "aws_access",
    "aws_secret",
    // Private paths
    "/home/",
    "/Users/",
    "C:\\Users\\",
    // Hostnames
    ".internal",
    ".local",
    ".corp",
    // SSH
    "id_rsa",
    "id_ed25519",
    ".pem",
    // Environment
    "export ",
    "ENV=",
];

/// Result type for corpus operations
pub type CorpusResult<T> = Result<T, CorpusError>;

/// Errors that can occur during corpus operations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CorpusError {
    /// Corpus file not found
    NotFound(String),
    /// Corpus contains sensitive patterns
    SensitiveData { line: usize, pattern: String },
    /// Corpus is empty
    Empty,
    /// Invalid format
    InvalidFormat(String),
    /// IO error
    IoError(String),
}

impl std::fmt::Display for CorpusError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(path) => write!(f, "Corpus not found: {path}"),
            Self::SensitiveData { line, pattern } => {
                write!(f, "Sensitive pattern '{pattern}' found at line {line}")
            }
            Self::Empty => write!(f, "Corpus is empty"),
            Self::InvalidFormat(msg) => write!(f, "Invalid format: {msg}"),
            Self::IoError(msg) => write!(f, "IO error: {msg}"),
        }
    }
}

impl std::error::Error for CorpusError {}

/// A validated corpus of shell commands
#[derive(Debug, Clone)]
pub struct Corpus {
    /// Commands in the corpus
    commands: Vec<String>,
    /// Unique command prefixes for coverage analysis
    prefixes: HashSet<String>,
}

impl Corpus {
    /// Load corpus from a file, validating for sensitive data
    pub fn load<P: AsRef<Path>>(path: P) -> CorpusResult<Self> {
        let path = path.as_ref();
        let content =
            std::fs::read_to_string(path).map_err(|e| CorpusError::IoError(e.to_string()))?;

        Self::from_string(&content)
    }

    /// Create corpus from string content
    pub fn from_string(content: &str) -> CorpusResult<Self> {
        let mut commands = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Validate for sensitive patterns
            Self::validate_line(line, line_num + 1)?;

            commands.push(line.to_string());
        }

        if commands.is_empty() {
            return Err(CorpusError::Empty);
        }

        // Build prefix set for coverage analysis
        let prefixes: HashSet<String> = commands
            .iter()
            .filter_map(|cmd| cmd.split_whitespace().next())
            .map(String::from)
            .collect();

        Ok(Self { commands, prefixes })
    }

    /// Validate a single line for sensitive patterns
    fn validate_line(line: &str, line_num: usize) -> CorpusResult<()> {
        let lower = line.to_lowercase();

        for pattern in SENSITIVE_PATTERNS {
            if lower.contains(&pattern.to_lowercase()) {
                return Err(CorpusError::SensitiveData {
                    line: line_num,
                    pattern: (*pattern).to_string(),
                });
            }
        }

        Ok(())
    }

    /// Get commands for training
    pub fn commands(&self) -> &[String] {
        &self.commands
    }

    /// Get number of commands
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Check if corpus is empty
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Get unique command prefixes (first word of each command)
    pub fn prefixes(&self) -> &HashSet<String> {
        &self.prefixes
    }

    /// Get coverage statistics
    pub fn coverage_stats(&self) -> CorpusStats {
        let mut token_counts: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        let mut total_tokens = 0;

        for cmd in &self.commands {
            for token in cmd.split_whitespace() {
                *token_counts.entry(token.to_string()).or_insert(0) += 1;
                total_tokens += 1;
            }
        }

        CorpusStats {
            total_commands: self.commands.len(),
            unique_prefixes: self.prefixes.len(),
            unique_tokens: token_counts.len(),
            total_tokens,
        }
    }
}

/// Statistics about a corpus
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorpusStats {
    /// Total number of commands
    pub total_commands: usize,
    /// Number of unique command prefixes
    pub unique_prefixes: usize,
    /// Number of unique tokens
    pub unique_tokens: usize,
    /// Total tokens across all commands
    pub total_tokens: usize,
}

// ============================================================================
// TESTS - EXTREME TDD
// ============================================================================

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

    // ========================================================================
    // Corpus Loading Tests
    // ========================================================================

    #[test]
    fn test_corpus_from_string_basic() {
        let content = "git status\ngit commit -m message\ncargo build";
        let corpus = Corpus::from_string(content).expect("should parse");

        assert_eq!(corpus.len(), 3);
        assert_eq!(corpus.commands()[0], "git status");
        assert_eq!(corpus.commands()[2], "cargo build");
    }

    #[test]
    fn test_corpus_skips_empty_lines() {
        let content = "git status\n\n\ncargo build\n";
        let corpus = Corpus::from_string(content).expect("should parse");

        assert_eq!(corpus.len(), 2);
    }

    #[test]
    fn test_corpus_skips_comments() {
        let content = "# This is a comment\ngit status\n# Another comment\ncargo build";
        let corpus = Corpus::from_string(content).expect("should parse");

        assert_eq!(corpus.len(), 2);
    }

    #[test]
    fn test_corpus_trims_whitespace() {
        let content = "  git status  \n\tcargo build\t";
        let corpus = Corpus::from_string(content).expect("should parse");

        assert_eq!(corpus.commands()[0], "git status");
        assert_eq!(corpus.commands()[1], "cargo build");
    }

    #[test]
    fn test_corpus_empty_returns_error() {
        let content = "\n\n# Only comments\n";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::Empty)));
    }

    // ========================================================================
    // Sensitive Data Detection Tests (CRITICAL)
    // ========================================================================

    #[test]
    fn test_detects_password_pattern() {
        // PASSWORD in uppercase is detected
        let content = "mysql -u root PASSWORD=secret123";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_password_colon_pattern() {
        // password: pattern is detected
        let content = "curl -H 'password: secret123'";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_api_key_pattern() {
        let content = "curl -H 'api_key: secret123'";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_aws_key_pattern() {
        let content = "aws configure set aws_access_key_id AKIA123";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_home_path() {
        let content = "cd /home/username/projects";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_users_path_mac() {
        let content = "ls /Users/john/Documents";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_internal_hostname() {
        let content = "ssh server.internal";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_ssh_key_path() {
        let content = "ssh -i id_rsa user@server";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_detects_export_statement() {
        let content = "export API_KEY=secret";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_sensitive_detection_case_insensitive() {
        let content = "curl -H 'PASSWORD: test'";
        let result = Corpus::from_string(content);

        assert!(matches!(result, Err(CorpusError::SensitiveData { .. })));
    }

    #[test]
    fn test_reports_correct_line_number() {
        let content = "git status\ncargo build\ncurl -H 'api_key: x'";
        let result = Corpus::from_string(content);

        match result {
            Err(CorpusError::SensitiveData { line, .. }) => {
                assert_eq!(line, 3);
            }
            _ => panic!("Expected SensitiveData error"),
        }
    }

    // ========================================================================
    // Safe Commands Tests
    // ========================================================================

    #[test]
    fn test_allows_safe_git_commands() {
        let content = r#"
git status
git commit -m "feat: add feature"
git push origin main
git pull --rebase
git checkout -b feature/new
git log --oneline -10
git diff HEAD~1
git stash pop
"#;
        let corpus = Corpus::from_string(content).expect("should parse");
        assert!(corpus.len() >= 8);
    }

    #[test]
    fn test_allows_safe_docker_commands() {
        let content = r#"
docker build -t myapp .
docker run -d -p 8080:80 nginx
docker compose up -d
docker ps -a
docker logs container_name
docker exec -it container_name bash
"#;
        let corpus = Corpus::from_string(content).expect("should parse");
        assert!(corpus.len() >= 6);
    }

    #[test]
    fn test_allows_safe_cargo_commands() {
        let content = r#"
cargo build --release
cargo test --all-features
cargo clippy -- -D warnings
cargo fmt --check
cargo run --example demo
cargo doc --open
"#;
        let corpus = Corpus::from_string(content).expect("should parse");
        assert!(corpus.len() >= 6);
    }

    // ========================================================================
    // Coverage Statistics Tests
    // ========================================================================

    #[test]
    fn test_prefixes_extraction() {
        let content = "git status\ngit commit\ncargo build\ncargo test";
        let corpus = Corpus::from_string(content).expect("should parse");

        assert_eq!(corpus.prefixes().len(), 2);
        assert!(corpus.prefixes().contains("git"));
        assert!(corpus.prefixes().contains("cargo"));
    }

    #[test]
    fn test_coverage_stats() {
        let content = "git status\ngit commit -m msg";
        let corpus = Corpus::from_string(content).expect("should parse");
        let stats = corpus.coverage_stats();

        assert_eq!(stats.total_commands, 2);
        assert_eq!(stats.unique_prefixes, 1); // just "git"
        assert_eq!(stats.total_tokens, 6); // git, status, git, commit, -m, msg
    }

    // ========================================================================
    // Error Display Tests
    // ========================================================================

    #[test]
    fn test_error_display_not_found() {
        let err = CorpusError::NotFound("/path/to/file".into());
        assert!(err.to_string().contains("/path/to/file"));
    }

    #[test]
    fn test_error_display_sensitive() {
        let err = CorpusError::SensitiveData {
            line: 42,
            pattern: "password".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("password"));
        assert!(msg.contains("42"));
    }
}