aprender-shell 0.41.0

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

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

/// Mutation engine for shell commands
pub struct CommandMutator {
    /// Flag substitutions
    flag_subs: HashMap<&'static str, Vec<&'static str>>,
    /// Command substitutions
    cmd_subs: HashMap<&'static str, Vec<&'static str>>,
}

impl CommandMutator {
    /// Create new mutator with default rules
    #[must_use]
    pub fn new() -> Self {
        let mut flag_subs = HashMap::new();
        flag_subs.insert("-m", vec!["-am", "--message", "-m"]);
        flag_subs.insert("--release", vec!["--debug", ""]);
        flag_subs.insert("--lib", vec!["--bin", "--doc", "--test", ""]);
        flag_subs.insert("-v", vec!["-vv", "-vvv", "--verbose", ""]);
        flag_subs.insert("-a", vec!["--all", ""]);
        flag_subs.insert("-f", vec!["--force", ""]);
        flag_subs.insert("-n", vec!["--dry-run", ""]);
        flag_subs.insert("-i", vec!["--interactive", ""]);
        flag_subs.insert("-r", vec!["-R", "--recursive", ""]);

        let mut cmd_subs = HashMap::new();
        cmd_subs.insert("commit", vec!["add", "status", "diff", "log"]);
        cmd_subs.insert("push", vec!["pull", "fetch"]);
        cmd_subs.insert("test", vec!["build", "check", "run", "bench"]);
        cmd_subs.insert("install", vec!["uninstall", "update", "add", "remove"]);
        cmd_subs.insert("start", vec!["stop", "restart", "status"]);
        cmd_subs.insert("up", vec!["down", "restart", "logs"]);
        cmd_subs.insert("create", vec!["delete", "update", "get", "describe"]);

        Self {
            flag_subs,
            cmd_subs,
        }
    }

    /// Generate mutations of a command
    pub fn mutate(&self, command: &str) -> Vec<String> {
        let parts: Vec<&str> = command.split_whitespace().collect();
        if parts.is_empty() {
            return Vec::new();
        }

        let mut mutations = Vec::new();
        self.mutate_subcommand(&parts, &mut mutations);
        self.mutate_flags(&parts, command, &mut mutations);
        Self::append_common_variations(command, &mut mutations);

        mutations.sort();
        mutations.dedup();
        mutations
    }

    /// Substitute the second token (subcommand) with known alternatives.
    fn mutate_subcommand(&self, parts: &[&str], mutations: &mut Vec<String>) {
        if parts.len() < 2 {
            return;
        }
        let Some(subs) = self.cmd_subs.get(parts[1]) else {
            return;
        };
        for sub in subs {
            let mut new_parts = parts.to_vec();
            new_parts[1] = sub;
            mutations.push(new_parts.join(" "));
        }
    }

    /// Substitute matching flag tokens anywhere in the command.
    fn mutate_flags(&self, parts: &[&str], command: &str, mutations: &mut Vec<String>) {
        for (i, part) in parts.iter().enumerate() {
            let Some(subs) = self.flag_subs.get(*part) else {
                continue;
            };
            Self::push_flag_substitutions(parts, i, subs, command, mutations);
        }
    }

