aprender-core 0.29.1

Next-generation machine learning library in pure Rust
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
//! Shell-aware vocabulary for tokenizing bash/shell scripts.
//!
//! Provides a specialized vocabulary that understands shell syntax:
//! builtins, operators, variables, control flow, and common patterns.
//! Designed for use with the neural encoder architecture in `citl::neural`.
//!
//! # Example
//!
//! ```
//! use aprender::text::shell_vocab::ShellVocabulary;
//!
//! let vocab = ShellVocabulary::new();
//! let tokens = vocab.tokenize("#!/bin/bash\necho $HOME");
//! assert!(!tokens.is_empty());
//! assert_eq!(vocab.cls_token(), 2);
//! ```

use std::collections::HashMap;

/// Shell-aware vocabulary for tokenizing shell scripts.
///
/// Maps shell tokens (builtins, operators, variables, control flow keywords)
/// to integer IDs suitable for embedding layers. Follows the same pattern
/// as `citl::neural::Vocabulary` but specialized for shell script analysis.
#[derive(Debug, Clone)]
pub struct ShellVocabulary {
    /// Token to ID mapping
    token_to_id: HashMap<String, usize>,
    /// ID to token mapping (for decoding)
    id_to_token: HashMap<usize, String>,
    /// Special token IDs
    pad_id: usize,
    unk_id: usize,
    cls_id: usize,
    sep_id: usize,
    eos_id: usize,
    /// Safety class labels
    label_names: Vec<&'static str>,
}

/// The 5 safety classes for shell script classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SafetyClass {
    /// Passes all checks (lint clean, deterministic, idempotent)
    Safe = 0,
    /// Variable quoting issues detected
    NeedsQuoting = 1,
    /// Contains non-deterministic constructs ($RANDOM, $$, timestamps)
    NonDeterministic = 2,
    /// Missing idempotency flags (-p, -f)
    NonIdempotent = 3,
    /// Security rule violations (SEC001-SEC008)
    Unsafe = 4,
}

impl SafetyClass {
    /// All safety class variants in order.
    #[must_use]
    pub const fn all() -> [SafetyClass; 5] {
        [
            SafetyClass::Safe,
            SafetyClass::NeedsQuoting,
            SafetyClass::NonDeterministic,
            SafetyClass::NonIdempotent,
            SafetyClass::Unsafe,
        ]
    }

    /// Number of classes.
    #[must_use]
    pub const fn num_classes() -> usize {
        5
    }

    /// Human-readable label for this class.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            SafetyClass::Safe => "safe",
            SafetyClass::NeedsQuoting => "needs-quoting",
            SafetyClass::NonDeterministic => "non-deterministic",
            SafetyClass::NonIdempotent => "non-idempotent",
            SafetyClass::Unsafe => "unsafe",
        }
    }

    /// Create from class index.
    #[must_use]
    pub const fn from_index(idx: usize) -> Option<SafetyClass> {
        match idx {
            0 => Some(SafetyClass::Safe),
            1 => Some(SafetyClass::NeedsQuoting),
            2 => Some(SafetyClass::NonDeterministic),
            3 => Some(SafetyClass::NonIdempotent),
            4 => Some(SafetyClass::Unsafe),
            _ => None,
        }
    }
}

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

