dirge-agent 0.7.4

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
#[cfg(all(test, feature = "semantic-bash"))]
mod tests {
    use crate::semantic::adapters::bash::{parse_bash_segments, parse_bash_segments_full};

    #[test]
    fn test_simple_command() {
        let segments = parse_bash_segments("cargo test --all");
        assert_eq!(segments, vec!["cargo test --all"]);
    }

    #[test]
    fn test_double_ampersand_splits() {
        let segments = parse_bash_segments("cargo test && echo done");
        assert_eq!(segments, vec!["cargo test", "echo done"]);
    }

    #[test]
    fn test_semicolon_splits() {
        let segments = parse_bash_segments("echo a; echo b");
        assert_eq!(segments, vec!["echo a", "echo b"]);
    }

    #[test]
    fn test_pipe_splits() {
        let segments = parse_bash_segments("cat file | grep foo | wc -l");
        assert_eq!(segments, vec!["cat file", "grep foo", "wc -l"]);
    }

    #[test]
    fn test_mixed_separators() {
        let segments = parse_bash_segments("a && b | c");
        assert_eq!(segments, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_command_substitution_is_complex() {
        let (segments, complex) = parse_bash_segments_full("echo $(rm -rf /)").unwrap();
        assert!(complex, "command substitution should be marked complex");
        assert_eq!(segments.len(), 1);
    }

    #[test]
    fn test_single_quotes_are_safe() {
        let (segments, complex) = parse_bash_segments_full("echo 'safe $(not expanded)'").unwrap();
        assert!(!complex, "single quotes should not trigger complex");
        assert_eq!(segments.len(), 1);
    }

    #[test]
    fn test_double_quotes_are_complex() {
        let (_segments, complex) =
            parse_bash_segments_full("echo \"dangerous $(expanded)\"").unwrap();
        assert!(complex, "double quotes with substitution should be complex");
    }

    #[test]
    fn test_git_commands_parse() {
        let segments = parse_bash_segments("git diff --staged && git status");
        assert_eq!(segments, vec!["git diff --staged", "git status"]);
    }

    #[test]
    fn test_parse_error_fallback() {
        let segments = parse_bash_segments("for i in");
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0], "for i in");
    }

    // --- C3: compound-form recursion ---------------------------

    /// Brace groups recurse — each contained command lands as its
    /// own segment so per-command rules fire. Previously the whole
    /// `{ ... }` was pushed verbatim and matched no rule.
    #[test]
    fn test_brace_group_recurses_into_commands() {
        let segments = parse_bash_segments("{ echo a; rm -rf /tmp/x; }");
        assert!(
            segments.iter().any(|s| s.starts_with("echo")),
            "got: {segments:?}"
        );
        assert!(
            segments.iter().any(|s| s.starts_with("rm")),
            "got: {segments:?}"
        );
        // The literal "{ ... }" wrapper should NOT appear as a segment.
        assert!(
            !segments.iter().any(|s| s.contains("{ echo")),
            "got: {segments:?}"
        );
    }

    /// if/then/fi recurses into its body — the inner commands get
    /// individual permission checks.
    #[test]
    fn test_if_statement_recurses_into_body() {
        let segments = parse_bash_segments("if true; then rm /tmp/x; echo done; fi");
        assert!(
            segments.iter().any(|s| s.starts_with("rm")),
            "got: {segments:?}"
        );
        assert!(
            segments.iter().any(|s| s.starts_with("echo")),
            "got: {segments:?}"
        );
    }

    /// while loops same.
    #[test]
    fn test_while_loop_recurses() {
        let segments = parse_bash_segments("while true; do rm -rf /tmp/x; done");
        assert!(
            segments.iter().any(|s| s.starts_with("rm")),
            "got: {segments:?}"
        );
    }

    /// for loops same.
    #[test]
    fn test_for_loop_recurses() {
        let segments = parse_bash_segments("for f in a b c; do rm $f; done");
        assert!(
            segments.iter().any(|s| s.starts_with("rm")),
            "got: {segments:?}"
        );
    }

