Skip to content

test(discover): let bash decide whether a rewrite changed what runs, and fix what it found (#3262) - #5100

Merged
aeppling merged 6 commits into
rtk-ai:developfrom
KuSh:test/discover-exec-oracle
Nov 29, 2026
Merged

aeppling merged 6 commits into
rtk-ai:developfrom
KuSh:test/discover-exec-oracle

Conversation

@KuSh

@KuSh KuSh commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

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.rs runs a command and its rewrite under bash with recording stubs ahead of everything on PATH, 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 hi was rewritten to D='# 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, so shellcheck disable=SC2034' was read as the command. D="x y"; echo hi and D='no trailing space' fail the same way.

  • The prefix is read by words with quote state, in one split_env_prefix. A quoted value is one word, and D='# shellcheck …' is left as written.
  • An assignment is bash's own: a name of letters, digits and _ not starting with a digit, then = or +=, in any case. foo=bar git status is now rewritten as foo=bar rtk git status, and 1a=b, foo-bar=x and "foo"=x stay commands.
  • A value holding an array, a substitution, a backtick, an expansion or an unclosed quote has no certain end, so the scanner does not guess. For the uppercase = names the old pattern knew, the word ends at its first blank as before: RUST_LOG=${LEVEL} cargo test is still rewritten. For the names this change adds, a=(git diff --stat) is not an assignment and the line is left alone.
  • RTK_DISABLED= and RTK_DISABLED+= are read as assignment words, so MSG='use RTK_DISABLED=1'; git status disables 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 gain and rtk discover read the prefix the same way, gain one command at a time as the rewrite does, and a newline or carriage return ends an assignment like a blank.
  • The reader of a quoted script (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.
  • The permission gate reads the command behind each assignment through split_env_word: MSG="chore: rm -rf build dir" && git commit -m "$MSG" is no longer denied by Bash(rm -rf *).
  • A line holding a continuation is also checked as bash joins it and as the rewrite joins it. A deny there leaves the line unrewritten, and so does an ask the line as written does not already show, so the host decides on it.
  • sudo is 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-fast on this branch: 5847 passed, 0 failed
  • Each rule above has a test that fails when the rule is removed
  • rtk rewrite of 31,933 generated lines (prefix shapes of RTK_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 with RTK_DISABLED set 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 it
  • The deny-rule probe (curl *) gives the same verdict as develop on every row
  • Each line and its rewrite run under bash in a container with stub git and cargo that log whether RTK_DISABLED reached them

Fixes #3262

🤖 Generated with Claude Code

@rtk-wshm-sync-bot

Copy link
Copy Markdown

wshm · Automated triage by AI

📊 Automated PR Analysis

🐛 Type bug-fix
🟡 Risk medium

Summary

Replaces 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 D='# shellcheck disable=SC2034'. It also adds a bash-driven exec-trace oracle test suite that compares what actually runs (programs, args, cwd) between the original command and its rewrite rather than comparing against hand-written textual expectations.

Review Checklist

  • Tests present
  • Breaking change
  • Docs updated

Linked issues: #3262


Analyzed automatically by wshm · This is an automated analysis, not a human review.

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_ENV file that defines git()

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).

@KuSh

KuSh commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Thank you for the review, both blockers reproduced here and are fixed in the amended commit (test(discover): let bash decide whether a rewrite changed what runs, …).

1. False RTK_DISABLED detection: prefix_contains_rtk_disabled is now a check on the words of the prefix (with skip_blanks / word_end_from): one of them has to start with RTK_DISABLED=. The three places that tested the prefix with contains (the rewrite, and the two shell-wrapper readers) go through it, so rtk rewrite, rtk gain and rtk discover agree. MSG='use RTK_DISABLED=1'; git status rewrites with no warning, and NOT_RTK_DISABLED=1 git status is no longer taken for the variable. New tests cover the predicate (quoted, escaped and unquoted values), the gain and discover readers, the rewrite's stderr, and both wrapper readers (bash -c "MSG='use RTK_DISABLED=1'; git status", uv run bash -c '…', shell_wrapper_positions); each fails when its call site goes back to contains.

One shape is left: a bash -c "…" script that carries the data in escaped double quotes (MSG=\"use RTK_DISABLED=1\") is read from its raw text and is not rewritten. That is #5175.

2. The oracle's environment: all three bash invocations go through common::native_command, and trace runs in the oracle's own directory. With BASH_FUNC_git%% exported the previous oracle failed and this one passes; with a BASH_ENV file defining git() it passes too.

Also rebased onto develop.

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@KuSh
KuSh force-pushed the test/discover-exec-oracle branch from 5ab5ccc to c9eb6d6 Compare November 21, 2026 09:57
@KuSh

KuSh commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, both reproduce on a develop build, and both are fixed in the first commit.

  • RTK_DISABLED=1; git status, RTK_DISABLED=1 && git status, FOO=1 RTK_DISABLED=1; git status and RTK_DISABLED=1 alone no longer warn. An assignment with no command after it only sets a shell variable, so a line that is nothing but assignments has no prefix and the command behind the ; is rewritten as it is on develop. The tests cover the statement form and run rtk rewrite to check stderr.
  • RTK_DISABLED+=1 git status is read like RTK_DISABLED=1 git status: skipped, as on develop.

Your two findings had the same shape: the prefix reader got wider (by words, lowercase names, +=, an assignment that is a whole statement), and each place that reads a prefix inherited it. So I went through the other readers and found the same shape in four more, now fixed with a test each:

  • uv run bash -c 'RTK_DISABLED=1; echo hi' stopped being routed, because the reader of a quoted script took the bare assignment as an opt-out. Develop routes it.
  • rtk gain counted a bare RTK_DISABLED=1 as a bypass, and a newline inside an unquoted word no longer ended an assignment, so X=1\nRTK_DISABLED=1 git status was missed. Newline and carriage return now end a word like a blank, and gain reads each command of a line, as the rewrite does (so a && RTK_DISABLED=1 git x now counts, and RTK_DISABLED=1; git x no longer does).
  • rtk discover read RTK_DISABLED= only, so a += line was reported as a missed saving.
  • An array, a substitution, a backtick or an expansion in a value holds blanks in ways that reading them is the lexer's job, so the scanner does not guess where such a word ends. For the names develop's pattern knew (uppercase, =) it ends at the first blank, as before, so a line develop rewrote is still rewritten (RUST_LOG=${LEVEL} cargo test). For a name this change adds, a=(git diff --stat) is not an assignment and the rewrite leaves the line alone rather than edit inside it.

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 RTK_DISABLED=, +=, lowercase, quoted and escaped values, arrays, expansions, env, wrappers, separators, three permission configs), and ran each line and its rewrite under bash in a container with stub git/cargo that log whether RTK_DISABLED reached them. No invocation that bash ran with RTK_DISABLED set is rewritten, and every line where this branch rewrites less than develop is either the quoted-assignment case #3262 is about, an escaped blank in a value (X=a\ git status runs status), or an assignment with nothing behind it. The grids cover rtk rewrite; gain, discover and the gate's reading are covered by unit tests.

Left as on develop, in case they are worth separate issues: a subshell or brace group (( RTK_DISABLED=1 git status )) skips the rewrite without the warning, V=$(env RTK_DISABLED=1 foo) bar reads the substitution's contents as a prefix, and an assignment followed by a redirect still counts as a prefix. I did not touch the hook swap's own assignment reader (is_assignment in claude_pipeline.rs), which accepts names starting with a digit and rejects +=.

KuSh and others added 2 commits November 21, 2026 11:08
…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]>

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Adrien EPPLING and others added 2 commits November 28, 2026 14:37
…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]>
@KuSh