impl ShellVocabulary {
    /// Create a new shell-aware vocabulary with comprehensive shell token coverage.
    #[must_use]
    pub fn new() -> Self {
        let mut token_to_id = HashMap::new();
        let mut id_to_token = HashMap::new();
        let mut id = 0usize;

        let mut insert = |token: &str, current_id: &mut usize| {
            token_to_id.insert(token.to_string(), *current_id);
            id_to_token.insert(*current_id, token.to_string());
            *current_id += 1;
        };

        // Special tokens (0-4)
        insert("[PAD]", &mut id);
        let pad_id = 0;
        insert("[UNK]", &mut id);
        let unk_id = 1;
        insert("[CLS]", &mut id);
        let cls_id = 2;
        insert("[SEP]", &mut id);
        let sep_id = 3;
        insert("[EOS]", &mut id);
        let eos_id = 4;

        // Shebangs
        for shebang in &["#!/bin/bash", "#!/bin/sh", "#!/usr/bin/env"] {
            insert(shebang, &mut id);
        }

        // Shell builtins
        for builtin in &[
            "echo", "printf", "read", "cd", "pwd", "export", "unset", "set", "source", "eval",
            "exec", "exit", "return", "shift", "test", "true", "false", ":", "type", "hash",
            "alias", "unalias", "trap", "wait", "kill", "jobs", "bg", "fg", "umask", "getopts",
            "local", "declare", "typeset", "readonly", "let", "command", "builtin", "enable",
        ] {
            insert(builtin, &mut id);
        }

        // Common external commands
        for cmd in &[
            "mkdir", "rm", "cp", "mv", "ln", "chmod", "chown", "cat", "grep", "sed", "awk", "find",
            "sort", "uniq", "wc", "head", "tail", "cut", "tr", "tee", "xargs", "curl", "wget",
            "tar", "gzip", "gunzip", "zip", "unzip", "touch", "ls", "stat", "file", "basename",
            "dirname", "mktemp", "date", "sleep", "install",
        ] {
            insert(cmd, &mut id);
        }

        // Control flow keywords
        for kw in &[
            "if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "until",
            "case", "esac", "function",
        ] {
            insert(kw, &mut id);
        }

        // Shell operators
        for op in &[
            "|", "||", "&&", ";", ";;", "&", ">", ">>", "<", "<<", "<<<", "2>", "2>>", "2>&1",
            "&>", "(", ")", "((", "))", "[", "]", "[[", "]]", "{", "}", "$", "${", "$(", "$((",
            "`", "=", "==", "!=", "-eq", "-ne", "-lt", "-gt", "-le", "-ge", "-z", "-n", "-f", "-d",
            "-e", "-r", "-w", "-x", "-s", "!", "~",
        ] {
            insert(op, &mut id);
        }

        // Common shell variables
        for var in &[
            "$HOME",
            "$USER",
            "$PATH",
            "$PWD",
            "$SHELL",
            "$RANDOM",
            "$BASHPID",
            "$$",
            "$!",
            "$?",
            "$#",
            "$@",
            "$*",
            "$0",
            "$1",
            "$2",
            "$TMPDIR",
            "$IFS",
            "$LANG",
            "$TERM",
            "$HOSTNAME",
            "$OSTYPE",
            "$MACHTYPE",
        ] {
            insert(var, &mut id);
        }

        // Common flags (idempotency/safety related)
        for flag in &[
            "-p",
            "-f",
            "-r",
            "-rf",
            "-n",
            "-e",
            "-i",
            "-v",
            "-q",
            "-m",
            "-s",
            "-t",
            "-o",
            "-a",
            "-b",
            "-c",
            "-g",
            "-h",
            "-k",
            "-l",
            "-u",
            "-x",
            "--force",
            "--recursive",
            "--verbose",
            "--quiet",
            "--parents",
            "--no-clobber",
        ] {
            insert(flag, &mut id);
        }

        // String/quoting tokens
        for q in &["\"", "'", "\\", "\n", "\t"] {
            insert(q, &mut id);
        }

        // Numeric literals (common)
        for n in &[
            "0", "1", "2", "3", "4", "5", "10", "100", "255", "644", "755",
        ] {
            insert(n, &mut id);
        }

        // Common words in shell scripts
        for word in &[
            "file", "dir", "path", "name", "tmp", "log", "err", "out", "input", "output", "config",
            "data", "src", "dest", "root", "user", "home", "bin", "lib", "etc", "var", "dev",
            "null", "proc", "sys", "run", "opt", "ok", "error", "warning", "fatal", "info",
            "debug", "start", "stop", "restart", "status", "check", "install", "update", "remove",
            "clean", "build",
        ] {
            insert(word, &mut id);
        }

        let label_names = vec![
            "safe",
            "needs-quoting",
            "non-deterministic",
            "non-idempotent",
            "unsafe",
        ];

        Self {
            token_to_id,
            id_to_token,
            pad_id,
            unk_id,
            cls_id,
            sep_id,
            eos_id,
            label_names,
        }
    }