    /// case statements: each case-clause body is recursed into.
    #[test]
    fn test_case_statement_recurses() {
        let segments = parse_bash_segments("case $x in foo) rm /tmp/x;; bar) echo b;; esac");
        assert!(
            segments.iter().any(|s| s.starts_with("rm")),
            "got: {segments:?}"
        );
        assert!(
            segments.iter().any(|s| s.starts_with("echo")),
            "got: {segments:?}"
        );
    }

    // --- C4: redirect-target extraction ------------------------

    use crate::semantic::adapters::bash::extract_redirect_targets;

    #[test]
    fn extract_redirect_targets_output_redirect() {
        let t = extract_redirect_targets("echo pwned > /etc/something");
        assert_eq!(t, vec!["/etc/something".to_string()]);
    }

    #[test]
    fn extract_redirect_targets_append() {
        let t = extract_redirect_targets("echo line >> /var/log/foo");
        assert_eq!(t, vec!["/var/log/foo".to_string()]);
    }

    #[test]
    fn extract_redirect_targets_multiple() {
        // `cmd > a 2> b` writes to BOTH a and b — both should be
        // checked by the path gate.
        let t = extract_redirect_targets("rustc src.rs > out.log 2> err.log");
        assert!(t.contains(&"out.log".to_string()), "got: {t:?}");
        assert!(t.contains(&"err.log".to_string()), "got: {t:?}");
    }

    #[test]
    fn extract_redirect_targets_strips_quotes() {
        let t = extract_redirect_targets("echo x > \"/tmp/with spaces\"");
        assert_eq!(t, vec!["/tmp/with spaces".to_string()]);
    }

    #[test]
    fn extract_redirect_targets_no_redirects() {
        assert!(extract_redirect_targets("echo hello").is_empty());
        assert!(extract_redirect_targets("cargo test --all").is_empty());
    }

    #[test]
    fn extract_redirect_targets_heredoc_skipped() {
        // <<EOF has no file target — skip.
        let t = extract_redirect_targets("cat <<EOF\nhi\nEOF");
        assert!(t.is_empty(), "got: {t:?}");
    }

    /// fd-duplication redirects (`2>&1`, `>&2`) target file
    /// descriptors, not files. They must NOT trigger a write
    /// permission check — the check against `validate_path` would
    /// reject the bare number as a "numeric path," and even if it
    /// passed, there's no file being written.
    #[test]
    fn extract_redirect_targets_skips_fd_duplication() {
        assert!(extract_redirect_targets("cargo test 2>&1").is_empty());
        assert!(extract_redirect_targets("cmd >&2").is_empty());
        assert!(extract_redirect_targets("cmd 1>&2").is_empty());
    }

    /// Redirected statement: the inner command is checked (redirect
    /// operands handled by C4 separately, not surfaced here).
    #[test]
    fn test_redirected_statement_recurses_to_inner_command() {
        let segments = parse_bash_segments("echo pwned > /etc/something");
        assert!(
            segments.iter().any(|s| s.starts_with("echo")),
            "got: {segments:?}"
        );
        // Old behaviour pushed the whole `echo pwned > /etc/something`;
        // now the segment is just the command without the redirect.
        assert!(
            !segments.iter().any(|s| s.contains("/etc/something")),
            "segment should NOT include the redirect target; got: {segments:?}"
        );
    }
}

