Repository navigation
Conversation
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
left a comment
There was a problem hiding this comment.
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. --shellonRuncarriesrequires = "command"+conflicts_with = "args"; onErr/Test/Summaryit carries no clap constraints at all, sortk test --shell fish cargo testdies at runtime withpass the shell command as one quoted argument after --shellinstead of a clap usage error. Same flag, two surfaces.is_unambiguous_fish's POSIX veto list coversthen/fi/do/done/esac/elif,[[and heredocs, but not backticks —echo `hostname`; and echo okclassifies 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_argsjoins argv with spaces and no re-quoting, sortk test cargo test --filter "a b"is tracked ascargo test --filter a b. Cosmetic (tracking label andTestEcosystem::detectinput 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,zshandfishindebian:sidand dumped the argvrtkreceives. All three host layers deliver the script byte-identically, including the multilineif … endcase and the'\''idiom. The\\/\'veto is the right pair to refuse, andprintf '%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 thefishPATH probe; both probes areFnOnceand are reached only on the fish path. - Never auto-allowed. Mutating
RewriteOutcome::Ask(wrapped)→Allow(wrapped)inrewrite_cmd.rs:89failstest_fish_script_rewrites_to_ask_wrapand nothing else;hook_cmd.rshas its own equivalent test. The claim is real and pinned. - Quoted parens are safe.
rtk grep -E '(foo|bar)' srcandecho '(printf x)'are unaffected by the new rule on both binaries. fishinSUPPORTED_SHELLSstays conservative.fish -lc,fish --command, andfish -cfollowed by a non-space all returnNone;env FOO=1 fish -c '…'and a trailing--fooare 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
fishonPATH: 0 were wrapped. The classifier is precise in practice.not grep -q pat filedoes 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 letsfish -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_escapewill 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.rsandhook_cmd.rsis this PR's doing." It predates the PR — and develop has since collapsed it (see rebase note). - "The conservative
\rhandling will cost rewrites." The opposite:rtk rewrite $'git status\rand echo ok'on the merge-base emitsrtk git statusand echo ok— the\ris 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 thepull_requestworkflow be created; I will approve the run as soon as there is one. Until then, neither of us has a Windows signal, andcmd /C+-Commandflag 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.
| let tokens = tokenize_inner(cmd, NewlineMode::Conservative); | ||
| if tokens | ||
| .iter() | ||
| .any(|token| token.kind == TokenKind::Shellism && matches!(token.value.as_str(), "(" | ")")) |
There was a problem hiding this comment.
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.
| .any(|(i, tok)| tok.kind == TokenKind::Redirect && redirect_has_file_target(&tokens, i)) | ||
| } | ||
|
|
||
| pub(crate) fn has_unclosed_quote_or_escape(cmd: &str) -> bool { |
There was a problem hiding this comment.
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.
| /// | ||
| /// 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> { |
There was a problem hiding this comment.
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.
|
@KuSh — split, rebased onto
Blocker 1 — fixed exactly as you shaped it.
Blocker 2 — avoided rather than fixed. Blocker 3 — fixed in A.
From the optional list: Not done, deliberately: fish-aware On the rebase: #3828's commit needed re-threading through CI still has never run for these branches — A is the one I would most like a Windows signal on ( |
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 runnersrtk run,rtk err,rtk testandrtk summaryrebuilt their positional arguments into one string and executed it throughsh -c(cmd /Con Windows). Argument boundaries were lost and globs, variables and operators were expanded by a shell the caller never asked for.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>', orrtk err|test|summary --shell <name> '<script>'. PowerShell andpwshget-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 constructsThe 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 toAsk, neverAllow.3.
feat(rewrite): accept quoted fish -c wrappers#3828 excluded
fishfrom the wrapper subset because the shared lexer could not attest fish's control keywords. Change 2 supplies exactly that guarantee, andrewrite_shell_wrapperruns the gate on the inner script: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:Ask, never auto-allowed: the script's content is unattestable by definition.rtk …, or an explicit-cwrapper), 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 undersh/bash/zshandfish— on Windows, without a resolvablefishbinary, or withhooks.wrap_fish_scripts = false.fishPATH probe, so non-fish commands reaching the gate (echo $(date), POSIX blocks) do zero I/O in the hook hot path.if/forwithout 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:
sudobehaviour is inherited from #3828 unchanged:sudo bash -c '…'passes through, because the innerrtkwould run as root where it is offsecure_path(#146/#3569).Key files
src/core/shell.rssrc/main.rs--shellsurface onrun/err/test/summary; positional forms route to direct executionsrc/discover/lexer.rssrc/discover/shell_wrapper.rsfishrejoins the conservative quoted-cwrapper subsetsrc/discover/fish_script.rssrc/core/config.rshooks.wrap_fish_scripts(defaults to enabled)src/hooks/rewrite_cmd.rs,src/hooks/hook_cmd.rsAsk, wrapper injected so tests do not depend on the local fish binary or user configtests/run_shell_test.rstests/fish_wrap_test.rs#[ignore])tests/rewrite_shell_wrapper_test.rsTest plan
cargo fmt --all --check— cleancargo clippy --all-targets -- -D warnings— cleancargo test --all— 3,313 passed, 0 failed, 9 ignoredcargo test --all -- --ignored— 9 passed (includes realfishexecution)rtk rewriteend-to-end, isolatedHOME/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)if … endblock →rtk run --shell fish -c '…'(exit 3, no auto-allow)rtk runend-to-end: explicit fish executes fish-only syntax, argv boundaries survive ('a b',*,$HOMEunexpanded),-ckeeps the POSIX default, exit code 7 propagates,--shell fish echo okis rejected instead of re-joinedcmd /C, PowerShell flag selection, wrapper parsing)Tested on macOS 26.6.2 arm64 (M1 Pro), rustc 1.97.1, fish 4.9.0.