aidaemon 0.11.7

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use tokio::sync::RwLock;

use super::command_risk::split_by_operators;

/// Commands that modify files on disk.
/// NOTE: `mkdir` and `touch` are excluded because they CREATE new paths —
/// they don't destroy or modify existing data and should not require
/// prior verification that the target already exists.
const FILE_MODIFYING_COMMANDS: &[&str] = &[
    "rm", "shred", "mv", "cp", "chmod", "chown", "chattr", "dd", "mkfs", "ln",
];

/// Commands that modify files only when a specific flag is present.
const CONDITIONAL_MODIFYING: &[(&str, &str)] = &[
    ("sed", "-i"),
    ("tee", ""), // tee always writes
];

/// Commands whose path arguments should be recorded as "seen."
/// Includes read-only commands and creation commands (`mkdir`, `touch`)
/// that produce paths safe for subsequent operations.
const PATH_RECORDING_COMMANDS: &[&str] = &[
    "ls", "cat", "head", "tail", "less", "more", "file", "stat", "wc", "du", "find", "tree", "fd",
    "grep", "rg", "diff", "bat", "exa", "eza", "readlink", "test", "mkdir", "touch",
];

/// A warning returned when a modifying command targets unverified paths.
pub struct VerificationWarning {
    pub unverified_paths: Vec<String>,
    pub message: String,
}

/// Tracks which filesystem paths a session has "seen" (via read-only commands)
/// and gates file-modifying commands that target unverified paths.
pub struct VerificationTracker {
    seen_paths: RwLock<HashMap<String, HashSet<PathBuf>>>,
}

impl VerificationTracker {
    pub fn new() -> Self {
        Self {
            seen_paths: RwLock::new(HashMap::new()),
        }
    }

    /// Record a single path (and its parent directory) as seen for a session.
    pub async fn record_seen_path(&self, session_id: &str, path: &str) {
        let expanded = shellexpand::tilde(path).to_string();
        let pb = PathBuf::from(&expanded);
        let canonical = if pb.is_absolute() {
            pb
        } else {
            // Best-effort: store as-is for relative paths
            pb
        };

        let mut map = self.seen_paths.write().await;
        let set = map.entry(session_id.to_string()).or_default();
        // Record the path itself
        set.insert(canonical.clone());
        // Record parent directory so that `ls /foo` verifies `rm /foo/bar`
        if let Some(parent) = canonical.parent() {
            set.insert(parent.to_path_buf());
        }
    }

    /// Parse a read-only command and record all extracted path arguments.
    pub async fn record_from_command(&self, session_id: &str, command: &str) {
        let segments = split_by_operators(command);
        for (segment, _) in &segments {
            let trimmed = segment.trim();
            if trimmed.is_empty() {
                continue;
            }
            if let Some((base_cmd, args)) = parse_command_and_args(trimmed) {
                let cmd_name = strip_sudo(&base_cmd);
                if PATH_RECORDING_COMMANDS.contains(&cmd_name.as_str()) {
                    let paths = extract_path_args(&args);
                    for p in paths {
                        self.record_seen_path(session_id, &p).await;
                    }
                }
                // Also record paths from cd commands (the target dir is now "seen")
                if cmd_name == "cd" {
                    let paths = extract_path_args(&args);
                    for p in paths {
                        self.record_seen_path(session_id, &p).await;
                    }
                }
            }
        }
    }