/// C4 (audit fix): extract redirect target paths from a bash
/// command so the caller can route each through the path permission
/// gate. Previously `echo pwned > /etc/something` matched the safe
/// `echo **` rule and wrote to the destination without any path
/// check — the redirect target was invisible to the permission
/// system.
///
/// Returns destination paths for: `>` `>>` `&>` `&>>` `>&` `<` `<<<`
/// and combined forms (`1>file`, `2>file`, etc.). Heredocs (`<<EOF`)
/// have no file target so they're skipped. Empty when no redirects.
///
/// Returns `Vec::new()` on parse error or when the `semantic-bash`
/// feature is disabled — the caller still gets the normal segment
/// checks, just no extra path gate for the redirect destination.
#[allow(dead_code)]
pub fn extract_redirect_targets(command: &str) -> Vec<String> {
    #[cfg(feature = "semantic-bash")]
    {
        use tree_sitter::Parser;
        let lang: tree_sitter::Language = tree_sitter_bash::LANGUAGE.into();
        let mut parser = Parser::new();
        if parser.set_language(&lang).is_err() {
            return Vec::new();
        }
        let Some(tree) = parser.parse(command, None) else {
            return Vec::new();
        };
        if tree.root_node().has_error() {
            return Vec::new();
        }
        let mut targets = Vec::new();
        collect_redirect_targets(tree.root_node(), command.as_bytes(), &mut targets);
        targets
    }
    #[cfg(not(feature = "semantic-bash"))]
    {
        let _ = command;
        Vec::new()
    }
}

/// F1 (dirge-dvy): extract positional path arguments to file-mutating
/// commands so the permission layer can route each through the write
/// rules — independent of the bash command-pattern check.
///
/// Concrete bypass this closes: a user adds `bash: { "rm *": "allow" }`
/// for convenience. The bash command-pattern check allows
/// `rm /etc/passwd` because it matches `rm *`. Without this extractor,
/// the path `/etc/passwd` never reaches the write rules → silently
/// deleted. With it, every mutation path routes through
/// `enforce(tool="write", Scope::PathResolve(arg))` and write's deny
/// rules apply.
///
/// Ported from opencode's `packages/opencode/src/tool/shell.ts:30-51`
/// (`FILES` set) and `:191-221` (`pathArgs` filter logic). Restricted
/// to commands that semantically WRITE files; omits `cd`/`pushd`/etc
/// (no mutation) and `cat`/`get-content`/etc (read-only). Adds `ln`,
/// `tee`, `dd` which opencode doesn't explicitly list but
/// semantically mutate.
///
/// chmod / chown special-case: their FIRST positional arg is the
/// mode (`777`, `u+x`) or owner spec (`user:group`), not a path.
/// Skip arg index 0 for those commands.
#[cfg(feature = "semantic-bash")]
pub fn extract_mutation_paths(command: &str) -> Vec<String> {
    const FILE_MUTATORS: &[&str] = &[
        "rm", "cp", "mv", "mkdir", "rmdir", "touch", "chmod", "chown", "ln", "tee", "dd",
    ];

    use tree_sitter::Parser;
    let lang: tree_sitter::Language = tree_sitter_bash::LANGUAGE.into();
    let mut parser = Parser::new();
    if parser.set_language(&lang).is_err() {
        return Vec::new();
    }
    let Some(tree) = parser.parse(command, None) else {
        return Vec::new();
    };
    if tree.root_node().has_error() {
        return Vec::new();
    }
    let mut paths = Vec::new();
    collect_mutation_paths(
        tree.root_node(),
        command.as_bytes(),
        FILE_MUTATORS,
        &mut paths,
    );
    paths
}

