bash-ast 0.8.20

Typed Rust AST over tree-sitter-bash. Parses bash source into a strongly-typed tree suitable for structural analysis (permission gating, linting, refactoring) rather than execution.
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
use bash_ast::{parse_to_ast, summary::summarise_bash_shape};

// ============================================================================
// Helper
// ============================================================================

fn shape(src: &str) -> bash_ast::summary::BashShape {
    let prog = parse_to_ast(src).unwrap_or_else(|e| panic!("parse failed for {:?}: {e:?}", src));
    summarise_bash_shape(&prog)
}

// ============================================================================
// primary_program + cwd_hint (cd-stripping)
// ============================================================================

#[test]
fn simple_command_primary_program() {
    let s = shape("cargo check --workspace");
    assert_eq!(s.primary_program.as_deref(), Some("cargo"));
    assert_eq!(s.cwd_hint, None);
}

#[test]
fn cd_and_then_command_primary_program_and_cwd_hint() {
    let s = shape("cd packages/yah/ui && bun run typecheck");
    assert_eq!(s.primary_program.as_deref(), Some("bun"));
    assert_eq!(s.cwd_hint.as_deref(), Some("packages/yah/ui"));
}

#[test]
fn double_cd_chain() {
    let s = shape("cd /tmp && cd sub && cargo test");
    assert_eq!(s.primary_program.as_deref(), Some("cargo"));
    // cwd_hint from the last cd before the real command
    assert_eq!(s.cwd_hint.as_deref(), Some("sub"));
}

#[test]
fn leading_var_assignment_skipped() {
    let s = shape("RUST_LOG=debug cargo run -p yah");
    // tree-sitter parses `RUST_LOG=debug cargo run` as a Command with a leading
    // variable assignment, so primary_program should still be "cargo".
    assert_eq!(s.primary_program.as_deref(), Some("cargo"));
}

#[test]
fn pipeline_primary_is_first_stage() {
    let s = shape("cargo check 2>&1 | head -20");
    assert_eq!(s.primary_program.as_deref(), Some("cargo"));
}

// ============================================================================
// all_programs
// ============================================================================

#[test]
fn all_programs_single() {
    let s = shape("cargo build -p desktop");
    assert_eq!(s.all_programs, vec!["cargo"]);
}

#[test]
fn all_programs_pipeline_deduped() {
    let s = shape("cargo check | grep error | grep error");
    assert_eq!(s.all_programs, vec!["cargo", "grep"]);
}

#[test]
fn all_programs_list() {
    let s = shape("cargo check && bun run build");
    assert_eq!(s.all_programs, vec!["cargo", "bun"]);
}

// ============================================================================
// list_ops
// ============================================================================

#[test]
fn list_ops_and() {
    let s = shape("cargo check && echo done");
    assert_eq!(s.list_ops, vec!["&&"]);
}

#[test]
fn list_ops_or() {
    let s = shape("cargo check || echo failed");
    assert_eq!(s.list_ops, vec!["||"]);
}

#[test]
fn list_ops_mixed_deduped() {
    let s = shape("a && b && c || d");
    // Three list nodes: && && ||. After dedup: &&, ||.
    assert!(s.list_ops.iter().any(|op| op == "&&"));
    assert!(s.list_ops.iter().any(|op| op == "||"));
}

// ============================================================================
// pipeline_stages
// ============================================================================

#[test]
fn pipeline_stages_single_command() {
    let s = shape("cargo check");
    assert_eq!(s.pipeline_stages, 1);
}

#[test]
fn pipeline_stages_two_stage() {
    let s = shape("echo hi | grep hi");
    assert_eq!(s.pipeline_stages, 2);
}

#[test]
fn pipeline_stages_three_stage() {
    let s = shape("cat file.txt | grep foo | wc -l");
    assert_eq!(s.pipeline_stages, 3);
}

// ============================================================================
// redirects
// ============================================================================