    /// Check a potentially file-modifying command. Returns a warning if any
    /// target paths have not been previously seen in this session.
    pub async fn check_modifying_command(
        &self,
        session_id: &str,
        command: &str,
    ) -> Option<VerificationWarning> {
        let segments = split_by_operators(command);
        let mut unverified = Vec::new();

        for (segment, _) in &segments {
            let trimmed = segment.trim();
            if trimmed.is_empty() {
                continue;
            }
            if let Some((base_cmd, args)) = parse_command_and_args(trimmed) {
                let cmd_name = strip_sudo(&base_cmd);

                let is_modifying = FILE_MODIFYING_COMMANDS.contains(&cmd_name.as_str())
                    || CONDITIONAL_MODIFYING.iter().any(|(cmd, flag)| {
                        cmd_name == *cmd && (flag.is_empty() || args.iter().any(|a| a == flag))
                    });

                if !is_modifying {
                    continue;
                }

                let paths = extract_path_args(&args);
                if paths.is_empty() {
                    continue;
                }

                let map = self.seen_paths.read().await;
                let seen = map.get(session_id);

                for p in &paths {
                    let expanded = shellexpand::tilde(p).to_string();
                    let pb = PathBuf::from(&expanded);

                    let is_verified = if let Some(seen_set) = seen {
                        // Check exact path or if any ancestor directory was seen
                        seen_set.contains(&pb) || ancestors_seen(&pb, seen_set)
                    } else {
                        false
                    };

                    if !is_verified {
                        unverified.push(p.clone());
                    }
                }
            }
        }

        if unverified.is_empty() {
            None
        } else {
            Some(VerificationWarning {
                message: format!(
                    "The following paths have not been verified to exist in this session: {}. \
                     Use 'ls' or 'stat' to verify before modifying.",
                    unverified.join(", ")
                ),
                unverified_paths: unverified,
            })
        }
    }

    /// Remove all tracked paths for a session.
    #[allow(dead_code)]
    pub async fn clear_session(&self, session_id: &str) {
        let mut map = self.seen_paths.write().await;
        map.remove(session_id);
    }
}

/// Check if any ancestor of `path` is in the seen set.
fn ancestors_seen(path: &std::path::Path, seen: &HashSet<PathBuf>) -> bool {
    let mut current = path.parent();
    while let Some(ancestor) = current {
        if seen.contains(ancestor) {
            return true;
        }
        current = ancestor.parent();
    }
    false
}

/// Strip `sudo` prefix from a command name.
fn strip_sudo(cmd: &str) -> String {
    if cmd == "sudo" {
        // caller should have already handled sudo in parse_command_and_args
        return cmd.to_string();
    }
    cmd.to_string()
}

/// Parse a single command segment into (command_name, args).
/// Handles sudo by skipping it and any flags (like -u user).
fn parse_command_and_args(segment: &str) -> Option<(String, Vec<String>)> {
    let tokens = match shell_words::split(segment) {
        Ok(t) => t,
        Err(_) => return None,
    };
    if tokens.is_empty() {
        return None;
    }

    let mut idx = 0;

    // Skip sudo and its flags
    if tokens[idx] == "sudo" {
        idx += 1;
        // Skip sudo flags like -u, -E, etc
        while idx < tokens.len() {
            if tokens[idx].starts_with('-') {
                idx += 1;
                // If the flag takes a value (e.g., -u root), skip that too
                if idx < tokens.len() && !tokens[idx].starts_with('-') {
                    // Check if previous flag was -u, -g, -C etc that take arguments
                    let prev = &tokens[idx - 1];
                    if prev == "-u" || prev == "-g" || prev == "-C" {
                        idx += 1;
                    }
                }
            } else {
                break;
            }
        }
    }

    if idx >= tokens.len() {
        return None;
    }

    let cmd = tokens[idx].clone();
    let args = tokens[idx + 1..].to_vec();
    Some((cmd, args))
}

/// Extract path-like arguments from a token list, filtering out flags.
fn extract_path_args(args: &[String]) -> Vec<String> {
    let mut paths = Vec::new();
    let mut skip_next = false;

    for (i, arg) in args.iter().enumerate() {
        if skip_next {
            skip_next = false;
            continue;
        }

        // Skip flags
        if arg.starts_with('-') {
            // Some flags take a value argument, skip the next token too.
            // Common examples: -o output, -f file, --output file
            if i + 1 < args.len() {
                let next = &args[i + 1];
                // Heuristic: if the flag is short (-X) and next arg doesn't start with -,
                // it might be a flag value. Skip it to be safe for common cases.
                if (arg.len() == 2 || arg.starts_with("--")) && !next.starts_with('-') {
                    // Only skip for known value-taking flags
                    let value_flags = [
                        "-o",
                        "-f",
                        "-t",
                        "-m",
                        "-T",
                        "--target-directory",
                        "--output",
                        "--suffix",
                        "--backup",
                    ];
                    if value_flags.contains(&arg.as_str()) {
                        skip_next = true;
                    }
                }
            }
            continue;
        }

        // Skip things that look like shell variables or globs with braces
        if arg.starts_with('$') || arg.contains("$(") {
            continue;
        }

        // Skip chmod-style mode arguments (symbolic: +x, u+x, go-w, a=rwx;
        // numeric: 755, 0644).  These are NOT paths.
        if is_chmod_mode_arg(arg) {
            continue;
        }

        // Looks like a path argument
        paths.push(arg.clone());
    }

    paths
}