#[cfg(feature = "semantic-bash")]
fn collect_mutation_paths(
    node: tree_sitter::Node,
    source: &[u8],
    mutators: &[&str],
    out: &mut Vec<String>,
) {
    if node.kind() == "command" {
        // Collect head + positional args. The tree-sitter-bash
        // grammar emits the head as `command_name`, then positional
        // args as `word` / `string` / `raw_string` / `concatenation`.
        // Skip anything else (redirections, variable assignments,
        // etc. — those have their own node kinds and aren't paths
        // here).
        let mut head: Option<String> = None;
        let mut args: Vec<String> = Vec::new();
        for i in 0..node.named_child_count() {
            let Some(child) = node.named_child(i) else {
                continue;
            };
            // Don't walk into redirections — they were handled by
            // the redirect_targets extractor and including them
            // here would double-prompt.
            if child.kind() == "file_redirect"
                || child.kind() == "heredoc_redirect"
                || child.kind() == "herestring_redirect"
            {
                continue;
            }
            let text = match child.utf8_text(source) {
                Ok(t) => t.trim().to_string(),
                Err(_) => continue,
            };
            if head.is_none() {
                head = Some(text);
                continue;
            }
            // Skip flag args (`-r`, `--recursive`).
            if text.starts_with('-') {
                continue;
            }
            // Skip chmod permission specs (`+x`, `u+x`).
            if matches!(head.as_deref(), Some("chmod")) && text.starts_with('+') {
                continue;
            }
            args.push(unquote_simple(&text));
        }

        if let Some(h) = head {
            // Strip path prefix on the head so absolute paths like
            // `/bin/rm` still match the basename rule. Skip empty
            // heads.
            let basename = std::path::Path::new(&h)
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap_or(h.as_str());
            if mutators.contains(&basename) {
                // chmod / chown: drop the first positional arg
                // (mode spec / owner spec — not a path).
                let path_args: &[String] = if matches!(basename, "chmod" | "chown") {
                    args.get(1..).unwrap_or(&[])
                } else {
                    &args
                };
                for p in path_args {
                    if !p.is_empty() {
                        out.push(p.clone());
                    }
                }
            }
        }
        // Don't recurse into `command` children — done.
        return;
    }
    // Recurse on non-command nodes (program, list, pipeline, etc.).
    for i in 0..node.named_child_count() {
        if let Some(child) = node.named_child(i) {
            collect_mutation_paths(child, source, mutators, out);
        }
    }
}

#[cfg(feature = "semantic-bash")]
fn collect_redirect_targets(node: tree_sitter::Node, source: &[u8], out: &mut Vec<String>) {
    match node.kind() {
        // `file_redirect` is the tree-sitter-bash node for `> file`,
        // `>> file`, `&> file`, `1> file`, `2> file`, etc. It has the
        // operator as an anonymous child + a `word`/`string`/etc.
        // named child carrying the destination.
        "file_redirect" => {
            // Find the destination — typically the last named child.
            for i in (0..node.named_child_count()).rev() {
                if let Some(child) = node.named_child(i) {
                    if let Ok(text) = child.utf8_text(source) {
                        let trimmed = unquote_simple(text.trim());
                        if !trimmed.is_empty()
                            && !trimmed.starts_with("&")
                            && !trimmed.chars().all(|c| c.is_ascii_digit())
                        {
                            out.push(trimmed);
                        }
                    }
                    break;
                }
            }
        }
        // `herestring_redirect` (<<<) is followed by a value, not a
        // file target — skip. Heredoc (<<EOF) similarly has no path.
        "heredoc_redirect" | "herestring_redirect" => {}
        _ => {
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    collect_redirect_targets(child, source, out);
                }
            }
        }
    }
}

#[cfg(feature = "semantic-bash")]
fn unquote_simple(s: &str) -> String {
    // Tree-sitter `word` nodes come without quotes; `string` nodes
    // include them. Strip a single matched pair of leading/trailing
    // quotes so the path matches what the shell would resolve.
    let bytes = s.as_bytes();
    if bytes.len() >= 2
        && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
            || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''))
    {
        return s[1..s.len() - 1].to_string();
    }
    s.to_string()
}

#[allow(dead_code)]
pub fn parse_bash_segments(command: &str) -> Vec<String> {
    parse_bash_segments_full(command)
        .map(|(segs, _)| segs)
        .unwrap_or_else(|_| vec![command.to_string()])
}

