Repository navigation
test(discover): let bash decide whether a rewrite changed what runs, and fix what it found (#3262) - #5100
Conversation
📊 Automated PR Analysis
SummaryReplaces regex-based env-prefix parsing with a word-by-word scanner (split_env_prefix/split_env_word) that correctly handles quoted assignment values containing blanks, fixing a bug where rewrites edited inside quoted literals like Review Checklist
Linked issues: #3262 Analyzed automatically by wshm · This is an automated analysis, not a human review. |
aeppling
left a comment
There was a problem hiding this comment.
Thanks for splitting this out of #4136. Reviewed at e9b08cf6, compared against develop 9cc447b2 with release builds of both.
Blockers
1. False RTK_DISABLED detection (not on develop)
prefix_contains_rtk_disabled is a substring check on the prefix. The prefix can now hold a whole quoted value that ends its statement, so a message that only mentions the variable trips it.
$ rtk rewrite "MSG='use RTK_DISABLED=1'; git status"
MSG='use RTK_DISABLED=1'; rtk git status
[rtk] RTK_DISABLED=1 detected — skipping filter for this command. Remove RTK_DISABLED=1 to restore token savings.
Develop prints the same rewrite with no warning. The line is aimed at the agent (#508), so it pushes the agent to edit its own commit message.
rtk gain is affected the same way through cmd_has_rtk_disabled_prefix. With one such command in a 3-command session:
[warn] 1 commands (33%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details
Develop shows no warning for that session.
Suggested fix: match an assignment word that starts with RTK_DISABLED=, walking the prefix with word_end_from / skip_blanks, instead of contains. Please add a test for both paths.
2. The oracle runs bash in the contributor's environment
Oracle::trace uses Command::new("bash"), so it inherits the whole environment and runs in the repo directory. That goes against the machine-independence rule in .claude/rules/cli-testing.md. Either of these makes all 3 tests fail with "ran nothing a stub recorded":
- an exported function:
BASH_FUNC_git%%='() { /usr/bin/git "$@"; }' - a
BASH_ENVfile that definesgit()
In both runs the real git status ran in the test's directory.
Suggested fix: build the command with common::native_command("bash") and set .current_dir(&self.root).
e9b08cf to
5ab5ccc
Compare
|
Thank you for the review, both blockers reproduced here and are fixed in the amended commit ( 1. False One shape is left: a 2. The oracle's environment: all three Also rebased onto develop. |
aeppling
left a comment
There was a problem hiding this comment.
One case of the false RTK_DISABLED detection is still there: a prefix with no command after it.
$ rtk rewrite "RTK_DISABLED=1; git status"
RTK_DISABLED=1; rtk git status
[rtk] RTK_DISABLED=1 detected — skipping filter for this command. Remove RTK_DISABLED=1 to restore token savings.
Same with RTK_DISABLED=1 && git status, FOO=1 RTK_DISABLED=1; git status and RTK_DISABLED=1 alone, through rtk hook claude too. The assignment only sets a shell variable and the command is still rewritten. develop prints no warning there.
Only warning when a command follows the prefix fixes it, in rewrite_segment_inner:
if !rest_after_env.is_empty() && prefix_contains_rtk_disabled(env_prefix) {RTK_DISABLED=1 git status, X=1; RTK_DISABLED=1 git status and env RTK_DISABLED=1 git status still warn and skip the rewrite with that change. Please add a test for the statement form.
Also, RTK_DISABLED+=1 git status is now rewritten, because the check only matches RTK_DISABLED=. develop left it alone.
Correction to my first review: the rtk gain warning for the MSG='use RTK_DISABLED=1' session shows on develop too, so only the rtk rewrite half of that point was a regression. Your change fixes both.
5ab5ccc to
c9eb6d6
Compare
|
Thanks, both reproduce on a develop build, and both are fixed in the first commit.
Your two findings had the same shape: the prefix reader got wider (by words, lowercase names,
To look for more of them I ran develop's binary and this branch's over about 32,000 generated lines and a further 27,000 (prefix shapes of Left as on develop, in case they are worth separate issues: a subshell or brace group ( |
…and fix what it found (rtk-ai#3262) Every test of the rewriter compares it against an expectation somebody wrote down. A mistake in the author's model of shell grammar therefore sits on both sides of the comparison and agrees with itself — which is how a rewrite that reached inside `$( )` passed a full suite, and how a bracket counted on one side but not the other passed it again. This asks bash instead. Recording stubs sit ahead of everything on `PATH`, the original command and its rewrite are each run, and what actually executed has to match: which programs, with which arguments, in which directory. The `rtk` stub runs the command it wraps and marks its output, the way the real one filters, so a rewrite at a command position changes nothing that is compared while one that reaches into a substitution changes the text the outer command was built from. Three things had to be got right, none of which reading the code would have told me: - `echo` is a shell builtin, so a stub by that name is never reached. The outer command of a substitution has to be one bash looks up on `PATH`. - The stages of a pipeline run concurrently and reach the log in whatever order they are scheduled, so the comparison is over a set. - `>( )` hands over the writing end of a pipe. It opens but never delivers, so reading it waits for a writer that is waiting for this process to finish. The oracle is held to detecting as well as passing. Alongside the equivalence cases are rewrites wrong in ways this repository has actually shipped — reaching into a substitution, into a process substitution, into a quoted assignment, and turning one command into another — each of which it has to object to. And a command RTK merely declined to rewrite runs identically, so it has to stay quiet about that, or "everything differs" would satisfy the rest. It found rtk-ai#3262 on its first run against the real rewriter, from a case nobody had written an expectation for. `D='# shellcheck disable=SC2034'; echo hi` came back as `D='# rtk shellcheck disable=SC2034'; echo hi`: RTK edited inside a quoted literal, so the variable held text nobody wrote. The env prefix was matched with a pattern whose value alternation is `(?:"…"|'…'|[^\s]*)` followed by `\s+`. A quoted value that is not followed by a blank fails that `\s+`, the alternation backtracks to the unquoted branch, and `[^\s]*` takes the fragment up to the first space — `D='# ` — leaving `shellcheck disable=SC2034'` to be read as the command. Three shapes share the one cause, and only the first was reported: D='# shellcheck disable=SC2034'; echo hi -> prefix D='# command shellcheck … D="x y"; echo hi -> prefix D="x command y"… D='no trailing space' -> prefix D='no command trailing… A quoted value is one word however many blanks it holds, so the prefix is now read by scanning words with quote state rather than by matching a pattern: a backslash escapes inside double quotes and is literal inside single ones, and a word ends at the first blank or newline that is not inside either; inside `$'…'` a backslash escapes, and an escaped or doubled `$` opens nothing. An array, a substitution, an expansion or a quote with no closing holds blanks in ways that reading them is the lexer's job, so a word with one in it has no certain end. It is taken at its first blank, as the pattern took it, so such a word never hides a command from a rule that reads commands. For the names the pattern knew (uppercase, `=`) the rewrite reads it that way too, so `RUST_LOG=${LEVEL} cargo test` is rewritten as it was; for a name this change adds, `a=(git diff --stat)` is not an assignment and the rewrite leaves it alone rather than edit inside it. A backslash before a newline is read the same way, because the rewrite joins the continuation as a blank where bash joins nothing. A word is an assignment on bash's own terms: a name of letters, digits and `_` not starting with a digit, then `=` or `+=`, in any case. The pattern took uppercase names only, so `foo=bar git status` was never rewritten, and `d='# shellcheck …'` escaped the quoting fix above only by not being recognised at all. `1a=b`, `foo-bar=x` and `"foo"=x` are commands to bash and stay commands here. `sudo` is still never stripped (rtk-ai#146). Four call sites read that prefix and each carried its own copy of the pattern, which is why they had to change together or disagree. They now go through one `split_env_prefix`, so there is one place to be right. It also retires `strip_disabled_prefix`'s trick of recovering the prefix length by subtracting the stripped string's length from the original's, which worked only because the pattern happened to remove a prefix. `RTK_DISABLED=` (and `RTK_DISABLED+=`) is one of those words, so it is recognised as one: a message that only mentions it (`MSG='use RTK_DISABLED=1'; git status`) disables nothing and draws no warning, in `rtk rewrite`, `rtk gain` and `rtk discover` alike. The warning says a command was skipped, so an assignment with no command after it (`RTK_DISABLED=1; git status`) draws none either, and the command behind the `;` is rewritten. The splitter holds that rule: a line that is nothing but assignments has no prefix, so the rewrite, the reader of a quoted script, `rtk gain` and `rtk discover` all see the same thing; `gain` reads each command of a line, as the rewrite does. The permission gate reads the command behind each assignment in turn, so a deny or ask rule can name any layer of a prefix. It does so through `split_env_word`, the same word reading one word at a time, so an assignment that ends its statement is one word there too: `MSG="chore: rm -rf build dir" && git commit -m "$MSG"` is no longer denied by `Bash(rm -rf *)`. Unix only, and skipped where there is no bash. What a process substitution carries can only be compared where a bounded read is available, and `timeout` is coreutils, which macOS does not ship — so the oracle checks for it and drops the two `<( )`/`>( )` cases when it is missing, rather than comparing two empty readings and calling them equal. Every trace is also required to be non-empty, because a case whose programs are all unstubbed records nothing on either side and would otherwise pass while testing nothing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The oracle checks that a rewrite runs the same programs, which also holds when rtk declines to rewrite at all. These tests pin the rewrite itself for the shapes rtk-ai#3262 was reported with: a quoted assignment value holding a command name, a `|`, a `;` or prose, before a `;`, at the end of the line or glued to an unquoted part, and the commands outside the quotes that are still rewritten. The oracle also runs `FOO=a\ git status`, whose escaped blank belongs to the value, so the line runs `status` and there is no `git` to rewrite. Co-authored-by: zhiwuyazhe_fjr <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
c9eb6d6 to
85067de
Compare
aeppling
left a comment
There was a problem hiding this comment.
Thanks, the round-2 points and the four readers are fixed, and #3262 is gone in a real Claude Code session.
One regression: a deny rule is lost when an assignment prefix spans a line continuation. With deny: ["Bash(git push:*)"]:
$ rtk rewrite $'D=1 \\\na1=x git push origin main'; echo "rc=$?"
D=1 a1=x rtk git push origin main
rc=3
develop and v1.2.1 leave the line alone (rc 1), so Claude Code denies it. On this branch the rule no longer matches the command behind rtk. In a real session with deny: ["Bash(git status:*)"] and D=1 \⏎a1=x git status, Claude Code denies the command with the v1.2.1 hook (develop returns the same rc 1). With this branch's hook it asks for approval, and under --permission-mode bypassPermissions the command runs.
Same with D="a b" \⏎x=1 git push origin main, x=1 git\⏎push origin main and x=1 git push\ followed by CRLF and origin main: each is rewritten with rc 3, where develop returns rc 1.
…e command The deny check read the line as written, where a `\<newline>` stops the word scan, while the rewrite reads it joined: `D=1 \<newline>a1=x git push` was rewritten to `D=1 a1=x rtk git push` past a `git push:*` deny rule. When a join changes the line, the deny rules are also checked on the line as bash joins it and as the rewrite joins it. A deny on either returns Defer, so the host decides on the line as written.
…e command The joined readings of a line holding a continuation were checked against the deny rules only, so an ask rule did not see a command split by one: `D=1 \<newline>a1=x git push` was auto-allowed past a `git push:*` ask rule. An ask found on a joined line now returns Defer unless the line as written already asks, so the host decides on it. A deny inside a shell wrapper that only a joined line shows returns Defer too. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Thanks for The joined readings were checked against the deny rules only, so the same split got past an One borderline case remains. With deny
On the split line, the deny found on the joined reading returns Defer, which takes precedence over the ask raised by My personal view is that when one command of a line is denied, the whole line should be denied, with a hint to the agent naming the denied command so it can rewrite the line without it. I left the behaviour as it is in this push, and I am interested in what you think. |
A line that already defers returns before the joined readings, and a reading identical to the line is skipped. The exit-code table and the gate order point to `PermissionVerdict::Defer` for what defers. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Agreed, pushed The hint sounds right for hosts where RTK blocks the call itself. I'd keep it for a separate PR. |
This is #4136's commit on its own: it needs none of the lexer work it was stacked on, so it can land on develop and fix #3262 there. #3462 fixed the same bug; its regression tests pass on this branch, except one spacing assertion that fails on develop too.
tests/exec_equivalence_test.rsruns a command and its rewrite under bash with recording stubs ahead of everything onPATH, and requires the same programs to run with the same arguments in the same directory. The expectations in every other rewriter test were written by the same person who wrote the rewriter, so a wrong model of shell grammar sits on both sides. The oracle is held to detecting as well as passing: it has to object to four rewrites that are wrong in ways this repository has shipped, and stay quiet about one that merely skipped a command. A case list of arrays, expansions and substitutions in assignment values is included. Unix only, skipped where there is no bash.On its first run it found #3262:
D='# shellcheck disable=SC2034'; echo hiwas rewritten toD='# rtk shellcheck disable=SC2034'; echo hi. The env prefix was matched by a pattern that backtracks into a quoted value when no blank follows it, soshellcheck disable=SC2034'was read as the command.D="x y"; echo hiandD='no trailing space'fail the same way.split_env_prefix. A quoted value is one word, andD='# shellcheck …'is left as written._not starting with a digit, then=or+=, in any case.foo=bar git statusis now rewritten asfoo=bar rtk git status, and1a=b,foo-bar=xand"foo"=xstay commands.=names the old pattern knew, the word ends at its first blank as before:RUST_LOG=${LEVEL} cargo testis still rewritten. For the names this change adds,a=(git diff --stat)is not an assignment and the line is left alone.RTK_DISABLED=andRTK_DISABLED+=are read as assignment words, soMSG='use RTK_DISABLED=1'; git statusdisables nothing and warns about nothing. An assignment with no command after it (RTK_DISABLED=1; git status) has no prefix, draws no warning, and the command behind the;is rewritten.rtk gainandrtk discoverread the prefix the same way,gainone command at a time as the rewrite does, and a newline or carriage return ends an assignment like a blank.uv run bash -c 'RTK_DISABLED=1; echo hi') no longer takes a bare assignment as an opt-out, so the call is routed as on develop.split_env_word:MSG="chore: rm -rf build dir" && git commit -m "$MSG"is no longer denied byBash(rm -rf *).sudois still never stripped (Feature Request: Add sudo prefix support for command rewriting #146).The quoted-assignment tests assert the whole rewritten line rather than that something changed.
Test plan
cargo fmt --all --check,cargo clippy --all-targets(no warnings),cargo test --all --no-fail-faston this branch: 5847 passed, 0 failedrtk rewriteof 31,933 generated lines (prefix shapes ofRTK_DISABLED=,+=, lowercase names, quoted and escaped values, arrays, expansions,env, wrappers, separators) compared with develop's binary, and a further 27,000 comparisons under three permission configs, both run before the line-continuation check was added: no line that bash runs withRTK_DISABLEDset is rewritten, and every line this branch rewrites less than develop is a quoted assignment (bug(hook): rewrite edits inside quoted string literals — 'shellcheck' in a single-quoted sed replacement became 'rtk shellcheck' (data corruption) #3262), an escaped blank in a value, or an assignment with nothing behind itcurl *) gives the same verdict as develop on every rowgitandcargothat log whetherRTK_DISABLEDreached themFixes #3262
🤖 Generated with Claude Code