    /// Get vocabulary size.
    #[must_use]
    pub fn vocab_size(&self) -> usize {
        self.token_to_id.len()
    }

    /// Get the PAD token ID.
    #[must_use]
    pub fn pad_token(&self) -> usize {
        self.pad_id
    }

    /// Get the UNK token ID.
    #[must_use]
    pub fn unk_token(&self) -> usize {
        self.unk_id
    }

    /// Get the CLS token ID.
    #[must_use]
    pub fn cls_token(&self) -> usize {
        self.cls_id
    }

    /// Get the SEP token ID.
    #[must_use]
    pub fn sep_token(&self) -> usize {
        self.sep_id
    }

    /// Get the EOS token ID.
    #[must_use]
    pub fn eos_token(&self) -> usize {
        self.eos_id
    }

    /// Get the safety class labels.
    #[must_use]
    pub fn label_names(&self) -> &[&str] {
        &self.label_names
    }

    /// Tokenize a shell script into token IDs.
    ///
    /// Performs shell-aware tokenization that preserves:
    /// - Shebangs as single tokens
    /// - Variable references ($VAR, ${VAR})
    /// - Operators (||, &&, >>, etc.)
    /// - Quoted strings
    ///
    /// # Example
    ///
    /// ```
    /// use aprender::text::shell_vocab::ShellVocabulary;
    ///
    /// let vocab = ShellVocabulary::new();
    /// let tokens = vocab.tokenize("echo hello");
    /// assert!(tokens.len() >= 2);
    /// ```
    #[must_use]
    pub fn tokenize(&self, script: &str) -> Vec<usize> {
        let raw_tokens = self.shell_split(script);
        raw_tokens.iter().map(|t| self.get_token_id(t)).collect()
    }

    /// Tokenize and prepend CLS, append EOS, truncate to max_len.
    #[must_use]
    pub fn encode(&self, script: &str, max_len: usize) -> Vec<usize> {
        let mut ids = Vec::with_capacity(max_len);
        ids.push(self.cls_id);

        let raw_tokens = self.shell_split(script);
        for token in &raw_tokens {
            if ids.len() >= max_len - 1 {
                break;
            }
            ids.push(self.get_token_id(token));
        }

        ids.push(self.eos_id);

        // Pad to max_len
        while ids.len() < max_len {
            ids.push(self.pad_id);
        }

        ids
    }

    /// Decode token IDs back to tokens (for debugging).
    #[must_use]
    pub fn decode(&self, ids: &[usize]) -> Vec<String> {
        ids.iter()
            .map(|&id| {
                self.id_to_token
                    .get(&id)
                    .cloned()
                    .unwrap_or_else(|| format!("[ID:{id}]"))
            })
            .collect()
    }