/// Recognise chmod permission-mode arguments so they are not mistaken for paths.
/// Matches symbolic modes like `+x`, `u+x`, `go-rw`, `a=rwx,u+s` and numeric
/// modes like `755`, `0644`.
fn is_chmod_mode_arg(arg: &str) -> bool {
    let bytes = arg.as_bytes();
    if bytes.is_empty() {
        return false;
    }

    // Numeric mode: 3-4 octal digits, optionally prefixed with 0
    if bytes.len() >= 3
        && bytes.len() <= 4
        && bytes.iter().all(|b| b.is_ascii_digit() && *b <= b'7')
    {
        return true;
    }

    // Symbolic mode: [ugoa]*[+-=][rwxXstugo]+ possibly comma-separated
    // Examples: +x, u+x, go-rw, a=rwx, u+s,g-w
    for part in arg.split(',') {
        let part_bytes = part.as_bytes();
        if part_bytes.is_empty() {
            return false;
        }
        // Find the operator position (+, -, =)
        let op_pos = part_bytes
            .iter()
            .position(|b| *b == b'+' || *b == b'-' || *b == b'=');
        match op_pos {
            Some(pos) => {
                // Before the operator: must be [ugoa]* (can be empty)
                if !part_bytes[..pos]
                    .iter()
                    .all(|b| matches!(b, b'u' | b'g' | b'o' | b'a'))
                {
                    return false;
                }
                // After the operator: must be [rwxXstugo]+ (non-empty)
                let after = &part_bytes[pos + 1..];
                if after.is_empty()
                    || !after.iter().all(|b| {
                        matches!(
                            b,
                            b'r' | b'w' | b'x' | b'X' | b's' | b't' | b'u' | b'g' | b'o'
                        )
                    })
                {
                    return false;
                }
            }
            None => return false,
        }
    }

    true
}

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

    #[tokio::test]
    async fn test_record_and_verify_path() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // Not yet seen — should warn
        let warning = tracker
            .check_modifying_command(sid, "rm /tmp/foo.txt")
            .await;
        assert!(warning.is_some());
        assert!(warning
            .unwrap()
            .unverified_paths
            .contains(&"/tmp/foo.txt".to_string()));

        // Record the path
        tracker.record_seen_path(sid, "/tmp/foo.txt").await;

        // Now verified — should pass
        let warning = tracker
            .check_modifying_command(sid, "rm /tmp/foo.txt")
            .await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_parent_directory_verification() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // ls /foo records /foo as seen parent
        tracker.record_from_command(sid, "ls /foo").await;

        // rm /foo/bar should pass because /foo was seen
        let warning = tracker.check_modifying_command(sid, "rm /foo/bar").await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_unverified_path_returns_warning() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        let warning = tracker
            .check_modifying_command(sid, "rm -rf /important/data")
            .await;
        assert!(warning.is_some());
        let w = warning.unwrap();
        assert!(w.unverified_paths.contains(&"/important/data".to_string()));
        assert!(w.message.contains("not been verified"));
    }

    #[tokio::test]
    async fn test_compound_commands() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // Record via compound read command
        tracker.record_from_command(sid, "cd /foo && ls /bar").await;

        // Both /foo and /bar should be seen
        let warning = tracker
            .check_modifying_command(sid, "rm /foo/file.txt")
            .await;
        assert!(warning.is_none());

        let warning = tracker
            .check_modifying_command(sid, "rm /bar/file.txt")
            .await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_flag_filtering() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // rm -rf /dir should extract /dir, not -rf
        let warning = tracker.check_modifying_command(sid, "rm -rf /dir").await;
        assert!(warning.is_some());
        let w = warning.unwrap();
        assert_eq!(w.unverified_paths, vec!["/dir".to_string()]);
    }

    #[tokio::test]
    async fn test_session_isolation() {
        let tracker = VerificationTracker::new();

        tracker.record_seen_path("session-a", "/tmp/file").await;

        // session-b should not see session-a's paths
        let warning = tracker
            .check_modifying_command("session-b", "rm /tmp/file")
            .await;
        assert!(warning.is_some());

        // session-a should see it
        let warning = tracker
            .check_modifying_command("session-a", "rm /tmp/file")
            .await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_sudo_handling() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // sudo rm /etc/foo should extract /etc/foo
        let warning = tracker
            .check_modifying_command(sid, "sudo rm /etc/foo")
            .await;
        assert!(warning.is_some());
        let w = warning.unwrap();
        assert!(w.unverified_paths.contains(&"/etc/foo".to_string()));
    }

    #[tokio::test]
    async fn test_tilde_expansion() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // Record home dir file
        let home = std::env::var("HOME").unwrap_or_else(|_| "/home/user".to_string());
        let expanded_path = format!("{}/file.txt", home);
        tracker.record_seen_path(sid, &expanded_path).await;

        // rm ~/file.txt should be verified (tilde expands to same path)
        let warning = tracker.check_modifying_command(sid, "rm ~/file.txt").await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_read_only_commands_not_flagged() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // Read-only commands should never return a warning
        let warning = tracker
            .check_modifying_command(sid, "cat /etc/passwd")
            .await;
        assert!(warning.is_none());

        let warning = tracker.check_modifying_command(sid, "ls /var/log").await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_sed_inplace_flagged() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // sed -i is file-modifying
        let warning = tracker
            .check_modifying_command(sid, "sed -i 's/foo/bar/' /tmp/config.txt")
            .await;
        assert!(warning.is_some());

        // sed without -i is not modifying (just outputs to stdout)
        let warning = tracker
            .check_modifying_command(sid, "sed 's/foo/bar/' /tmp/config.txt")
            .await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_tee_flagged() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // tee always writes
        let warning = tracker
            .check_modifying_command(sid, "tee /tmp/output.txt")
            .await;
        assert!(warning.is_some());
    }

    #[tokio::test]
    async fn test_clear_session() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        tracker.record_seen_path(sid, "/tmp/file.txt").await;
        let warning = tracker
            .check_modifying_command(sid, "rm /tmp/file.txt")
            .await;
        assert!(warning.is_none());

        tracker.clear_session(sid).await;

        let warning = tracker
            .check_modifying_command(sid, "rm /tmp/file.txt")
            .await;
        assert!(warning.is_some());
    }

    #[tokio::test]
    async fn test_record_from_command_ls() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        tracker.record_from_command(sid, "ls /var/log").await;

        // Files under /var/log should be verified
        let warning = tracker
            .check_modifying_command(sid, "rm /var/log/syslog")
            .await;
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn test_mv_flagged() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        let warning = tracker
            .check_modifying_command(sid, "mv /tmp/a /tmp/b")
            .await;
        assert!(warning.is_some());
        let w = warning.unwrap();
        // Both source and destination should be unverified
        assert!(w.unverified_paths.contains(&"/tmp/a".to_string()));
        assert!(w.unverified_paths.contains(&"/tmp/b".to_string()));
    }

    #[test]
    fn test_parse_command_and_args_basic() {
        let (cmd, args) = parse_command_and_args("rm -rf /foo").unwrap();
        assert_eq!(cmd, "rm");
        assert_eq!(args, vec!["-rf", "/foo"]);
    }

    #[test]
    fn test_parse_command_and_args_sudo() {
        let (cmd, args) = parse_command_and_args("sudo rm -f /etc/file").unwrap();
        assert_eq!(cmd, "rm");
        assert_eq!(args, vec!["-f", "/etc/file"]);
    }

    #[test]
    fn test_extract_path_args_filters_flags() {
        let args: Vec<String> = vec!["-rf".into(), "/dir".into(), "-v".into()];
        let paths = extract_path_args(&args);
        assert_eq!(paths, vec!["/dir".to_string()]);
    }

    #[test]
    fn test_extract_path_args_skips_shell_vars() {
        let args: Vec<String> = vec!["$HOME/file".into(), "/real/path".into()];
        let paths = extract_path_args(&args);
        assert_eq!(paths, vec!["/real/path".to_string()]);
    }

    #[tokio::test]
    async fn test_mkdir_not_blocked() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // mkdir should NOT be blocked even when path is unverified
        // because it creates new directories
        let warning = tracker
            .check_modifying_command(sid, "mkdir -p /tmp/new_project")
            .await;
        assert!(
            warning.is_none(),
            "mkdir should not be blocked by verification"
        );

        let warning = tracker
            .check_modifying_command(sid, "mkdir /tmp/another_dir")
            .await;
        assert!(warning.is_none(), "mkdir without -p should not be blocked");
    }

    #[tokio::test]
    async fn test_touch_not_blocked() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // touch should NOT be blocked — it creates files or updates timestamps
        let warning = tracker
            .check_modifying_command(sid, "touch /tmp/new_file.txt")
            .await;
        assert!(
            warning.is_none(),
            "touch should not be blocked by verification"
        );
    }

    #[tokio::test]
    async fn test_mkdir_records_paths() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // After mkdir, the created path should be recorded as seen
        tracker
            .record_from_command(sid, "mkdir -p /tmp/new_project")
            .await;

        // Now cp into that directory should work
        let warning = tracker
            .check_modifying_command(sid, "cp /verified/file /tmp/new_project/file")
            .await;
        // /tmp/new_project is seen, but /verified/file is not
        // We just check that /tmp/new_project/file is resolved via parent
        let w = warning.unwrap();
        assert!(
            !w.unverified_paths
                .contains(&"/tmp/new_project/file".to_string()),
            "path under mkdir'd dir should be verified"
        );
    }

    #[tokio::test]
    async fn test_chmod_mode_args_not_treated_as_paths() {
        let tracker = VerificationTracker::new();
        let sid = "test-session";

        // Record the file path
        tracker.record_seen_path(sid, "/tmp/script.sh").await;

        // chmod +x should not flag "+x" as an unverified path
        let warning = tracker
            .check_modifying_command(sid, "chmod +x /tmp/script.sh")
            .await;
        assert!(warning.is_none(), "chmod +x on verified path should pass");

        // chmod u+x should not flag "u+x"
        let warning = tracker
            .check_modifying_command(sid, "chmod u+x /tmp/script.sh")
            .await;
        assert!(warning.is_none(), "chmod u+x on verified path should pass");

        // chmod 755 should not flag "755"
        let warning = tracker
            .check_modifying_command(sid, "chmod 755 /tmp/script.sh")
            .await;
        assert!(warning.is_none(), "chmod 755 on verified path should pass");

        // chmod go-rw should not flag "go-rw"
        let warning = tracker
            .check_modifying_command(sid, "chmod go-rw /tmp/script.sh")
            .await;
        assert!(
            warning.is_none(),
            "chmod go-rw on verified path should pass"
        );

        // chmod a=rwx should not flag "a=rwx"
        let warning = tracker
            .check_modifying_command(sid, "chmod a=rwx /tmp/script.sh")
            .await;
        assert!(
            warning.is_none(),
            "chmod a=rwx on verified path should pass"
        );

        // Unverified file should still warn (only the file, not the mode)
        let warning = tracker
            .check_modifying_command(sid, "chmod +x /srv/unknown.sh")
            .await;
        assert!(warning.is_some());
        let w = warning.unwrap();
        assert_eq!(w.unverified_paths, vec!["/srv/unknown.sh".to_string()]);
    }

    #[test]
    fn test_is_chmod_mode_arg() {
        // Symbolic modes
        assert!(is_chmod_mode_arg("+x"));
        assert!(is_chmod_mode_arg("u+x"));
        assert!(is_chmod_mode_arg("go-rw"));
        assert!(is_chmod_mode_arg("a=rwx"));
        assert!(is_chmod_mode_arg("u+s,g-w"));
        assert!(is_chmod_mode_arg("+X"));

        // Numeric modes
        assert!(is_chmod_mode_arg("755"));
        assert!(is_chmod_mode_arg("0644"));
        assert!(is_chmod_mode_arg("777"));

        // Not modes
        assert!(!is_chmod_mode_arg("/tmp/file"));
        assert!(!is_chmod_mode_arg("hello"));
        assert!(!is_chmod_mode_arg(""));
        assert!(!is_chmod_mode_arg("999")); // 9 is not octal
    }
}