#[test]
fn redirects_stderr_to_stdout() {
    // tree-sitter splits `2>&1` into descriptor=`2` + operator=`>&`.
    // The redirects field stores the operator token only, not the full spec.
    let s = shape("cargo build 2>&1");
    assert!(s.redirects.contains(&">&".to_string()), "redirects={:?}", s.redirects);
}

#[test]
fn redirects_append() {
    let s = shape("echo hi >> out.txt");
    assert!(s.redirects.contains(&">>".to_string()), "redirects={:?}", s.redirects);
}

#[test]
fn no_redirects() {
    let s = shape("cargo check");
    assert!(s.redirects.is_empty());
}

// ============================================================================
// has_heredoc
// ============================================================================

#[test]
fn heredoc_detected() {
    let s = shape("cat <<EOF\nhello\nEOF");
    assert!(s.has_heredoc);
}

#[test]
fn no_heredoc() {
    let s = shape("echo hello");
    assert!(!s.has_heredoc);
}

// ============================================================================
// SideEffect: GitWrite
// ============================================================================

#[test]
fn side_effect_git_push() {
    let s = shape("git push origin main");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::GitWrite)));
}

#[test]
fn side_effect_git_commit() {
    let s = shape("git commit -m 'fix'");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::GitWrite)));
}

#[test]
fn no_side_effect_git_log() {
    let s = shape("git log --oneline -10");
    assert!(s.side_effect.is_none(), "git log should not be classified as side-effect");
}

#[test]
fn no_side_effect_git_status() {
    let s = shape("git status");
    assert!(s.side_effect.is_none());
}

// ============================================================================
// SideEffect: GitHub
// ============================================================================

#[test]
fn side_effect_gh_pr_create() {
    let s = shape("gh pr create --title 'My PR'");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::GitHub)));
}

#[test]
fn side_effect_gh_release_create() {
    let s = shape("gh release create v1.0.0");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::GitHub)));
}

#[test]
fn no_side_effect_gh_pr_view() {
    let s = shape("gh pr view 123");
    assert!(s.side_effect.is_none(), "gh pr view should not trigger GitHub side-effect");
}

// ============================================================================
// SideEffect: Publish
// ============================================================================

#[test]
fn side_effect_cargo_publish() {
    let s = shape("cargo publish --dry-run");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::Publish)));
}

#[test]
fn no_side_effect_cargo_build() {
    let s = shape("cargo build -p desktop");
    assert!(s.side_effect.is_none());
}

// ============================================================================
// SideEffect: Destructive
// ============================================================================

#[test]
fn side_effect_rm() {
    let s = shape("rm -rf /tmp/foo");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::Destructive)));
}

#[test]
fn side_effect_mkfs() {
    let s = shape("mkfs.ext4 /dev/sdb");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::Destructive)));
}

// ============================================================================
// SideEffect: Network
// ============================================================================

#[test]
fn side_effect_curl_post() {
    let s = shape("curl -X POST https://api.example.com/data");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::Network)));
}

#[test]
fn side_effect_curl_merged_delete() {
    let s = shape("curl -XDELETE https://api.example.com/item/1");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::Network)));
}

#[test]
fn no_side_effect_curl_get() {
    let s = shape("curl https://api.example.com/data");
    assert!(s.side_effect.is_none(), "plain curl GET should not be a side-effect");
}

// ============================================================================
// SideEffect: SudoOrInstall
// ============================================================================

#[test]
fn side_effect_sudo() {
    let s = shape("sudo systemctl restart myservice");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::SudoOrInstall)));
}

#[test]
fn side_effect_brew_install() {
    let s = shape("brew install ripgrep");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::SudoOrInstall)));
}

#[test]
fn side_effect_apt_install() {
    let s = shape("apt-get install -y curl");
    assert!(matches!(s.side_effect, Some(bash_ast::summary::SideEffect::SudoOrInstall)));
}

#[test]
fn no_side_effect_brew_search() {
    let s = shape("brew search ripgrep");
    assert!(s.side_effect.is_none());
}

// ============================================================================
// ProgramKind
// ============================================================================