    fn push_flag_substitutions(
        parts: &[&str],
        i: usize,
        subs: &[&'static str],
        command: &str,
        mutations: &mut Vec<String>,
    ) {
        for sub in subs {
            let mut new_parts: Vec<&str> = parts.to_vec();
            if sub.is_empty() {
                new_parts.remove(i);
            } else {
                new_parts[i] = sub;
            }
            let new_cmd = new_parts.join(" ");
            if !new_cmd.is_empty() && new_cmd != command {
                mutations.push(new_cmd);
            }
        }
    }

    /// Add well-known flag variations for git/cargo when no long flags exist.
    fn append_common_variations(command: &str, mutations: &mut Vec<String>) {
        if command.contains("--") {
            return;
        }
        if command.starts_with("git ") {
            mutations.push(format!("{command} --verbose"));
        }
        if command.starts_with("cargo ") {
            mutations.push(format!("{command} --release"));
            mutations.push(format!("{command} --all-features"));
        }
    }

    /// Mutate a batch of commands
    pub fn mutate_batch(&self, commands: &[String]) -> Vec<String> {
        let mut all_mutations = Vec::new();
        let mut seen = HashSet::new();

        for cmd in commands {
            if seen.insert(cmd.clone()) {
                all_mutations.push(cmd.clone());
            }
            for mutation in self.mutate(cmd) {
                if seen.insert(mutation.clone()) {
                    all_mutations.push(mutation);
                }
            }
        }

        all_mutations
    }
}

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

/// Coverage-guided generator that fills gaps in n-gram model
pub struct CoverageGuidedGenerator {
    /// Known n-grams from training
    known_ngrams: HashSet<String>,
    /// Target n-gram size
    n: usize,
}

impl CoverageGuidedGenerator {
    /// Create from existing n-gram counts
    pub fn new(known_ngrams: HashSet<String>, n: usize) -> Self {
        Self { known_ngrams, n }
    }

    /// Generate commands that exercise underrepresented n-grams
    pub fn generate(&self, base_commands: &[String], count: usize) -> Vec<String> {
        let mut generated = Vec::new();
        let mut new_ngrams_added = HashSet::new();

        // Find which commands introduce new n-grams
        for cmd in base_commands {
            let ngrams = self.extract_ngrams(cmd);
            let new_count = ngrams
                .iter()
                .filter(|ng| !self.known_ngrams.contains(*ng))
                .count();

            if new_count > 0 {
                generated.push((cmd.clone(), new_count));
                for ng in ngrams {
                    if !self.known_ngrams.contains(&ng) {
                        new_ngrams_added.insert(ng);
                    }
                }
            }

            if generated.len() >= count * 2 {
                break;
            }
        }

        // Sort by coverage gain (descending)
        generated.sort_by(|a, b| b.1.cmp(&a.1));

        // Return top commands
        generated
            .into_iter()
            .take(count)
            .map(|(cmd, _)| cmd)
            .collect()
    }

    fn extract_ngrams(&self, command: &str) -> Vec<String> {
        let tokens: Vec<&str> = command.split_whitespace().collect();
        let mut ngrams = Vec::new();

        // First token as context
        if !tokens.is_empty() {
            ngrams.push(tokens[0].to_string());
        }

        // Build n-grams
        for i in 0..tokens.len() {
            let start = i.saturating_sub(self.n - 1);
            let context = tokens[start..=i].join(" ");
            ngrams.push(context);
        }

        ngrams
    }

    /// Report coverage stats
    pub fn coverage_report(&self, commands: &[String]) -> CoverageReport {
        let mut total_ngrams = HashSet::new();
        let mut new_ngrams = HashSet::new();

        for cmd in commands {
            for ng in self.extract_ngrams(cmd) {
                total_ngrams.insert(ng.clone());
                if !self.known_ngrams.contains(&ng) {
                    new_ngrams.insert(ng);
                }
            }
        }

        CoverageReport {
            known_ngrams: self.known_ngrams.len(),
            total_ngrams: total_ngrams.len(),
            new_ngrams: new_ngrams.len(),
            coverage_gain: if total_ngrams.is_empty() {
                0.0
            } else {
                new_ngrams.len() as f32 / total_ngrams.len() as f32
            },
        }
    }
}

/// Coverage statistics
#[derive(Debug, Clone)]
pub struct CoverageReport {
    /// N-grams already in model
    pub known_ngrams: usize,
    /// Total n-grams in synthetic data
    pub total_ngrams: usize,
    /// New n-grams from synthetic data
    pub new_ngrams: usize,
    /// Percentage of synthetic data that's new
    pub coverage_gain: f32,
}

/// Combined synthetic data pipeline
pub struct SyntheticPipeline {
    generator: CommandGenerator,
    mutator: CommandMutator,
}

impl SyntheticPipeline {
    /// Create new pipeline
    #[must_use]
    pub fn new() -> Self {
        Self {
            generator: CommandGenerator::new(),
            mutator: CommandMutator::new(),
        }
    }