pub fn parse_bash_segments_full(command: &str) -> Result<(Vec<String>, bool), String> {
    #[cfg(feature = "semantic-bash")]
    {
        use tree_sitter::Parser;

        let lang: tree_sitter::Language = tree_sitter_bash::LANGUAGE.into();
        let mut parser = Parser::new();
        parser
            .set_language(&lang)
            .map_err(|e| format!("Failed to set bash language: {e}"))?;

        let tree = parser
            .parse(command, None)
            .ok_or("Failed to parse bash command")?;

        let root = tree.root_node();
        let source = command.as_bytes();

        let mut segments = Vec::new();
        let mut is_complex = false;

        if has_complex_constructs(root) {
            is_complex = true;
            segments.push(command.to_string());
            return Ok((segments, is_complex));
        }

        if root.has_error() {
            segments.push(command.to_string());
            return Ok((segments, is_complex));
        }

        collect_segments(root, source, &mut segments);
        if segments.is_empty() {
            segments.push(command.to_string());
        }

        Ok((segments, is_complex))
    }
    #[cfg(not(feature = "semantic-bash"))]
    {
        Ok((vec![command.to_string()], false))
    }
}

#[cfg(feature = "semantic-bash")]
fn has_complex_constructs(node: tree_sitter::Node) -> bool {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            match child.kind() {
                "command_substitution"
                | "process_substitution"
                | "subshell"
                | "arithmetic_expansion" => return true,
                _ => {
                    if has_complex_constructs(child) {
                        return true;
                    }
                }
            }
        }
    }
    false
}

#[cfg(feature = "semantic-bash")]
fn collect_segments(node: tree_sitter::Node, source: &[u8], out: &mut Vec<String>) {
    // C3 (audit fix): compound forms (`{ ... }`, `if`, `while`, `for`,
    // `case`, function bodies) previously pushed the whole construct
    // as one opaque segment that matched no per-command rule — so
    // `{ rm -rf /tmp/foo; }` and `if cond; then rm; fi` bypassed
    // every bash permission rule. Opencode's `shell.ts` recurses via
    // `descendantsOfType("command")`; we mirror that by recursing
    // into compound forms so each contained `command` node lands as
    // its own segment.
    match node.kind() {
        "program" | "list" => {
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    collect_segments(child, source, out);
                }
            }
        }
        "pipeline" => {
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    // Each side of a pipe is checked separately —
                    // preserve the leaf-text behaviour here (a
                    // pipeline element is a single command, possibly
                    // redirected; recursing once into a redirected
                    // pipeline element collects the inner command).
                    if child.kind() == "redirected_statement"
                        || child.kind() == "compound_statement"
                        || child.kind() == "if_statement"
                        || child.kind() == "while_statement"
                        || child.kind() == "for_statement"
                        || child.kind() == "case_statement"
                        || child.kind() == "function_definition"
                        || child.kind() == "c_style_for_statement"
                    {
                        collect_segments(child, source, out);
                    } else {
                        let text = child.utf8_text(source).unwrap_or("").trim().to_string();
                        if !text.is_empty() {
                            out.push(text);
                        }
                    }
                }
            }
        }
        // Compound forms — recurse so each inner `command` lands as
        // its own segment.
        "compound_statement"
        | "if_statement"
        | "while_statement"
        | "for_statement"
        | "case_statement"
        | "function_definition"
        | "c_style_for_statement"
        | "case_item"
        | "elif_clause"
        | "else_clause"
        | "do_group" => {
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    collect_segments(child, source, out);
                }
            }
        }
        // Redirected command — recurse so the wrapped command is
        // checked. C4 (a follow-on fix) will additionally check the
        // redirect target through the path gate; for now the
        // segment text used by command-pattern rules is the inner
        // command without its redirections, matching how opencode
        // separates the two concerns.
        "redirected_statement" => {
            // Find the inner command/pipeline; the redirect operands
            // are leaf nodes (file_redirect, heredoc_redirect, etc.)
            // that don't carry shell-command text.
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    match child.kind() {
                        "command" | "pipeline" | "compound_statement" | "subshell" => {
                            collect_segments(child, source, out);
                        }
                        _ => {} // redirect operands — handled by C4
                    }
                }
            }
        }
        "command" => {
            let text = node.utf8_text(source).unwrap_or("").trim().to_string();
            if !text.is_empty() {
                out.push(text);
            }
        }
        _ => {
            for i in 0..node.named_child_count() {
                if let Some(child) = node.named_child(i) {
                    collect_segments(child, source, out);
                }
            }
        }
    }
}