#[test]
fn kind_ls_is_search() {
    use bash_ast::summary::ProgramKind;
    let s = shape("ls -la src/");
    assert_eq!(s.kind, Some(ProgramKind::Search));
}

#[test]
fn kind_grep_is_search() {
    use bash_ast::summary::ProgramKind;
    let s = shape("grep -r TODO .");
    assert_eq!(s.kind, Some(ProgramKind::Search));
}

#[test]
fn kind_git_is_vcs() {
    use bash_ast::summary::ProgramKind;
    let s = shape("git status");
    assert_eq!(s.kind, Some(ProgramKind::Vcs));
}

#[test]
fn kind_after_cd_strip() {
    use bash_ast::summary::ProgramKind;
    let s = shape("cd packages/yah/ui && bun run typecheck");
    assert_eq!(s.kind, Some(ProgramKind::Build));
}

#[test]
fn kind_curl_is_network() {
    use bash_ast::summary::ProgramKind;
    let s = shape("curl https://api.example.com/data");
    assert_eq!(s.kind, Some(ProgramKind::Network));
}

#[test]
fn kind_rm_is_destructive() {
    use bash_ast::summary::ProgramKind;
    let s = shape("rm -rf /tmp/foo");
    assert_eq!(s.kind, Some(ProgramKind::Destructive));
}

#[test]
fn kind_unknown_program_is_none() {
    let s = shape("flux capacitor --plutonium");
    assert!(s.kind.is_none(), "unknown program should not be classified");
}

#[test]
fn kind_is_orthogonal_to_side_effect() {
    use bash_ast::summary::{ProgramKind, SideEffect};
    // git push: kind=Vcs AND side_effect=GitWrite — both populated.
    let s = shape("git push --force origin main");
    assert_eq!(s.kind, Some(ProgramKind::Vcs));
    assert_eq!(s.side_effect, Some(SideEffect::GitWrite));
}

#[test]
fn kind_peels_timeout_wrapper() {
    use bash_ast::summary::ProgramKind;
    // `timeout 30 git push` — kind tracks the real program, not the wrapper.
    let s = shape("timeout 30 git push origin main");
    assert_eq!(s.kind, Some(ProgramKind::Vcs));
}

#[test]
fn kind_peels_env_wrapper() {
    use bash_ast::summary::ProgramKind;
    let s = shape("env RUST_LOG=debug cargo test");
    assert_eq!(s.kind, Some(ProgramKind::Build));
}

#[test]
fn kind_substring_mcp_fallback() {
    use bash_ast::summary::{ProgramKind, kind_for};
    assert_eq!(kind_for("mcp-server-postgres"), Some(ProgramKind::Mcp));
    assert_eq!(kind_for("claude-mcp"), Some(ProgramKind::Mcp));
    assert_eq!(kind_for("FOO_MCP"), Some(ProgramKind::Mcp));
}

#[test]
fn kind_substring_yah_fallback() {
    use bash_ast::summary::{ProgramKind, kind_for};
    assert_eq!(kind_for("yah-yubaba"), Some(ProgramKind::Yah));
    assert_eq!(kind_for("yah-camp"), Some(ProgramKind::Yah));
}

#[test]
fn kind_yah_wins_over_mcp() {
    use bash_ast::summary::{ProgramKind, kind_for};
    // yah-image-mcp is a yah binary that speaks MCP — kind tracks the
    // family it ships from, not the protocol it speaks.
    assert_eq!(kind_for("yah-image-mcp"), Some(ProgramKind::Yah));
}

#[test]
fn kind_exact_match_wins_over_substring() {
    use bash_ast::summary::{ProgramKind, kind_for};
    // `pwd` doesn't contain mcp/yah; sanity-check that exact-match
    // (Search) still resolves before any substring rule.
    assert_eq!(kind_for("pwd"), Some(ProgramKind::Search));
}