    /// Export vocabulary as JSON (token -> id mapping).
    ///
    /// # Errors
    ///
    /// Returns error if JSON serialization fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.token_to_id)
    }

    /// Split a shell script into tokens using shell-aware rules.
    fn shell_split(&self, script: &str) -> Vec<String> {
        let mut tokens = Vec::new();
        let chars: Vec<char> = script.chars().collect();
        let len = chars.len();
        let mut i = 0;

        while i < len {
            let c = chars[i];

            // Skip whitespace
            if c.is_whitespace() {
                i += 1;
                continue;
            }

            // Check for shebang at start of line
            if c == '#' && i + 1 < len && chars[i + 1] == '!' {
                let start = i;
                while i < len && chars[i] != '\n' {
                    i += 1;
                }
                let shebang = chars[start..i].iter().collect::<String>();
                tokens.push(shebang);
                continue;
            }

            // Comments
            if c == '#' {
                while i < len && chars[i] != '\n' {
                    i += 1;
                }
                continue;
            }

            // Dollar-prefixed tokens ($VAR, ${...}, $(...), $((..)))
            if c == '$' {
                let start = i;
                i += 1;
                if i < len {
                    match chars[i] {
                        '{' => {
                            // ${...}
                            while i < len && chars[i] != '}' {
                                i += 1;
                            }
                            if i < len {
                                i += 1; // skip '}'
                            }
                        }
                        '(' => {
                            if i + 1 < len && chars[i + 1] == '(' {
                                // $((...))
                                tokens.push("$((".to_string());
                                i += 2;
                                continue;
                            }
                            // $(...)
                            tokens.push("$(".to_string());
                            i += 1;
                            continue;
                        }
                        c2 if c2.is_alphanumeric()
                            || c2 == '_'
                            || c2 == '?'
                            || c2 == '#'
                            || c2 == '@'
                            || c2 == '*'
                            || c2 == '!'
                            || c2 == '$' =>
                        {
                            while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                }
                let token = chars[start..i].iter().collect::<String>();
                tokens.push(token);
                continue;
            }

            // Multi-character operators
            if i + 1 < len {
                let two: String = chars[i..i + 2].iter().collect();
                if matches!(
                    two.as_str(),
                    "||" | "&&"
                        | ">>"
                        | "<<"
                        | "!="
                        | "=="
                        | ";;"
                        | "(("
                        | "))"
                        | "[["
                        | "]]"
                        | "2>"
                ) {
                    tokens.push(two);
                    i += 2;
                    continue;
                }
            }

            // Single-character operators
            if matches!(
                c,
                '|' | '&' | ';' | '>' | '<' | '(' | ')' | '[' | ']' | '{' | '}' | '!' | '=' | '~'
            ) {
                tokens.push(c.to_string());
                i += 1;
                continue;
            }

            // Quoted strings — tokenize the quotes and contents separately
            if c == '"' || c == '\'' {
                tokens.push(c.to_string());
                let quote = c;
                i += 1;
                let start = i;
                while i < len && chars[i] != quote {
                    if chars[i] == '\\' && quote == '"' {
                        i += 1; // skip escaped char
                    }
                    i += 1;
                }
                if i > start {
                    let content: String = chars[start..i].iter().collect();
                    // Split content into sub-tokens
                    for word in content.split_whitespace() {
                        tokens.push(word.to_string());
                    }
                }
                if i < len {
                    tokens.push(quote.to_string());
                    i += 1;
                }
                continue;
            }

            // Backtick command substitution
            if c == '`' {
                tokens.push("`".to_string());
                i += 1;
                continue;
            }

            // Words (identifiers, commands, arguments)
            if c.is_alphanumeric() || c == '_' || c == '-' || c == '/' || c == '.' {
                let start = i;
                while i < len
                    && (chars[i].is_alphanumeric()
                        || chars[i] == '_'
                        || chars[i] == '-'
                        || chars[i] == '/'
                        || chars[i] == '.')
                {
                    i += 1;
                }
                let word: String = chars[start..i].iter().collect();
                tokens.push(word);
                continue;
            }

            // Backslash
            if c == '\\' {
                tokens.push("\\".to_string());
                i += 1;
                if i < len {
                    i += 1; // skip escaped char
                }
                continue;
            }

            // Anything else — skip
            i += 1;
        }

        tokens
    }

    fn get_token_id(&self, token: &str) -> usize {
        self.token_to_id.get(token).copied().unwrap_or(self.unk_id)
    }
}

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

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

    #[test]
    fn test_vocabulary_creation() {
        let vocab = ShellVocabulary::new();
        assert!(vocab.vocab_size() > 100);
        assert_eq!(vocab.pad_token(), 0);
        assert_eq!(vocab.unk_token(), 1);
        assert_eq!(vocab.cls_token(), 2);
    }

    #[test]
    fn test_special_tokens() {
        let vocab = ShellVocabulary::new();
        assert_eq!(vocab.pad_token(), 0);
        assert_eq!(vocab.unk_token(), 1);
        assert_eq!(vocab.cls_token(), 2);
        assert_eq!(vocab.sep_token(), 3);
        assert_eq!(vocab.eos_token(), 4);
    }

    #[test]
    fn test_tokenize_simple_echo() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("echo hello");
        assert_eq!(tokens.len(), 2);
        // "echo" should be a known builtin
        assert_ne!(tokens[0], vocab.unk_token());
    }

    #[test]
    fn test_tokenize_shebang() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("#!/bin/bash\necho hello");
        assert!(tokens.len() >= 2);
        // Shebang should be a known token
        assert_ne!(tokens[0], vocab.unk_token());
    }

    #[test]
    fn test_tokenize_variable() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("echo $HOME");
        assert_eq!(tokens.len(), 2);
        assert_ne!(tokens[1], vocab.unk_token()); // $HOME is known
    }

    #[test]
    fn test_tokenize_pipe() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("ls | grep foo");
        assert!(tokens.len() >= 3);
    }

    #[test]
    fn test_tokenize_operators() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("cmd1 && cmd2 || cmd3");
        // Should find && and || as known tokens
        assert!(tokens.len() >= 3);
    }

    #[test]
    fn test_encode_with_padding() {
        let vocab = ShellVocabulary::new();
        let encoded = vocab.encode("echo hello", 32);
        assert_eq!(encoded.len(), 32);
        assert_eq!(encoded[0], vocab.cls_token());
        // Last non-pad should be EOS
        let last_non_pad = encoded
            .iter()
            .rposition(|&id| id != vocab.pad_token())
            .expect("should have non-pad token");
        assert_eq!(encoded[last_non_pad], vocab.eos_token());
    }

    #[test]
    fn test_encode_truncation() {
        let vocab = ShellVocabulary::new();
        let long_script = "echo a; echo b; echo c; echo d; echo e; echo f; echo g";
        let encoded = vocab.encode(long_script, 8);
        assert_eq!(encoded.len(), 8);
        assert_eq!(encoded[0], vocab.cls_token());
    }

    #[test]
    fn test_decode_roundtrip() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("echo hello");
        let decoded = vocab.decode(&tokens);
        assert_eq!(decoded[0], "echo");
    }

    #[test]
    fn test_safety_class_labels() {
        assert_eq!(SafetyClass::Safe.label(), "safe");
        assert_eq!(SafetyClass::Unsafe.label(), "unsafe");
        assert_eq!(SafetyClass::num_classes(), 5);
    }

    #[test]
    fn test_safety_class_from_index() {
        assert_eq!(SafetyClass::from_index(0), Some(SafetyClass::Safe));
        assert_eq!(SafetyClass::from_index(4), Some(SafetyClass::Unsafe));
        assert_eq!(SafetyClass::from_index(5), None);
    }

    #[test]
    fn test_to_json() {
        let vocab = ShellVocabulary::new();
        let json = vocab.to_json().expect("JSON export should succeed");
        assert!(json.contains("echo"));
        assert!(json.contains("[PAD]"));
    }

    #[test]
    fn test_comment_handling() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("echo hello # this is a comment\necho world");
        // Comments should be stripped
        let decoded = vocab.decode(&tokens);
        assert!(!decoded.contains(&"#".to_string()));
        assert!(!decoded.contains(&"comment".to_string()));
    }

    #[test]
    fn test_tokenize_mkdir_flags() {
        let vocab = ShellVocabulary::new();
        let tokens = vocab.tokenize("mkdir -p /tmp/foo");
        assert!(tokens.len() >= 3);
        // "mkdir" and "-p" should be known tokens
        assert_ne!(tokens[0], vocab.unk_token());
        assert_ne!(tokens[1], vocab.unk_token());
    }
}