Skip to content

feat(command-risk): parse commands with an in-crate shell parser - #294

Merged
mrnasil merged 2 commits into
mainfrom
feat/command-risk-ast
Oct 16, 2026
Merged

mrnasil merged 2 commits into
mainfrom
feat/command-risk-ast

Conversation

@mrnasil

@mrnasil mrnasil commented Oct 16, 2026

Copy link
Copy Markdown
Member

What

crates/command-risk gets a parser-grade front-end: src/parse.rs, a recursive-descent parser for the shell agents write, lowered to the existing tokenize::Segment shape. assess_segment and paths.rs (the parser-independent catastrophic tier) are unchanged. On any ParseError (unbalanced quotes, PowerShell/cmd syntax, a here-document with no terminator, nesting over 64) the old tokenizer runs exactly as before, so a line the parser cannot read is judged no less strictly than it was.

Supported: lists (; & && || newline), pipelines (| |& !), subshells, brace groups, if/while/until/for/select/case, function definitions, [[ ]], (( )), single, double, ANSI-C $'…' and $"…" quoting, $(…), backticks, $((…)), ${…}, process substitution, typed redirects (> >> >| &> &>> >& < <> <& <<<, fd numbers), here-documents (<<, <<-, quoted delimiters), scalar and array assignments.

New catches (all in the corpus test)

  • Assignment propagation: DIR=/; rm -rf $DIR, X=~ rm -rf $X, d=~; rm -rf "$d", export T=$HOME && rm -rf "$T", for d in build ~; do rm -rf $d; done, if …; then D=build; else D=/etc; fi; rm -rf $D are now Catastrophic. Segments are assessed once with variables as written and once per value seen so far (values only accumulate across branches; capped at 16 readings), and the worst wins, so a known value can only add risk (OUT=dist; rm -rf "$OUT" stays Destructive). X=~ rm -rf $X is read pessimistically: bash would expand the old $X, but the line was written to mean the new one.
  • Typed redirects: 2>&1, >&2, >&- and reads write no file; >&/tmp/x is a truncating write (the tokenizer saw & as a separator → was Safe). A leading redirect no longer sits in the command slot: >/dev/null rm -rf ~ was Safe before, now Catastrophic.
  • Here-documents are data: cat <<EOF with rm -rf / in its body is Safe (was Catastrophic). Fed to a shell (bash <<EOF, cat <<EOF | sh, bash <<< 'rm -rf ~') the body is assessed as a script; bash <<< 'rm -rf ~' was Safe before.
  • Exact quoting: rm -rf $'\x2f'etc is /etc → Catastrophic (was Caution).
  • Substitutions as structure: echo $(echo ")"; rm -rf ~) (raw scan stopped at the quoted )) and diff <(rm -rf ~) x are Catastrophic (were Destructive). The raw substitution_bodies scan is kept and unioned with the parser's bodies, so substitutions inside single quotes are still pessimistically assessed.
  • Comments: cmd.exe has no # comments, so comment text is re-split by the tokenizer and appended: echo # & rm -rf ~ is refused; # note\ncargo build stays Safe.

Why no dependency

Evaluated per the spike:

  • brush-parser 0.4.0: MIT, MSRV 1.88 (ok vs 1.91), ~60 µs/parse in release. But it pulls 77 crates into a currently zero-dependency foundation linked into the agent, including peg, cached, bon, uuid, getrandom and insta (a snapshot-testing library) as normal dependencies; none are in Cargo.lock today. Clean release build of a stub using it: 37 s. Its Word is still raw text needing a second word::parse pass, and it is bash-only like ours.
  • yash-syntax: GPL-3.0-or-later, fails deny.toml; MSRV 1.96 > 1.91.
  • conch-parser: unmaintained since 2019.
  • tree-sitter-bash: C build via cc, 438 KB crate.

The in-crate parser is ~1000 lines of production code, no unwrap/expect, no new dependency (so cargo deny/cargo audit are unaffected and dependency_boundaries.json needs no change).

Verdicts

Every existing test in assess.rs, tokenize.rs and lib.rs passes unchanged. New assess::tests::corpus_verdicts has 55 commands; the 33 build/test/everyday commands (cargo, npm, make, go, pytest, cmake, docker, 2>&1 | tail, for/if/case/while loops, [[ ]] ||, heredoc to /dev/null…) are all Safe.

Performance

Criterion, release, Windows (busy shared machine, so ±20%), same session, main vs this branch:

bench main branch
safe_short ls -la 1.2 µs 5.0 µs
safe_build 4.3 µs 8.2 µs
pipeline 14.3 µs 21.9 µs
chain/10 58 µs 133 µs
chain/50 (~1.4k chars) 278 µs 774 µs
typical_200 (new, 216 chars) – 39 µs
assign_heredoc (new) – 33 µs

A typical 200-character command is ~25× under the 1 ms budget. New test a_typical_command_is_assessed_well_under_a_millisecond asserts best-of-5 < 1 ms in optimised builds (< 10 ms in debug/coverage builds, to catch blow-ups without flaking). No check_bench_ceilings.py entry: it has no per-crate ceilings and the cost stays well below 1 ms.

