Skip to content

feat(shell)!: explicit shell execution, fish-aware hook gate, and fish -c wrapper rewriting - #3911

Closed
pashifika wants to merge 13 commits into
rtk-ai:developfrom
pashifika:feat/multiline-fish-control-flow-rewrite
Closed

pashifika wants to merge 13 commits into
rtk-ai:developfrom
pashifika:feat/multiline-fish-control-flow-rewrite

Conversation

@pashifika

Copy link
Copy Markdown
Contributor

Summary

Stacked on #3828. That PR's commit is the first in this branch, so the diff below still contains it — merge #3828 first and this one reduces to the shell-boundary work it deliberately left out. Thanks @SindriFr for rebasing the wrapper half of #3057; this is the rest of that work, rebased onto your branch. #3057 is closed in favour of this pair.

Four related changes, in commit order:

1. fix(cli)!: preserve argv boundaries in generic runners

rtk run, rtk err, rtk test and rtk summary rebuilt their positional arguments into one string and executed it through sh -c (cmd /C on Windows). Argument boundaries were lost and globs, variables and operators were expanded by a shell the caller never asked for.

rtk run printf '[%s]\n' 'a b' '*' '$HOME'
# [a b]
# [*]
# [$HOME]

Positional forms now execute the program directly. An intentional script is explicit: rtk run -c '<script>' (platform default, sh / cmd), rtk run --shell <name> -c '<script>', or rtk err|test|summary --shell <name> '<script>'. PowerShell and pwsh get -Command, other named shells -c. Explicit shell mode requires the whole script as one argument, so RTK never reconstructs quoting after Clap has already split argv.

2. fix(hooks): defer ambiguous shell constructs

The shared lexer now reports as unattestable: bare (…) substitution, a control keyword at a command boundary (and, or, not, begin, end, if, else, switch, case, for, while, function), and incomplete quoting or a trailing escape. Detection is command-position aware, so an ordinary argument (rg and src) stays attestable. Unattestable commands are neither rewritten nor auto-allowed — with a * allow rule they resolve to Ask, never Allow.

3. feat(rewrite): accept quoted fish -c wrappers

#3828 excluded fish from the wrapper subset because the shared lexer could not attest fish's control keywords. Change 2 supplies exactly that guarantee, and rewrite_shell_wrapper runs the gate on the inner script:

fish -c 'git status; cargo test'      → fish -c 'rtk git status; rtk cargo test'
fish -c 'git status; and cargo test'  → unchanged
fish -c 'git status (pwd)'            → unchanged
fish -c 'if test -d src; git status; end'  → unchanged

That is the fish half of #2767; together with #3828 the issue is fully covered.

4. Fish-script wrapping at the unattestable gate

A host can evaluate the Bash-tool command string with a POSIX/zsh layer while the user's shell is fish, so a fish script fails to parse before RTK ever runs. A command that is provably fish — a fish-only keyword (end, begin, switch, and, or, not) at command position with no POSIX disambiguator (then, fi, do, done, esac, elif, [[, heredoc) — is handed back as one quoted argument every host layer parses as a single command:

if test -d src
  git status
end
# → rtk run --shell fish -c 'if test -d src\n  git status\nend'
  • Always Ask, never auto-allowed: the script's content is unattestable by definition.
  • Skipped when the command already delegates (rtk …, or an explicit -c wrapper), when the script contains \\ or \' — the only two sequences where fish single-quote semantics diverge from POSIX, so every wrapped script round-trips byte-identically under sh/bash/zsh and fish — on Windows, without a resolvable fish binary, or with hooks.wrap_fish_scripts = false.
  • The pure checks (platform, delegation, classification, backslash veto) run before the config read and the fish PATH probe, so non-fish commands reaching the gate (echo $(date), POSIX blocks) do zero I/O in the hook hot path.
  • Ambiguous scripts (shared if/for without a fish-only marker, POSIX forms, heredocs) keep the previous defer behaviour.

Breaking change

Callers that relied on implicit shell expansion in positional arguments must state the shell:

rtk test cargo test                              # unchanged, direct argv
rtk test --shell sh 'cargo test && cargo clippy' # was: implicit sh -c
rtk run -c 'ls *.rs | wc -l'                     # was: rtk run ls *.rs | wc -l

sudo behaviour is inherited from #3828 unchanged: sudo bash -c '…' passes through, because the inner rtk would run as root where it is off secure_path (#146/#3569).

Key files