#[test]
fn kind_mcp_substring_fallback() {
    use bash_ast::summary::ProgramKind;
    // Programs that aren't in the exact table but contain "mcp" classify as
    // Mcp via the substring fallback. Names that *also* contain "yah" are
    // covered in kind_yah_wins_over_mcp — keep the cases here pure-mcp.
    assert_eq!(
        shape("mcp-server-postgres --port 7777").kind,
        Some(ProgramKind::Mcp),
    );
    assert_eq!(
        shape("foo-mcp run").kind,
        Some(ProgramKind::Mcp),
    );
    // Case-insensitive
    assert_eq!(
        shape("MCP-Inspector --target foo").kind,
        Some(ProgramKind::Mcp),
    );
}

#[test]
fn kind_mcp_does_not_match_unrelated_names() {
    // `tmpcheck` or `compose` shouldn't match "mcp" — different letter order.
    let s = shape("tmpcheck --quick");
    assert!(s.kind.is_none());
    let s = shape("compose up");
    assert!(s.kind.is_none());
}

#[test]
fn kind_expanded_search_entries() {
    use bash_ast::summary::ProgramKind;
    for cmd in ["fd .", "bat README.md", "jq .name file.json", "ps aux", "htop"] {
        assert_eq!(shape(cmd).kind, Some(ProgramKind::Search), "{cmd}");
    }
}

#[test]
fn kind_expanded_build_entries() {
    use bash_ast::summary::ProgramKind;
    for cmd in ["go build ./...", "deno run main.ts"] {
        let s = shape(cmd);
        // deno is ScriptingRuntime; go is Build — verify each lands correctly.
        let expected = match cmd.split_whitespace().next().unwrap() {
            "deno" => ProgramKind::ScriptingRuntime,
            "go" => ProgramKind::Build,
            _ => unreachable!(),
        };
        assert_eq!(s.kind, Some(expected), "{cmd}");
    }
}

#[test]
fn kind_expanded_container_entries() {
    use bash_ast::summary::ProgramKind;
    for cmd in ["kubectl get pods", "helm install chart", "terraform apply"] {
        assert_eq!(shape(cmd).kind, Some(ProgramKind::Container), "{cmd}");
    }
}

// ============================================================================
// R196-T13: primary_program peel improvements
// ============================================================================

#[test]
fn peel1_pure_assignment_stmts_skipped() {
    // Statements like `pass=0; fail=0; ./run.sh` — the pure assignments
    // should be skipped and the real command found.
    let s = shape("pass=0\nfail=0\n./tests/run_replay_tests.sh 27");
    assert_eq!(
        s.primary_program.as_deref(),
        Some("./tests/run_replay_tests.sh"),
        "primary should be the test runner, not an assignment"
    );
}

#[test]
fn peel2_for_loop_body_recursed() {
    // The load-bearing command is inside a `for` loop body.
    let s = shape("for i in 1 2 3; do\n  ./tests/run_replay_tests.sh \"$i\"\ndone");
    assert_eq!(
        s.primary_program.as_deref(),
        Some("./tests/run_replay_tests.sh"),
        "primary should come from inside the for-loop body"
    );
}

#[test]
fn peel2_while_loop_body_recursed() {
    let s = shape("while true; do\n  ./tests/run_replay_tests.sh 27\ndone");
    assert_eq!(s.primary_program.as_deref(), Some("./tests/run_replay_tests.sh"));
}

#[test]
fn peel2_compound_body_recursed() {
    // `{ ...; }` compound statement.
    let s = shape("{ ./tests/run_replay_tests.sh 27 2>&1; }");
    assert_eq!(s.primary_program.as_deref(), Some("./tests/run_replay_tests.sh"));
}

#[test]
fn peel3_assign_from_cmdsub_unwrapped() {
    // `out=$(VAR=1 ./tests/run_replay_tests.sh 27 2>&1)` — the cmdsub's
    // inner command is the load-bearing program.
    let s = shape("out=$(VAR=1 ./tests/run_replay_tests.sh 27 2>&1)");
    assert_eq!(
        s.primary_program.as_deref(),
        Some("./tests/run_replay_tests.sh"),
        "primary should come from inside the command substitution"
    );
}

