Repository navigation
feat(command-risk): parse commands with an in-crate shell parser - #294
Merged
Merged
Conversation
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]>
22 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
crates/command-riskgets a parser-grade front-end:src/parse.rs, a recursive-descent parser for the shell agents write, lowered to the existingtokenize::Segmentshape.assess_segmentandpaths.rs(the parser-independent catastrophic tier) are unchanged. On anyParseError(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)
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 $Dare 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 $Xis read pessimistically: bash would expand the old$X, but the line was written to mean the new one.2>&1,>&2,>&-and reads write no file;>&/tmp/xis 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.cat <<EOFwithrm -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.rm -rf $'\x2f'etcis/etc→ Catastrophic (was Caution).echo $(echo ")"; rm -rf ~)(raw scan stopped at the quoted)) anddiff <(rm -rf ~) xare Catastrophic (were Destructive). The rawsubstitution_bodiesscan is kept and unioned with the parser's bodies, so substitutions inside single quotes are still pessimistically assessed.cmd.exehas no#comments, so comment text is re-split by the tokenizer and appended:echo # & rm -rf ~is refused;# note\ncargo buildstays Safe.Why no dependency
Evaluated per the spike:
brush-parser0.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, includingpeg,cached,bon,uuid,getrandomandinsta(a snapshot-testing library) as normal dependencies; none are inCargo.locktoday. Clean release build of a stub using it: 37 s. ItsWordis still raw text needing a secondword::parsepass, and it is bash-only like ours.yash-syntax: GPL-3.0-or-later, failsdeny.toml; MSRV 1.96 > 1.91.conch-parser: unmaintained since 2019.tree-sitter-bash: C build viacc, 438 KB crate.The in-crate parser is ~1000 lines of production code, no
unwrap/expect, no new dependency (socargo deny/cargo auditare unaffected anddependency_boundaries.jsonneeds no change).Verdicts
Every existing test in
assess.rs,tokenize.rsandlib.rspasses unchanged. Newassess::tests::corpus_verdictshas 55 commands; the 33 build/test/everyday commands (cargo, npm, make, go, pytest, cmake, docker,2>&1 | tail,for/if/case/whileloops,[[ ]] ||, heredoc to/dev/null…) are all Safe.Performance
Criterion, release, Windows (busy shared machine, so ±20%), same session, main vs this branch:
ls -laA typical 200-character command is ~25× under the 1 ms budget. New test
a_typical_command_is_assessed_well_under_a_millisecondasserts best-of-5 < 1 ms in optimised builds (< 10 ms in debug/coverage builds, to catch blow-ups without flaking). Nocheck_bench_ceilings.pyentry: it has no per-crate ceilings and the cost stays well below 1 ms.Checks run
cargo check -p whycodes-command-riskokcargo test -p whycodes-command-risk111 passed;cargo test -p whycodes-agent --lib641 passed (only dependent, perscripts/affected_tests.py)cargo clippy -p whycodes-command-risk --all-targets -- -D warningscleancargo fmt --all --checkcleancheck_panic_budget.py,check_swallowed_error_budget.py,check_dependency_boundaries.py,check_tracked_secrets.py: okCoverage (100% floor)
cargo llvm-cov -p whycodes-command-risk --lib+-skip-expansionssummary +check_coverage_floors.py): OK whycodes-command-risk 2608/2608 lines 100.0%.lib.rs:253(theNone =>env-restore arm inassess_and_home_dir_read_the_environment), which also misses on a cleanmainon 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 acrosscd).Closes #286
🤖 Generated with Claude Code