KuSh commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for fef933b2. I pushed 495c0642 on top of it.

The joined readings were checked against the deny rules only, so the same split got past an ask rule: with ask git push:* and allow *, D=1 \⏎a1=x git push origin main was rewritten and auto-allowed. An ask found only on a joined line now returns Defer, and so does a deny inside a shell wrapper that only a joined line shows.

One borderline case remains. With deny git push:* and ask git commit:*:

Line develop 495c0642
git commit -m x && D=1 \⏎a1=x git push 3 1
git commit -m x && D=1 a1=x git push 3 2

On the split line, the deny found on the joined reading returns Defer, which takes precedence over the ask raised by git commit. An integration that runs the line unchanged on exit 1, such as OpenClaw, then no longer prompts.

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]>
@aeppling

Copy link
Copy Markdown
Contributor

Agreed, pushed c50f11ea: a deny on either joined reading now returns Deny (Defer inside a shell wrapper, as before). Claude Code without a hook also denies the whole line, so it sees no change. On OpenClaw, the 119 generated continuation lines that ran a denied push with no block and no prompt on 8ea7808b are now blocked.

The hint sounds right for hosts where RTK blocks the call itself. I'd keep it for a separate PR.

@aeppling
aeppling merged commit 1c6fe07 into rtk-ai:develop Nov 29, 2026
16 checks passed
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Nov 29, 2026
@KuSh
KuSh deleted the test/discover-exec-oracle branch December 1, 2026 07:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(hook): rewrite edits inside quoted string literals — 'shellcheck' in a single-quoted sed replacement became 'rtk shellcheck' (data corruption)

2 participants