Skip to content

feat(rewrite): rewrite each line of multi-line Bash blocks - #3188

Closed
falsydotdev wants to merge 3 commits into
rtk-ai:developfrom
falsydotdev:feat/rewrite-multiline-blocks
Closed

falsydotdev wants to merge 3 commits into
rtk-ai:developfrom
falsydotdev:feat/rewrite-multiline-blocks

Conversation

@falsydotdev

Copy link
Copy Markdown
Contributor

Summary

Example:

$ rtk hook check 'git status
# check history
  grep -rn foo src'
rtk git status
# check history
  rtk grep -rn foo src

Test plan

  • cargo fmt --all && cargo clippy --all-targets && cargo test (2559 passed)
  • Manual testing: rtk hook check output inspected for sequential lines, indented/comment/blank lines, CRLF, for/if blocks, cross-line && and |/|& continuations, quoted multi-line strings, heredocs
  • 16 new unit tests (registry::tests::multiline_blocks, lexer newline-token test) covering the rewrite and every passthrough gate

Ref #1243

Coding agents routinely emit multi-line Bash blocks of sequential
commands. The rewriter tokenized newlines as plain whitespace, so a
block was treated as one command: the rtk prefix landed on the first
line and every following line ran raw and unfiltered.

Split multi-line input at the newline tokens the quote-aware lexer
emits (newlines inside quoted strings are never split points) and
rewrite each line through the existing single-line path. Blank lines,
comment lines, indentation, and CRLF separators are preserved verbatim.

Per-line rewriting only applies when every line is an independent
command. The whole block passes through untouched when:
- a shell keyword opens control flow (for/if/while/case/...)
- a list or pipeline continues across the line break (&&, ||, |, |&
  at a line edge)
- a subshell or group spans lines
- the block contains a heredoc (existing gate)

Ref rtk-ai#1243

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TFWJoUCNkUiaAUBomN2Lb3
@CLAassistant

CLAassistant commented Jul 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Hardening from adversarial review of the multi-line rewrite:

- If any newline byte was swallowed by quote state (raw \n/\r count vs
  emitted newline tokens), pass the whole block through. The lexer has
  no comment awareness, so an apostrophe in a # comment opens quote
  state and hides subsequent lines; rewriting such a block would act on
  lines no permission verdict accounted for. Passthrough hands the
  original command to native permission handling. Quoted multi-line
  strings (commit messages) forgo their rewrite as the safe trade.
- Bail when (( or )) sits at a line edge: arithmetic spanning lines
  must not get a command prefix spliced into arithmetic context.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TFWJoUCNkUiaAUBomN2Lb3
@falsydotdev

Copy link
Copy Markdown
Contributor Author

Pushed a hardening commit (aaa123c) after running an adversarial review against the branch. Two gaps closed:

  • Swallowed newlines now force passthrough. The lexer has no comment state, so an apostrophe inside a # comment opens quote state and swallows the following newline — hiding later lines from the splitter. The block now passes through whenever the raw \n/\r count differs from the emitted newline-token count, so native permission handling always sees the original command. (This check is deliberately global, not per-segment.) Quoted multi-line strings — e.g. multi-line commit messages — also take this path now; forgoing that rewrite is the conservative trade.
  • Cross-line arithmetic bails. (( x = / ls )) previously had rtk spliced into arithmetic context; ((/)) at a line edge now triggers passthrough.

Both cases have tests (multiline_blocks::test_comment_apostrophe_*, test_arithmetic_spanning_lines_passes_through), plus a positive test that a comment with balanced quotes still rewrites. Full gate re-run: cargo fmt --check / clippy --all-targets / cargo test (2563 passed).

@aeppling

Copy link
Copy Markdown
Contributor

hey, i think this is addressing same enhancement as #2781

- Strip trailing unquoted comments before the independence checks:
  'git log | # keep pipeline' continues the pipeline across the
  newline even though the line ends in comment text, and rewriting
  the next line would rebuild a pipeline whose final stage the
  pipeline-safety guard may specifically reject (e.g. grep -f).