Checks run

  • cargo check -p whycodes-command-risk ok
  • cargo test -p whycodes-command-risk 111 passed; cargo test -p whycodes-agent --lib 641 passed (only dependent, per scripts/affected_tests.py)
  • cargo clippy -p whycodes-command-risk --all-targets -- -D warnings clean
  • cargo fmt --all --check clean
  • check_panic_budget.py, check_swallowed_error_budget.py, check_dependency_boundaries.py, check_tracked_secrets.py: ok

Coverage (100% floor)

  • Linux (WSL Arch, cargo llvm-cov -p whycodes-command-risk --lib + -skip-expansions summary + check_coverage_floors.py): OK whycodes-command-risk 2608/2608 lines 100.0%.
  • Windows: 2539/2540; the one miss is lib.rs:253 (the None => env-restore arm in assess_and_home_dir_read_the_environment), which also misses on a clean main on this machine because every home variable is set on Windows. Platform-only, pre-existing.

Docs

  • docs/guide.md "Shell command risk": what the parser now catches, fallback and comment behaviour.
  • docs/internals/permission-gate.md: front-end/fallback, readings, heredocs, typed redirects, limitations (bash syntax only; variables do not flow into $(…) bodies or across cd).

Closes #286

🤖 Generated with Claude Code

mrnasil and others added 2 commits October 17, 2026 00:06
A recursive-descent parser (crates/command-risk/src/parse.rs) now reads
the command and lowers it to the tokenizer's Segment shape, so assess.rs
and the parser-independent catastrophic tier in paths.rs are unchanged.
A parse error falls back to the tokenizer.

New: assignment propagation (DIR=/; rm -rf $DIR, X=~ rm -rf $X, export,
for items) with the as-written reading always assessed too, so a known
value only adds risk; typed redirects (2>&1 is no file, >&file is one,
a leading redirect no longer takes the command slot); here-document
bodies are data unless fed to a shell; exact quoting incl. ANSI-C;
substitution and process-substitution bodies delimited by the parser.
Comments are re-split by the tokenizer because cmd.exe has no # comments.

No dependency added: the maintained bash parser crate pulls ~77 crates
(peg, cached, bon, insta as a normal dependency) into the agent.

Closes #286

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mrnasil
mrnasil merged commit cb114de into main Oct 16, 2026
7 checks passed
@mrnasil
mrnasil deleted the feat/command-risk-ast branch October 16, 2026 21:50
mrnasil added a commit that referenced this pull request Nov 7, 2026
Re-ran the benchmarks (last process run 2026-10-16, last criterion run
2026-09-11). `--version` had drifted to 17 ms on Windows while an empty
Rust exe starts in ~10 ms on the same host. Three fixes:

- Delay-load user32, shell32, combase, oleaut32, ws2_32, bcrypt, userenv
  and advapi32 (MSVC only, build.rs). Loading them eagerly cost ~6 ms per
  process whether or not they were used.
- `hide_possible_values` on the dynamic clap value parsers. clap asked
  them for their values while building the command, which read
  config.toml and opened the session database on every invocation
  (~8 ms). Completion scripts are byte-identical; `--help` no longer
  lists every model id and local session ids.
- Skip the pre-0.7 legacy-instance migration before resolving Windows
  known folders when ~/.whycodes already holds instance files (~9 ms
  once the DLLs above are deferred). Behavior is unchanged: the copy
  step already returned early in that case.

Interleaved medians, before -> after: --version 17.5 -> 10.5 ms,
--help 26.1 -> 10.8 ms, config show 42.2 -> 23.2 ms, session list
44.1 -> 25.8 ms. Peak RSS of config show 14.2 -> 7.6 MB. TUI harness
spawn-to-exit 20.0 -> 12.5 ms. Criterion hot paths are flat or faster
except short `assess` calls (~1 us fixed cost from the #294 parser,
documented and left alone).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mrnasil added a commit that referenced this pull request Nov 7, 2026
Re-ran the benchmarks (last process run 2026-10-16, last criterion run
2026-09-11). `--version` had drifted to 17 ms on Windows while an empty
Rust exe starts in ~10 ms on the same host. Three fixes:

- Delay-load user32, shell32, combase, oleaut32, ws2_32, bcrypt, userenv
  and advapi32 (MSVC only, build.rs). Loading them eagerly cost ~6 ms per
  process whether or not they were used.
- `hide_possible_values` on the dynamic clap value parsers. clap asked
  them for their values while building the command, which read
  config.toml and opened the session database on every invocation
  (~8 ms). Completion scripts are byte-identical; `--help` no longer
  lists every model id and local session ids.
- Skip the pre-0.7 legacy-instance migration before resolving Windows
  known folders when ~/.whycodes already holds instance files (~9 ms
  once the DLLs above are deferred). Behavior is unchanged: the copy
  step already returned early in that case.

Interleaved medians, before -> after: --version 17.5 -> 10.5 ms,
--help 26.1 -> 10.8 ms, config show 42.2 -> 23.2 ms, session list
44.1 -> 25.8 ms. Peak RSS of config show 14.2 -> 7.6 MB. TUI harness
spawn-to-exit 20.0 -> 12.5 ms. Criterion hot paths are flat or faster
except short `assess` calls (~1 us fixed cost from the #294 parser,
documented and left alone).

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(command-risk): parse commands with a real shell AST

1 participant