File Purpose
src/core/shell.rs Direct-argv and explicit-shell command construction, per-shell flag selection, script-boundary validation
src/main.rs --shell surface on run/err/test/summary; positional forms route to direct execution
src/discover/lexer.rs Parenthesized syntax, command-position control keywords and incomplete quoting → unattestable
src/discover/shell_wrapper.rs fish rejoins the conservative quoted -c wrapper subset
src/discover/fish_script.rs Fish classification, divergent-backslash veto, wrap assembly, gate ordering
src/core/config.rs hooks.wrap_fish_scripts (defaults to enabled)
src/hooks/rewrite_cmd.rs, src/hooks/hook_cmd.rs Wrap at the unattestable gate for every host; always Ask, wrapper injected so tests do not depend on the local fish binary or user config
tests/run_shell_test.rs argv preservation, exit codes, default and explicit shells, missing shell, split-script rejection
tests/fish_wrap_test.rs E2E wrap, opt-out, backslash veto, cross-host quoting round-trip, real-fish execution (#[ignore])
tests/rewrite_shell_wrapper_test.rs fish portable rewrite and fish-specific passthrough

Test plan

  • cargo fmt --all --check — clean
  • cargo clippy --all-targets -- -D warnings — clean
  • cargo test --all — 3,313 passed, 0 failed, 9 ignored
  • cargo test --all -- --ignored — 9 passed (includes real fish execution)
  • rtk rewrite end-to-end, isolated HOME/XDG_CONFIG_HOME:
    • bash -c "head foo && grep -R bar ." → bash -c "rtk read foo && rtk grep -R bar ." (exit 3)
    • fish -c 'git status; cargo test' → fish -c 'rtk git status; rtk cargo test' (exit 3)
    • fish -c 'git status; and cargo test' → passthrough (exit 1)
    • multi-line if … end block → rtk run --shell fish -c '…' (exit 3, no auto-allow)
  • rtk run end-to-end: explicit fish executes fish-only syntax, argv boundaries survive ('a b', *, $HOME unexpanded), -c keeps the POSIX default, exit code 7 propagates, --shell fish echo ok is rejected instead of re-joined
  • CI to validate Linux and Windows (cmd /C, PowerShell flag selection, wrapper parsing)

Tested on macOS 26.6.2 arm64 (M1 Pro), rustc 1.97.1, fish 4.9.0.

pashifika and others added 13 commits September 7, 2026 09:59
An agent that reaches a project toolchain through a wrapper writes every
command as `direnv exec . bash -c '...'` or `devenv shell -- bash -c '...'`.
The script is one quoted argument, so the whole invocation was opaque and no
inner command was ever rewritten.

Parse the conservative subset of quoted `-c` wrappers and rewrite the script
in place, replacing only its byte span. The shell path, quote delimiters,
horizontal spacing, suffix arguments and fd redirects stay byte-identical.
Recursion is capped at one level, so a wrapper inside a wrapper stays raw.

A wrapper is reached at any prefix depth, so one sitting behind a transparent
prefix or a strippable `command` is still seen. A leading `sudo` keeps the
passthrough it has for bare commands: the inner `rtk` would run as root,
where it is off secure_path (rtk-ai#146).

Deferred unchanged: a script with a newline, heredoc, `$((`, active outer `$`
expansion, or any construct the shared lexer cannot attest; extra shell
options (`-lc`, `-e -c`); an unquoted or unbalanced script; and `fish`, whose
control keywords (`and`, `or`, `if`) at a command boundary need a fish-aware
lexer this does not model.

Permissions are evaluated on both sides of the new boundary: deny rules run
against the parsed inner segments, an inner deny outranks an outer allow, and
a wrapper rewrite is never auto-allowed — its strongest verdict is Ask, so a
`*` allow rule cannot approve a script the host never parsed.

Closes rtk-ai#2767

Co-authored-by: pashifika <[email protected]>
Execute positional run, err, test, and summary commands directly instead of reconstructing them for sh -c. Add explicit shell selection for command strings while retaining the platform defaults for run -c.

BREAKING CHANGE: positional arguments for run, err, test, and summary no longer receive implicit shell expansion; use -c or --shell with one quoted script when shell syntax is required.
Treat bare parentheses, command-position control keywords, and incomplete quoting as unattestable so hooks neither rewrite nor auto-allow commands whose shell semantics are uncertain.
Classify command strings as unambiguously fish via fish-only markers
(end/begin/switch/and/or/not at command position) vetoed by POSIX-only
constructs (then/fi/do/done/esac/elif, [[, heredocs, incomplete quoting,
NUL). Wrap classified scripts as rtk run --shell fish -c '<script>' with
portable single-quote escaping so POSIX and fish host layers both parse
the result. Gated on fish availability, non-Windows, and not already
delegating (rtk prefix or explicit shell -c wrapper).

Co-Authored-By: Claude Fable 5 <[email protected]>
Opt-out knob (default true) for the fish-script wrap in the hook rewrite
paths. Missing key keeps wrapping enabled so older configs are unaffected;
fish_script::try_wrap loads the flag before applying its other gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
At the unattestable gate in both decision paths (native hook hosts via
decide_from_verdict, legacy sh hook via rtk rewrite), unambiguously-fish
scripts now rewrite to rtk run --shell fish -c '<script>' instead of
deferring — the POSIX host layer parses one command with one quoted
argument, and fish executes the script. Wrapped rewrites always surface
as Ask (exit 3 / updatedInput without permissionDecision): the script
content is unattestable, so it is never auto-allowed even when an allow
rule matches the raw string. Deny still short-circuits first. Injection
seams (decide_from_verdict_with / evaluate_with) keep the tests
deterministic regardless of local fish or config state.

Co-Authored-By: Claude Fable 5 <[email protected]>
End-to-end rtk rewrite runs with an isolated home (config and Claude
settings can't leak into verdicts): multiline fish blocks wrap as Ask
(exit 3), wrap_fish_scripts=false and POSIX scripts defer (exit 1).
Cross-shell round-trip asserts the single-quote idiom delivers the
script byte-identical through sh/zsh/fish host layers, and an ignored
test executes a wrapped block through real fish, comparing output with
direct execution and checking exit-code propagation. Startup timing
recorded in the change work dir: wrap path ~5.5ms, no regression.

Co-Authored-By: Claude Fable 5 <[email protected]>
README auto-rewrite section, hooks permission-model README, French
FEATURES guide (behavior, gates, wrap_fish_scripts opt-out and config
sample), and the Codex awareness template (hook-enabled hosts wrap
automatically; Codex has no hook, keep wrapping manually).

Co-Authored-By: Claude Fable 5 <[email protected]>
Review-cycle round 1 fixes (reviewed by an independent worker, fixes
authored by a separate fixer, resolution confirmed by the non-author
reviewer):

- Refuse to wrap scripts containing \\ or \' — the only two sequences
  where fish single-quote semantics diverge from POSIX — so every
  wrapped script round-trips byte-identically under sh/bash/zsh AND
  fish host layers. Lone backslashes (e.g. printf '%s\n') still wrap.
- Run the pure checks (platform, delegation skip, classification,
  backslash veto) before the config read and the fish PATH probe, so
  non-fish unattestable commands (echo $(date), POSIX blocks) do zero
  I/O in the hook decision path; try_wrap_gated is now test-only.
- Extend coverage: unit tests for the veto and the lone-backslash wrap,
  a backslash payload in the cross-host round-trip test, and an E2E
  defer test for divergent-backslash scripts.

Co-Authored-By: Claude Fable 5 <[email protected]>
… code

search-strategy.md: expand discover/ into its real modules (lexer,
registry, rules, shell_wrapper, fish_script, provider, report), add
core/shell.rs and hooks/permissions.rs, and correct hook_cmd.rs to the
native multi-host processor it is. cli-testing.md: replace the stale
tests/common + integration_test.rs layout with the per-area
<area>_test.rs suites actually in tests/. TECHNICAL.md: the
unattestable-gate description now records the fish-script wrap
carve-out (unambiguously-fish scripts rewrite to rtk run --shell fish,
Ask-only) instead of claiming every gated command returns unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
rtk-ai#3828 left `fish` out of the wrapper subset because the shared lexer could
not attest fish's control keywords, so the semantics of a fish script were
unknown at the rewrite boundary. The lexer in this stack reports both bare
`(…)` substitution and a control keyword (`and`, `or`, `if`, `end`, …) at a
command boundary as unattestable, which is the guarantee that was missing:
`rewrite_shell_wrapper` runs that gate on the inner script, so a fish script
carrying control flow defers unchanged and only a portable script is
rewritten.

    fish -c 'git status; cargo test'
      → fish -c 'rtk git status; rtk cargo test'
    fish -c 'git status; and cargo test'    unchanged
    fish -c 'git status (pwd)'              unchanged

This also restores `fish -c` as an explicit wrapper for
`is_shell_wrapper_candidate`, so `fish_script.rs` never wraps an
already-delegating command a second time.

Refs rtk-ai#2767

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Round 1 of 3 — CHANGES REQUESTED

Claim: four related changes — argv-boundary preservation in rtk run|err|test|summary, a wider unattestable-construct gate, fish -c wrapper rewriting, and automatic wrapping of bare fish scripts at the hook gate.

Scope: accept if narrowed to "rewrite the inner commands of a quoted fish -c '…' wrapper, deferring on fish control flow and bare (…) inside that wrapper's script" — change 3 plus the fish-scoped half of change 2. Changes 1 and 4 are separate subjects and each needs its own PR. (round 1, frozen)

Ran: merge-base 5e10aa64 vs head 9f7d7cb, release-built with one CARGO_TARGET_DIR each (md5 856185ac… / 59d29249…, confirmed distinct). rtk rewrite over a 494-line command corpus harvested from this repo's own docs plus a 30-case hand matrix; rtk run|err|test|summary argv and exit codes before/after; the wrapped-script round-trip under real bash, zsh and fish in debian:sid; cargo test --all on the head (3193 passed, 0 failed, 8 ignored) and on a locally narrowed variant. The diff adds no filter, so the 20% savings floor (CONTRIBUTING.md) does not apply to it directly — it applies to what the diff forfeits, see blocker 1.

CI @9f7d7cb: never run. gh pr checks has only license/cla (pass) and a skipped check-target; actions/runs?event=pull_request&branch=feat/multiline-fish-control-flow-rewrite returns zero runs, where sibling fork PRs at least carry an action_required CI run. The PR is also CONFLICTING against develop (src/main.rs, src/hooks/hook_cmd.rs, src/hooks/rewrite_cmd.rs, src/discover/registry.rs, src/core/config.rs, src/hooks/README.md, hooks/codex/rtk-awareness.md). Approval is unavailable on this head regardless of the findings below.


Blocks merge (3, frozen at round 1)

1. src/discover/lexer.rs — the (…) / control-keyword deferral is global, so it stops RTK rewriting ordinary bash.

contains_unattestable_construct is not only the permission gate: it is the first thing rewrite_cmd.rs:84, hook_cmd.rs:273, permissions.rs:89 and discover/mod.rs:189 consult, and a true means no rewrite at all, not merely "no auto-allow". Adding bare (/) to it therefore removes the rewrite from every bash command that contains an unquoted subshell — including the parts of the line that are nowhere near the parens.

$ rtk rewrite 'git log -20 && (cd www && npm test)'
merge-base 5e10aa64:  rtk git log -20 && (cd www && npm test)     (exit 3)
head       9f7d7cb :  <nothing>                                    (exit 1)

$ rtk rewrite '(cd sub && git status)'
merge-base:  (cd sub && rtk git status)                            (exit 3)
head      :  <nothing>                                             (exit 1)

$ rtk rewrite $'git status\n(cd www && npm test)'
merge-base:  rtk git status\n(cd www && npm test)                  (exit 3)
head      :  <nothing>                                             (exit 1)

The control-keyword half costs the same, and not only on fish-shaped lines — if, for,
while, case, else and function are bash keywords too, so a bash line that contains a
block stops being rewritten even where the rewritable command sits outside it:

$ rtk rewrite 'git status; if true; then echo x; fi'
merge-base:  rtk git status; if true; then echo x; fi          (exit 3)
head      :  <nothing>                                          (exit 1)

$ rtk rewrite 'cargo build; for f in *.rs; do echo $f; done'
merge-base:  rtk cargo build; for f in *.rs; do echo $f; done   (exit 3)
head      :  <nothing>                                          (exit 1)

rtk git log -20 is 65.9% of bash output on this repo (14987 → 5116 bytes); the head forfeits all of it because the other half of the line has parens. (cd dir && cmd) is not an exotic form, and this is the exact failure mode of #1252 (P1-critical, "all RTK savings are lost for the wrapped invocation") — the PR extends it to a new construct rather than reducing it. It also silently flips permissions.rs's test_legitimate_subshell_allow into test_subshell_requires_confirmation; that rename is the change asking to be noticed.

Class: every call site of contains_unattestable_construct. Three of the four (rewrite_cmd, hook_cmd/decision, permissions, discover/mod) run on the host's command string, which RTK lexes as bash on purpose — is_word_boundary_whitespace is bash's $IFS, advance_quote_state mirrors bash, NewlineMode::Bash is named for it. Only the fourth, registry.rs:1336, runs on the inner script of a sh|bash|zsh|fish -c wrapper, and only when that wrapper is fish is (cmd) substitution and and/or/end control flow. Teaching the shared bash lexer fish's grammar makes it correct for neither.

Fix, and the reason this is a scope verdict rather than a request to revert: scope the new rules to fish context. I built it here to be sure it is small and that it costs the fish half nothing — ShellWrapper gains the matched shell (it currently discards it, supported_shell_end returns only an offset), contains_unattestable_construct_in(cmd, ShellDialect) takes the dialect, rewrite_shell_wrapper passes wrapper.dialect(), and the three host-string call sites keep bash rules. 38 lines across lexer.rs, shell_wrapper.rs, registry.rs:

                                          merge-base   head      fish-scoped
fish -c 'git status; cargo test'          —            rewrite   rewrite      ✅ change 3 intact
fish -c 'git status; and cargo test'      —            defer     defer        ✅
fish -c 'git status (pwd)'                —            defer     defer        ✅
fish -c 'if test -d src; git status; end' —            defer     defer        ✅
bash -c 'git status; cargo test'          —            rewrite   rewrite      ✅ (#3828 intact)
(cd sub && git status)                    rewrite      —         rewrite      ✅ regression gone
git log -20 && (cd www && npm test)       rewrite      —         rewrite      ✅
git status\n(cd www && npm test)          rewrite      —         rewrite      ✅
git status; if true; then echo x; fi      rewrite      —         rewrite      ✅
cargo build; for f in *.rs; do … done    rewrite      —         rewrite      ✅

cargo test --all on that variant fails exactly 10 tests, and which 10 is the interesting part: 3 lexer tests and 2 permission tests that pin the global rule, and 5 hook tests belonging to change 4. Change 3 needs none of them. That is the measurement behind the split below: change 2's global reach exists to serve change 4, not change 3.

has_unclosed_quote_or_escape is the one part of change 2 that is genuinely shell-agnostic — an unterminated quote is unattestable in any grammar — and it should stay global, once blocker 2 below is fixed. Note it also closes the $'\'' auto-allow hole (rtk rewrite "ls -la \$'\\'' ; rm -rf …": merge-base rewrites and would auto-allow under Bash(ls:*), head defers). I have an unmerged branch closing that same hole through ansi_c_quote_defeats_lexer; whichever lands first, I will rebase mine — don't hold this PR for it.

2. src/discover/lexer.rs:365 — has_unclosed_quote_or_escape is comment-blind, so a trailing # comment poisons the whole command.

The lexer has never modelled # comments (there is no '#' anywhere in lexer.rs), which cost nothing until something scanned the raw string end to end. Now an apostrophe or a paren in a comment reads as shell syntax:

$ rtk rewrite "ls -la # don't"
merge-base:  rtk ls -la # don't          (exit 3)
head      :  <nothing>                    (exit 1)

$ rtk rewrite "cargo build # check (fast)"
merge-base:  rtk cargo build # check (fast)   (exit 3)
head      :  <nothing>                         (exit 1)

Silent loss of the rewrite and a permanent Ask on a perfectly valid bash line. This one is independent of the fish scoping — my narrowed variant above does not fix it, because has_unclosed_quote_or_escape stays global there (correctly: an unterminated quote is unattestable in any grammar). The fix is to stop the scan at a # that begins an unquoted word and resume at the newline; I prototyped it (12 lines, in the patch linked below) and it restores all three cases while the real guards still fire — git status 'unfinished and git status \ keep deferring, where the merge-base wrongly rewrote both. It adds zero test failures: nothing in the PR pins the comment-blind behaviour.

3. src/cmds/rust/runner.rs:11, src/main.rs:2052/:2057/:2756 — the argv switch drops exit 127 and the [FAIL] contract when the program can't be resolved.

$ rtk err nosuchcmd123
merge-base:  [FAIL] Command failed (exit code: 127)
             sh: 1: nosuchcmd123: not found          exit 127
head      :  rtk: Failed to run err command: Failed to run err: Failed to spawn
             process: No such file or directory (os error 2)      exit 1

Same for rtk test, rtk summary and rtk run (127 → 1). 127 is the POSIX "command not found" code; CI steps and anything parsing RTK's [FAIL] line key on it, and the head replaces both with a raw anyhow chain on stderr. This is a regression against the merge-base and it belongs to PR A, not to the fish work — resolve the program with resolve_binary and, on failure, take the existing not-found path rather than bailing out of run_err/run_test/summary::run.

It also hits the form the shipped awareness body still teaches: rtk err "npm run build" runs on the merge-base and fails with Binary 'npm run build' not found on PATH on the head, while src/hooks/init.rs:237/:288/:293 (RTK_SLIM, installed as RTK.md for Claude and Gemini) still document rtk err <cmd> with no argv or --shell note. Only RTK_SLIM_CODEX was updated. Whatever PR A lands as, those three lines go with it.


Why four PRs, not one

The four changes do not share a justification, and bundling them means the weakest one gates the strongest.

PR A — fix(cli)!: preserve argv boundaries in generic runners (src/core/shell.rs, main.rs, runner.rs, summary.rs, tests/run_shell_test.rs). Nothing to do with fish. It is a breaking change that deserves its own ! entry and its own review:

$ rtk run printf '[%s]\n' 'a b' '*' '$HOME'
merge-base:  [a]n[b]n[a.rs]n[b.rs]n[/home/nlecam]n     # sh -c mangles argv
head      :  [a b] / [*] / [$HOME]                      # correct
$ rtk err "ls nonexist || echo fallback"
merge-base:  runs, exit 0
head      :  Failed to spawn process, exit 1            # the break

The argv preservation itself is correct as claimed. The exit-code story is mixed: the head correctly reports failure for a command the merge-base silently ran through sh and reported as success, but blocker 3 is the other half of it and has to be fixed before this lands. The documented forms (rtk test cargo test) are unaffected and no registry rule emits rtk run|err|test, so the blast radius is direct CLI callers who passed a quoted shell string. That is reviewable in an afternoon on its own and is held up here by the fish discussion.

PR B — feat(rewrite): accept quoted fish -c wrappers (change 3 + the fish-scoped half of change 2), stacked on #3828. This is the part I want. An agent that runs fish -c 'git status' through the Bash tool has emitted a valid bash command whose argument happens to be a fish script; RTK looking inside that wrapper is exactly the feature #3828 adds for sh -c/bash -c. No agent bug involved. With blocker 1 fixed this merges as soon as #3828 does.

PR C — change 4, fish-script wrapping at the unattestable gate. Its own text states the premise: "A host can evaluate the Bash-tool command string with a POSIX/zsh layer while the user's shell is fish, so a fish script fails to parse before RTK ever runs." That is an agent putting fish syntax into a tool called Bash. Compensating for it makes RTK responsible for guessing which language a command is written in, on by default (wrap_fish_scripts = true, so every user with a fish binary anywhere on PATH gets it), and it hands the host a command that runs under a different shell than the one the string was submitted to. I am not blocking it on a defect — I looked for one and did not find it, see "Hypotheses built and dropped" — I am saying the question "should RTK infer a command's shell?" deserves a thread of its own and should not be what keeps PR A and PR B out of develop. Open it as an issue or as its own PR and I will argue it there.

PR D — optional: has_unclosed_quote_or_escape alone, with blocker 2 fixed, if you want it to land independently of the fish work. It stands on its own merits, and it is the piece that closes the $'\'' auto-allow hole.


Optional — will not hold merge; I will resolve these threads

  • The behaviour change to bash ( … ) handling is not documented anywhere in the diff, while every fish-facing change is documented thoroughly. That asymmetry is itself evidence the bash reach was not intended.
  • --shell on Run carries requires = "command" + conflicts_with = "args"; on Err/Test/Summary it carries no clap constraints at all, so rtk test --shell fish cargo test dies at runtime with pass the shell command as one quoted argument after --shell instead of a clap usage error. Same flag, two surfaces.
  • is_unambiguous_fish's POSIX veto list covers then/fi/do/done/esac/elif, [[ and heredocs, but not backticks — echo `hostname`; and echo ok classifies fish and wraps, and fish has no backtick substitution, so the wrapped form prints the literal text. It needs a fish-only marker to be present at all, so the blast radius is tiny, but "provably fish" is a stronger claim than the veto list currently earns.
  • display_args joins argv with spaces and no re-quoting, so rtk test cargo test --filter "a b" is tracked as cargo test --filter a b. Cosmetic (tracking label and TestEcosystem::detect input only).

One more thing for the fish thread, not a blocker

Adding fish to SUPPORTED_SHELLS also puts the wrapper's inner script through split_for_permissions, which is bash-shaped. With deny: ["Bash(rm:*)"]:

fish -c 'rm -rf /tmp/zz'               merge-base: passthrough   head: Deny   ← real improvement
fish -c 'true; and rm -rf /tmp/zz'     merge-base: passthrough   head: passthrough
bash -c 'true && rm -rf /tmp/zz'       merge-base: passthrough   head: Deny

Not a regression — the merge-base denied none of the wrapper forms, so every non-fish line here is a win this PR and #3828 deliver. But the deny rule silently does not apply to the one fish form the PR exists to handle, because the segment reaching command_matches_pattern is and rm -rf /tmp/zz. It is the same thesis as blocker 1 seen from the security side: the bash lexer cannot segment fish, and the fix is for the fish path to know it is fish, not for the shared lexer to learn a second grammar.

Filed as follow-ups

Nothing filed yet — the leftovers here are the split above, which belongs in PRs, not issues. If you would rather change 4 be tracked as an issue than as a PR, say so and I will open it with the evidence from this round.

Checked and correct — no need to re-verify

  • The single-quote escape and the round-trip claim. I ran the wrapped output of five classified scripts through real bash, zsh and fish in debian:sid and dumped the argv rtk receives. All three host layers deliver the script byte-identically, including the multiline if … end case and the '\'' idiom. The \\ / \' veto is the right pair to refuse, and printf '%s\n' still wraps.
  • Gate ordering in try_wrap_with_probes. The pure checks (platform, delegation, classification, backslash veto) genuinely precede the config read and the fish PATH probe; both probes are FnOnce and are reached only on the fish path.
  • Never auto-allowed. Mutating RewriteOutcome::Ask(wrapped) → Allow(wrapped) in rewrite_cmd.rs:89 fails test_fish_script_rewrites_to_ask_wrap and nothing else; hook_cmd.rs has its own equivalent test. The claim is real and pinned.
  • Quoted parens are safe. rtk grep -E '(foo|bar)' src and echo '(printf x)' are unaffected by the new rule on both binaries.
  • fish in SUPPORTED_SHELLS stays conservative. fish -lc, fish --command, and fish -c followed by a non-space all return None; env FOO=1 fish -c '…' and a trailing --foo are handled.
  • Direction of the fish/bash single-quote divergence in the wrapper path is fail-safe. Bash's lexer closes a '…\' span earlier than fish does, so it can only produce more segments, never fewer — the dangerous direction (fish running two commands where the lexer saw one) is not reachable.

Hypotheses built and dropped

  • "Change 4 will mis-classify real bash as fish." I ran 494 real command lines harvested from this repo's docs through the head binary with a fish on PATH: 0 were wrapped. The classifier is precise in practice. not grep -q pat file does wrap, and bash would have failed on it — but I am not going to call a command nobody writes a regression. My objection to change 4 is about responsibility, not about a bug.
  • "The fish \' divergence lets fish -c '…' rewriting corrupt a quoted string." Not reachable: a single-quoted wrapper cannot contain a ' at the host layer, and the double-quoted wrapper path rejects an active \ escape. Dropped.
  • "has_unclosed_quote_or_escape will false-defer on apostrophes inside double quotes." It handles nested quotes correctly — git commit -m "don't crash" is unaffected on both binaries. Apostrophes in an unquoted comment are a different matter and did survive as blocker 2; the 494-line corpus happened to contain no commented commands, which is a reminder that a corpus proves presence, not absence.
  • "Some host entry point misses the wrap." Every host routes through decide_from_verdict / evaluate_with_verdict; both got it.
  • "The duplicated gate in rewrite_cmd.rs and hook_cmd.rs is this PR's doing." It predates the PR — and develop has since collapsed it (see rebase note).
  • "The conservative \r handling will cost rewrites." The opposite: rtk rewrite $'git status\rand echo ok' on the merge-base emits rtk git statusand echo ok — the \r is swallowed and two commands are welded into one word. The head defers instead. That is a pre-existing corruption this PR happens to sidestep; keep it whichever way the split goes.

Your questions

  • "[ ] CI to validate Linux and Windows (cmd /C, PowerShell flag selection, wrapper parsing)" → Still open, and not your fault: no CI workflow run has ever been created for this branch. Resolving the conflict should let the pull_request workflow be created; I will approve the run as soon as there is one. Until then, neither of us has a Windows signal, and cmd /C + -Command flag selection is the part of change 1 I most want CI to see.

Prototypes from this round

Both are local only — nothing is pushed. Together (ShellDialect, ShellWrapper::dialect, comment-aware quote scan) they are 50 lines across lexer.rs, shell_wrapper.rs and registry.rs, and with them the only remaining cargo test --all failures are the 10 tests that pin the global rule and change 4. Say the word and I will attach the patch or push it as a fixup to whichever PR ends up owning it.

Next

Split it. In order: (A) the argv/--shell change on its own, with blocker 3 fixed — that one is closest to landing and is held up here by a fish discussion it has nothing to do with. (B) fish -c wrapper rewriting on top of #3828, with the (…)/keyword deferral scoped to the wrapper's own script as shown above. (C) fish-script wrapping at the gate, separately, where we can argue the premise without holding A and B. Rebase B and C onto current develop when you get there: d6ce8f71 has already merged HookDecision and RewriteOutcome into one src/hooks/decision.rs, so the two copies of the wrap-at-gate collapse to a single site at decision.rs:86, and d00c514e + ad631395 (let-chains, rustfmt style edition 2024) mean a reformat is part of the rebase either way.

Rounds: 1/3. Threads: 0 open, 0 resolved this round.

Comment thread src/discover/lexer.rs
let tokens = tokenize_inner(cmd, NewlineMode::Conservative);
if tokens
.iter()
.any(|token| token.kind == TokenKind::Shellism && matches!(token.value.as_str(), "(" | ")"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocks merge 1 — the (/) rule is global, so it stops RTK rewriting ordinary bash.

contains_unattestable_construct is consulted by rewrite_cmd.rs:84, hook_cmd.rs:273, permissions.rs:89 and discover/mod.rs:189 before registry::rewrite_command, so true means no rewrite at all — not merely no auto-allow. Measured against the merge-base 5e10aa64:

$ rtk rewrite 'git log -20 && (cd www && npm test)'
merge-base:  rtk git log -20 && (cd www && npm test)     (exit 3)
head      :  <nothing>                                    (exit 1)

$ rtk rewrite '(cd sub && git status)'
merge-base:  (cd sub && rtk git status)                   (exit 3)
head      :  <nothing>                                    (exit 1)

The keyword list on the next line costs the same, and if/for/while/case/else/function are bash keywords too:

$ rtk rewrite 'git status; if true; then echo x; fi'
merge-base:  rtk git status; if true; then echo x; fi     (exit 3)
head      :  <nothing>                                    (exit 1)

(cmd) is fish substitution and and/or/end are fish control flow only inside a fish -c '…' script — which registry.rs:1336 already checks separately. Scoping both rules to that call site keeps every fish deferral in this PR and restores every bash rewrite above; see the review body for the three-way transcript and the 38-line shape of the change.

Comment thread src/discover/lexer.rs
.any(|(i, tok)| tok.kind == TokenKind::Redirect && redirect_has_file_target(&tokens, i))
}

pub(crate) fn has_unclosed_quote_or_escape(cmd: &str) -> bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocks merge 2 — this scan is #-comment blind, so a trailing comment poisons the whole command.

lexer.rs has never modelled # comments (there is no '#' anywhere in the file), which cost nothing until something scanned the raw string end to end. Now an apostrophe or a paren inside a comment reads as shell syntax:

$ rtk rewrite "ls -la # don't"
merge-base:  rtk ls -la # don't               (exit 3)
head      :  <nothing>                         (exit 1)

$ rtk rewrite "cargo build # check (fast)"
merge-base:  rtk cargo build # check (fast)   (exit 3)
head      :  <nothing>                         (exit 1)

Silent loss of the rewrite plus a permanent Ask on valid bash. Stop the scan at a # that begins an unquoted word and resume at the newline — I prototyped exactly that (12 lines): it restores all three cases, the real guards still fire (git status 'unfinished and git status \ keep deferring, where the merge-base wrongly rewrote both), and it adds zero test failures. Independent of the fish scoping in blocker 1; this part of the check is right to be global, it just needs to know where shell syntax ends.

Comment thread src/cmds/rust/runner.rs
///
/// Arguments execute directly, preserving every boundary Clap parsed. With
/// `shell`, the single supplied script runs through that shell instead.
pub fn run_err(command: &[String], shell: Option<&str>, verbose: u8) -> Result<i32> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocks merge 3 — the argv switch drops exit 127 and the [FAIL] contract.

$ rtk err nosuchcmd123
merge-base:  [FAIL] Command failed (exit code: 127)
             sh: 1: nosuchcmd123: not found                    exit 127
head      :  rtk: Failed to run err command: Failed to run err:
             Failed to spawn process: No such file... (os error 2)   exit 1

Same for run_test below, summary::run, and rtk run (127 → 1). 127 is the POSIX "command not found" code, and anything parsing RTK's [FAIL] line loses it too; both are replaced by a raw anyhow chain on stderr. Resolve the program with resolve_binary and, on failure, take the existing not-found path rather than bailing out of run_err/run_test/summary::run.

It also hits the form the shipped awareness body still teaches — rtk err "npm run build" runs on the merge-base and fails with Binary 'npm run build' not found on PATH here — while src/hooks/init.rs:237/:288/:293 (RTK_SLIM, installed as RTK.md for Claude and Gemini) still document rtk err <cmd> with no argv or --shell note. Only RTK_SLIM_CODEX was updated.

@pashifika

Copy link
Copy Markdown
Contributor Author

@KuSh — split, rebased onto develop @ 0924356, and all three blockers addressed. Closing this in favour of:

PR Contents
A #4125 fix(cli)!: preserve argv boundaries in generic runners — no fish, base develop
B #4126 fish -c wrapper rewriting, scoped as you proposed; carries #3828's commit rebased
C #4127 fish-script wrapping at the hook gate, with the premise argued in the body

Blocker 1 — fixed exactly as you shaped it. ShellWrapper keeps the shell it matched (dialect()), lexer gains ShellDialect + contains_unattestable_construct_in, and rewrite_shell_wrapper passes the dialect. The fish rules reach the wrapper's own script and nothing else. On B's binary:

git log -20 && (cd www && npm test)          → rtk git log -20 && (cd www && npm test)     (exit 3)
(cd sub && git status)                       → (cd sub && rtk git status)                  (exit 3)
git status; if true; then echo x; fi         → rtk git status; if true; then echo x; fi    (exit 3)
cargo build; for f in *.rs; do echo $f; done → rtk cargo build; for f in *.rs; do …        (exit 3)
fish -c 'git status; cargo test'             → fish -c 'rtk git status; rtk cargo test'    (exit 3)
fish -c 'git status; and cargo test'           unchanged                                   (exit 1)

test_fish_rules_do_not_reach_bash_commands and test_posix_dialect_keeps_subshells_and_keywords_attestable pin it, so the reach cannot come back silently.

Blocker 2 — avoided rather than fixed. has_unclosed_quote_or_escape is not in the global gate in any of the three PRs, so the comment-blind scan never ships: ls -la # don't and cargo build # check (fast) rewrite on all three branches. C keeps a module-local quote check that only decides whether to wrap (refusing to classify an unfinished script is the safe direction there). The global version and the $'\'' auto-allow hole are yours — land ansi_c_quote_defeats_lexer on its own; nothing here depends on it or conflicts with it.

Blocker 3 — fixed in A. resolve_binary up front, and a miss renders through each runner's own failure path:

$ rtk err nosuchcmd123
[FAIL] Command failed (exit code: 127)
  rtk: nosuchcmd123: command not found          exit 127
$ rtk run nosuchcmd123
rtk: nosuchcmd123: command not found            exit 127   (stderr)

test/summary likewise. Two neighbours the same switch had broken: rtk test ! <cmd> now applies the negation to the child's exit status instead of getting it from sh (your bang_before_a_command_still_runs_the_command caught it), and the awareness body — RTK_SLIM_CODEX is gone since the awareness-file cleanup, so RTK_INSTRUCTIONS in src/hooks/init.rs is what ships as RTK.md; its rtk err <cmd> line now teaches argv and --shell.

From the optional list: --shell arity is a usage error now (exit 2, clap-rendered) rather than a mid-execution failure — clap still cannot express "exactly one positional when this flag is present", so it is checked where clap would answer; display_args re-quotes arguments carrying whitespace; and the backtick gap is closed in C's veto list (echo `hostname`; and echo ok no longer classifies as fish).

Not done, deliberately: fish-aware split_for_permissions. With the dialect gate, fish -c 'true; and rm -rf /tmp/zz' is not rewritten at all, so the host evaluates the original command exactly as today — same as the merge-base, which denied none of the wrapper forms. Making the permission path fish-aware is the same thesis as blocker 1 seen from the security side and deserves its own change.

On the rebase: #3828's commit needed re-threading through rewrite_pipeline_stage/rewrite_pipeline_producer (#3171) and the let-chain style, and its head foo expectations now follow develop's --head-lines 10 default. Authorship and message are unchanged, and if #3828 lands first that commit drops out of B's diff.

CI still has never run for these branches — A is the one I would most like a Windows signal on (cmd /C and the -Command flag selection). Thanks for the depth of round 1; the three-way split is clearly the right shape.

@pashifika pashifika closed this Sep 19, 2026
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.

2 participants