- Bail when a line's unquoted ()/{} don't balance: array literals
  (arr=(one), function bodies (foo() {), and groups span lines, so
  surrounding lines are not independent commands. Subsumes the
  previous single-char edge checks.
- Bail on any block containing $'...': inside ANSI-C quoting bash
  treats \' as a literal quote that does not close the string, but
  the lexer thinks it does — emitting a split point bash would never
  honor, the inverse of the swallowed-newline case the count check
  catches.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TFWJoUCNkUiaAUBomN2Lb3
@falsydotdev

Copy link
Copy Markdown
Contributor Author

Second adversarial review round (two independent reviewers) — three more gaps closed in 882d561:

  • Array literals / function bodies spanning lines: arr=(one ... two) slipped past the edge checks (the parens are mid-line), so the inner line — an array element — got an rtk prefix. Now any line whose unquoted (/) or {/} don't balance bails the whole block; this also catches foo() { function definitions and subsumes the earlier single-char edge checks.
  • Continuation operators behind trailing comments: git log | # keep pipeline ends in comment text, so the ends_with("|") check missed that bash continues the pipeline across the newline — and rewriting the next line could rebuild a pipeline whose final stage the pipeline-safety guard specifically rejects (e.g. grep -f). Independence checks now run against the line with any trailing unquoted comment stripped.
  • ANSI-C $'...' quoting: inside $'...' bash treats \' as a literal quote that does not close the string; the lexer thinks it does, and emits a split point bash would never honor — the exact inverse of the swallowed-newline case, invisible to the count check. rtk could be spliced into the contents of a string literal. Any block containing $' now passes through.

The review also re-probed everything previously fixed (comment-apostrophe swallowed newlines, cross-line arithmetic, CRLF/lone-CR byte round-trips, UTF-8 offset slicing, ${HOME} brace balance, time/! prefixes) — all hold. Tests added for each new case, including positives that balanced grouping and quoted/unquoted ${...} still rewrite. Gate re-run: fmt / clippy / cargo test (2568 passed).

One divergence found during review is pre-existing and outside this branch's diff (collapse_line_continuations treats \\<newline> — escaped backslash + separator newline — as a continuation); filing separately.

@falsydotdev

Copy link
Copy Markdown
Contributor Author

@aeppling You're right, thanks — same territory (#1243), and I'd missed #2781 when I searched for prior art (I grepped for "multiline", your title says "bundles" — my bad).

The two PRs differ mainly in risk posture. #2781 goes for coverage: statement-level rewriting inside bundles that also contain pipes/substitutions/redirects, with the #1155 ask-clamp as the safety net (39.3% → 71.8% is a big win). #3188 is deliberately narrow: strictly line-level, and any construct that makes lines non-independent — or that the lexer can't attest — forces whole-block passthrough. Lower coverage, but the rewrite can never touch a line the splitter misjudged.

Since we'd just built an adversarial corpus for #3188 (two independent review rounds), I ran it against the #2781 head (2c89559). Four inputs currently rewrite in ways worth a look — all pass bash -n, which is why differential fuzz keyed on syntax validity wouldn't flag them:

  1. Comment apostrophe swallows the newline — bash's word-start # comment rule vs a lexer with no comment state:
    git status # don't
    rm -rf /tmp/x
    
    → rtk git status # dont' + the second line preserved raw. The apostrophe opens quote state, so the splitter never "saw" line 2 — worth checking how the ask-clamp treats lines that quote-state hid from split_for_permissions.
  2. Continuation operator behind a trailing comment:
    git log | # keep pipeline
    grep -f patterns.txt
    
    → rtk grep -f patterns.txt becomes the pipeline's final stage — which develop's own pipeline-final guard specifically rejects for grep -f (pattern file vs stdin).
  3. ANSI-C quoting — inside $'...', \' is a literal quote that does not close the string:
    x=$'foo\'
    git status
    '
    
    → rtk git status is spliced into the value of the string literal (silent data corruption; git status here is content, not a command).
  4. Function bodies get rewritten (foo() { rtk git status; }) — possibly intended given the coverage philosophy, but it changes captured output for x=$(foo) call sites.

#3188 now passes all of these by bailing to passthrough (the fix commits document each one). Happy for these to just become fuzz-corpus additions to #2781 if maintainers prefer the higher-coverage direction — the tests transfer either way, and I'd rather one good implementation land than two compete. Maintainers' call.

@falsydotdev

Copy link
Copy Markdown
Contributor Author

The failing CI / benchmark check is the known non-deterministic live-HTTP case (#2844): curl json against mockhttp.org/json/1 came back at 26 raw tokens this run, so the filter's 61-token output tripped the never-worse guard (-134%). This branch doesn't touch the curl filter (or any filter) — the diff is confined to the rewrite path (registry.rs) and lexer, and all rewrite benchmark cases pass. All other checks are green. Could a maintainer re-run the benchmark job when convenient?

@aeppling

Copy link
Copy Markdown
Contributor

Hey @revopsrocks , thanks for addressing this, here is a review, some of those case are not likely to be ran by agent, but if possible to have a solid implementation that cover most of case

Narrow the $' bail

One unrelated line currently disables the whole block:

kubectl get pods
git status
echo $'a\tb'          -> disables the other two

Only ' inside a $'…' span is actually hazardous, the rest rewrite normally.

Narrow the cross-line && / || / | bail

develop rewrites this correctly and completely today; the PR declines it:

git status &&
git log -3

develop → rtk git status && rtk git log -3
this PR → passthrough

comment_start should recognise "#" after an operator

Bash starts a comment wherever # begins a word, including right after |, &&, ;, (, ) — not only after whitespace:
Comment starts when the preceding non-space byte is whitespace, start-of-line, or one of | & ; ( ).

Guard the heredoc gate against line continuations

collapse_line_continuations joins <NL> with a space where bash joins with nothing, so << stops existing and has_heredoc() misses it:

cat <\
<EOF
git status
EOF

= cat < <EOF / rtk git status / EOF → syntax error near '<'

No real-world occurrences produced by agents, but the fix is one line: run has_heredoc() on the raw input, before collapse_line_continuations.

#[test]
fn test_heredoc_split_by_line_continuation_passes_through() {
    assert_eq!(
        rewrite_command_no_prefixes("cat <\\\n<EOF\ngit status\nEOF", &[]),
        None
    );
}

@KuSh

KuSh commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

Thanks for building this out. The line-by-line multiline rewrite landed on develop in #3319 (merged 2026-08-03), covering the same split-at-newline-tokens approach and the same passthrough gates for control flow, cross-line lists and pipelines, grouping and heredocs, along with a few extra ones. Running the develop binary on the example from this PR gives exactly the output shown here, and the lexer test added here is present on develop under the same name, so nothing from this PR looks missing. Please comment or reopen if you find a block shape develop still mishandles.

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.

4 participants