#[test]
fn noisetable_repro_for_loop_with_assign_cmdsub() {
    // Full repro from noisetable session:a5025082 — for loop body contains
    // `out=$(VAR=1 ./tests/run_replay_tests.sh 27 2>&1)`.
    let s = shape(
        "for i in $(seq 1 10); do\n  out=$(VAR=1 ./tests/run_replay_tests.sh 27 2>&1)\ndone",
    );
    assert_eq!(
        s.primary_program.as_deref(),
        Some("./tests/run_replay_tests.sh"),
        "primary should drill through for→assign→cmdsub to find the test runner"
    );
}

// ============================================================================
// top_level_statements (R196-F14)
// ============================================================================
//
// Drives the conveyor modal's batch-approve splitter. The whole point of
// surfacing parser-level statement spans is that tree-sitter handles tricky
// cases (line continuations, quoted newlines) that a naive `raw.split('\n')`
// gets wrong — which fanned a single multi-flag `yah board open` invocation
// into a dozen approval prompts.

#[test]
fn top_level_statements_simple() {
    let src = "cargo check";
    let s = shape(src);
    assert_eq!(s.top_level_statements.len(), 1);
    let slice = &s.top_level_statements[0];
    assert_eq!(slice.kind, bash_ast::summary::StatementKind::Command);
    assert_eq!(&src[slice.byte_start..slice.byte_end], "cargo check");
}

#[test]
fn top_level_statements_backslash_continuation_is_one() {
    // Tree-sitter treats backslash-LF as a lexer-level continuation, so a
    // multi-flag invocation broken across lines with `\` produces ONE
    // top-level statement — not one per `\<LF>`. This is the load-bearing
    // case for the AST-driven splitter.
    let src = "yah board open \\\n  --kind feature \\\n  --parent R196 \\\n  --title 'foo'";
    let s = shape(src);
    assert_eq!(
        s.top_level_statements.len(),
        1,
        "backslash-LF continuations must collapse: {:?}",
        s.top_level_statements,
    );
    assert_eq!(s.top_level_statements[0].kind, bash_ast::summary::StatementKind::Command);
}

#[test]
fn top_level_statements_newline_joined_two_commands() {
    let src = "cargo check\nbun run typecheck";
    let s = shape(src);
    assert_eq!(s.top_level_statements.len(), 2);
    let [a, b] = [&s.top_level_statements[0], &s.top_level_statements[1]];
    assert_eq!(&src[a.byte_start..a.byte_end], "cargo check");
    assert_eq!(&src[b.byte_start..b.byte_end], "bun run typecheck");
}

#[test]
fn top_level_statements_pipeline_is_one() {
    // A pipeline is a single top-level statement — splitting it would change
    // semantics, so the slice covers the whole pipe.
    let src = "head -n 20 log | tail -3";
    let s = shape(src);
    assert_eq!(s.top_level_statements.len(), 1);
    assert_eq!(s.top_level_statements[0].kind, bash_ast::summary::StatementKind::Pipeline);
}

#[test]
fn top_level_statements_list_is_one() {
    // `cmd1 && cmd2` is a single List statement (also unsafe to split — the
    // `&&` couples the two commands).
    let src = "cargo check && bun run build";
    let s = shape(src);
    assert_eq!(s.top_level_statements.len(), 1);
    assert_eq!(s.top_level_statements[0].kind, bash_ast::summary::StatementKind::List);
}

#[test]
fn top_level_statements_quoted_newline_does_not_split() {
    // A literal `\n` inside double quotes is part of the argument, not a
    // statement terminator. tree-sitter handles this — the splitter consuming
    // top_level_statements inherits the correctness automatically.
    let src = "echo \"line1\nline2\"";
    let s = shape(src);
    assert_eq!(
        s.top_level_statements.len(),
        1,
        "quoted newline must not split: {:?}",
        s.top_level_statements,
    );
}