    /// Generate synthetic training data
    ///
    /// 1. Generate base commands from templates
    /// 2. Mutate real history for variations
    /// 3. Use coverage-guided selection
    pub fn generate(
        &self,
        real_history: &[String],
        known_ngrams: HashSet<String>,
        count: usize,
    ) -> SyntheticResult {
        // Step 1: Generate template commands
        let template_commands = self.generator.generate(count * 2);

        // Step 2: Mutate real history
        let mutated_commands = self.mutator.mutate_batch(real_history);

        // Step 3: Combine all candidates
        let mut all_candidates: Vec<String> = template_commands;
        all_candidates.extend(mutated_commands);

        // Step 4: Coverage-guided selection
        let coverage_gen = CoverageGuidedGenerator::new(known_ngrams.clone(), 3);
        let selected = coverage_gen.generate(&all_candidates, count);

        // Step 5: Generate report
        let report = coverage_gen.coverage_report(&selected);

        SyntheticResult {
            commands: selected,
            report,
        }
    }
}

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

/// Result of synthetic data generation
#[derive(Debug)]
pub struct SyntheticResult {
    /// Generated commands
    pub commands: Vec<String>,
    /// Coverage report
    pub report: CoverageReport,
}

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

    #[test]
    fn test_command_generator_creates_commands() {
        let gen = CommandGenerator::new();
        let commands = gen.generate(1000);
        assert!(commands.len() >= 500);
        assert!(commands.iter().any(|c| c.starts_with("git")));
        assert!(commands.iter().any(|c| c.starts_with("cargo")));
    }

    #[test]
    fn test_command_generator_no_duplicates() {
        let gen = CommandGenerator::new();
        let commands = gen.generate(1000);
        let unique: HashSet<_> = commands.iter().collect();
        assert_eq!(commands.len(), unique.len());
    }

    #[test]
    fn test_mutator_creates_variations() {
        let mutator = CommandMutator::new();
        let mutations = mutator.mutate("git commit -m test");
        assert!(!mutations.is_empty());
        assert!(mutations
            .iter()
            .any(|m| m.contains("add") || m.contains("status")));
    }

    #[test]
    fn test_mutator_flag_substitution() {
        let mutator = CommandMutator::new();
        let mutations = mutator.mutate("cargo build --release");
        assert!(mutations
            .iter()
            .any(|m| !m.contains("--release") || m.contains("--debug")));
    }

    #[test]
    fn test_coverage_guided_prioritizes_new_ngrams() {
        let known: HashSet<String> = vec!["git".to_string(), "git commit".to_string()]
            .into_iter()
            .collect();
        let gen = CoverageGuidedGenerator::new(known, 3);

        let candidates = vec![
            "git commit".to_string(), // Known
            "cargo test".to_string(), // New
        ];

        let selected = gen.generate(&candidates, 1);
        assert_eq!(selected.len(), 1);
        assert!(selected[0].contains("cargo")); // Should prefer new
    }

    #[test]
    fn test_pipeline_generates_diverse_data() {
        let pipeline = SyntheticPipeline::new();
        let history = vec!["git status".to_string(), "cargo test".to_string()];
        let known = HashSet::new();

        let result = pipeline.generate(&history, known, 50);
        assert!(!result.commands.is_empty());
        assert!(result.report.new_ngrams > 0);
    }

    #[test]
    fn test_coverage_report_accuracy() {
        let known: HashSet<String> = vec!["git".to_string()].into_iter().collect();
        let gen = CoverageGuidedGenerator::new(known, 2);

        let commands = vec!["git status".to_string(), "cargo test".to_string()];
        let report = gen.coverage_report(&commands);

        assert_eq!(report.known_ngrams, 1);
        assert!(report.new_ngrams > 0);
        assert!(report.coverage_gain > 0.0);
    }
}