Skip to content

refactor(cmdline): one borrowed token type with separator and newline kinds - #4341

Open
KuSh wants to merge 1 commit into
lex/11-lexer-to-corefrom
lex/12-segment-edits
Open

KuSh wants to merge 1 commit into
lex/11-lexer-to-corefrom
lex/12-segment-edits

Conversation

@KuSh

@KuSh KuSh commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Gives the lexer one borrowed token type, and makes every reader of a command line split words, read comments and join continuations where bash does.

  • tokenize returns Token { kind, value, offset }, a slice of the input. Tokens tile the input; Sep (a blank run) and Newline (\n) carry what lies between words.
  • words() is the one function that finds words, and QuoteScan the one quote-state machine.
  • Word boundaries are $IFS (space, tab, newline) wherever a command line is read. Rule patterns and built-in filters spell a separator [ \t\n], and a test rejects \b, \s and \S in them.
  • QuoteScan reads a backslash in an ANSI-C quote as bash does, as escaping the byte after it, so every reader ends the quote and its word where the shell does.
  • core/cmdline/rtk.rs answers whether a command already runs rtk, from its words.
  • core/cmdline/source.rs reads a text as bash's parser does before it has words, and says which # opens a comment and which \⏎ joins two lines. It follows the nesting, which one flat quote state cannot: $( ) inside double quotes, ${x#y}, $(( 16#ff )), $(ls # c⏎).
  • The tokenizer emits a comment as one Comment token, and the scan restarts after it. Comments stay tokens: the rewrite gives them back, and the permission checks ignore them.
  • join_continuations is the one reader of continuations. The rewrite, the permission gate, the hook's substitution check and rtk discover read a line through it, and a rule pattern is read through it too.
  • A text is too complex where something in it never closes, past 16 levels of nesting or a read that costs too much, or where bash reads it two ways. join_continuations then returns a TooComplex, and the permission gate has a verdict of the same name.
  • On a line the reader reads, rules hold for what it calls commands. On a line it cannot read, a deny rule is checked against the best-effort text, comments included, and otherwise the verdict is TooComplex.

Behaviour changes

  • \r, VT, FF and NBSP are word bytes, as in bash. A CRLF line is not rewritten: git status\r\ngit log rewrites the second line only.
  • A command word ends at a blank or the end of the line: helm-docs is not helm, dotnet build-server is not dotnet build.
  • An escaped trailing blank stays in its word: git log | head\ is not rewritten, since it runs head .
  • A tab after head, tail, cat or rtk reads like a space.
  • 'rtk' git status and \rtk git status count as rtk, as bash runs them.
  • cat is rewritten only when it names a file and its only options are bare -n.
  • The permission gate reads a line with its continuations joined, as bash runs it and as the rewrite emits it: ls "$\⏎(rm Y)" is decided as ls "$(rm Y)", and l\⏎s as ls.
  • A quote in a comment opens nothing, a \ at its end escapes nothing and the line after it is read as its own: git status # don't⏎git diff becomes rtk git status # don't⏎rtk git diff.
  • A rule does not read comment text: with more:* denied and echo a allowed, echo a # note; more is allowed, where the ; in the comment used to split the line.
  • A # after an escaped or quoted |, &, ;, ( or ) starts no comment.
  • A line too complex to read is not rewritten: a[1 # 2]=b; ls, echo a>#b, echo "$['1\⏎+1']", <<$(a). A deny rule naming a command on what can be read of it still denies. Otherwise the Claude hook asks for the line as it stands, saying why, over an allow rule that names some commands, and other hosts decide themselves.
  • The Claude hook leaves that line to the host where the session's permission mode never prompts (bypassPermissions, dontAsk, auto), and where settings hold no deny entry or Bash(…) ask rule and allow either Bash(*) or nothing named, so claude -p --allowedTools Bash runs it as before. With a deny entry or a named allow rule, a hook ask under claude -p in default or acceptEdits mode stops the tool call with a readable error where the line used to run.
  • A line whose every command opts out, through RTK_DISABLED or exclude_commands, stays with its host, and the audit log records the rest as skip:too_complex.

Test plan

  • cargo fmt --all --check && cargo clippy --all-targets -- -D warnings && cargo test --all: 6076 passing, clippy clean, at this commit
  • wincheck.sh (cfg(windows) type-check) clean
  • Hook verdicts compared with the parent commit over 1,274,141 commands: 3,199 newly allowed, each a line whose comment or continuation the parent misread. All run in bash in a container: they run only the allowed commands, but for two lines starting ls\r and git status\r, which the gate reads as ls and git status, on develop too
  • Every allowed rewrite that differs from the parent's (21,093) run in bash in a container next to the original line: the same commands run, with the same output and exit code. Five lines with a background & differed in one run and matched the original in 12 repeats
  • Reader against bash: 117,744 lines of subscripts and case in substitutions, with a canary at each command position. On the 12,461 where the canary ran, a deny rule on it denied every one
  • Every generated line where bash ran a denied command (6,334), against develop: 1,742 newly denied, none newly allowed. 20 denied by develop only because a comment held the word and now left to the host, where the real command is spelled so no rule names it (git -c a=b push, \rm), as it is without the comment

Part of stack #4139 (#4129 → #4331 → this). Based on #4331. Each commit gates green on its own, so the stack is bisectable.

🤖 Generated with Claude Code

@rtk-wshm-sync-bot

Copy link
Copy Markdown

wshm · Automated triage by AI

📊 Automated PR Analysis

♻️ Type refactor
🟡 Risk medium

Summary

Refactors the discover module's command-segment rewriter to lex a compound command line once and apply changes as a validated list of span-based Edits (new cmdline/edit.rs module with apply_edits), instead of ad hoc string manipulation. Adds CompoundLex::trimmed_slice, Tok/tok_view, and shell_split_from_tokens helpers shared between the rewriter and the permission gate's segmentation logic, and updates src/core/README.md to document the new shared scanning helpers and edit model.

Review Checklist

  • Tests present
  • Breaking change
  • Docs updated

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

@KuSh
KuSh marked this pull request as draft September 29, 2026 23:55
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 7be8b0b to 8bbeca8 Compare October 2, 2026 15:20
@KuSh KuSh changed the title refactor(discover): rewrite a segment by lexing once and editing spans refactor(cmdline): one borrowed token type with separator and newline kinds Oct 2, 2026
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 8bbeca8 to d85b7a5 Compare October 2, 2026 16:01
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from d85b7a5 to 86bb9d4 Compare October 2, 2026 16:20
@KuSh
KuSh marked this pull request as ready for review October 2, 2026 18:20
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 86bb9d4 to 8dcdf68 Compare October 5, 2026 22:36
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 8dcdf68 to 1997821 Compare October 7, 2026 07:16
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 1997821 to 5122113 Compare October 9, 2026 16:16
@KuSh
KuSh force-pushed the lex/12-segment-edits branch 3 times, most recently from d9a8246 to eaf7d86 Compare October 15, 2026 00:24
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from eaf7d86 to 3e917c7 Compare October 15, 2026 12:03
@KuSh
KuSh force-pushed the lex/12-segment-edits branch 2 times, most recently from b1f32f7 to 9652e84 Compare November 3, 2026 06:27
@KuSh
KuSh marked this pull request as draft November 4, 2026 07:41
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 9652e84 to 5886ebe Compare November 5, 2026 11:48
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 5886ebe to 164441e Compare November 5, 2026 12:12
@KuSh
KuSh marked this pull request as ready for review November 5, 2026 12:22
@KuSh
KuSh force-pushed the lex/12-segment-edits branch 2 times, most recently from fca7c1f to c2a0ae2 Compare November 18, 2026 01:06
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from c2a0ae2 to 85cf7c2 Compare November 19, 2026 01:12
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 85cf7c2 to b8bf1b0 Compare November 21, 2026 09:57
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from b8bf1b0 to da55fee Compare November 23, 2026 00:14
@KuSh
KuSh force-pushed the lex/12-segment-edits branch 2 times, most recently from 76c5135 to 103633a Compare November 27, 2026 22:44
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 103633a to 307c12d Compare November 28, 2026 01:23
… kinds

`tokenize` returns `Token { kind, value, offset }`, built directly by the
tokenizer: every value is a slice of the input, and the tokens tile it, so
each byte belongs to exactly one token. Two kinds carry what lies between
words: `Sep`, the exact run of spaces and tabs, and `Newline`, the `\n` it
sits on. The lexer always emits both; the segmenter's `NewlinePolicy` says
whether a newline ends a segment or separates words like a `Sep`.
`tokenize_at` lexes a piece of a larger input with offsets into that input,
which is how the segmenter reads the pieces a policy cuts.

A `Word` is a run of adjacent tokens that are not blanks, with its span, and
`words(input, tokens)` is the one function that finds them: the env-prefix
split, golangci's flag parsing and `shell_split` all read it. `QuoteScan` is
the one flat quote-state machine, walked by the tokenizer, by
`resolve_word_text` and by every other quote-aware scan in the lexer.

A command ends where its last word does, and an escaped or quoted blank is
part of that word. The rewrite path in `discover/registry.rs` therefore
takes the ends of a line, a segment, a pipeline stage, a wrapper prefix, an
env prefix and the command in front of trailing redirects from the tokens:
`content_span` gives a token range's span without the blanks around it,
`tokenize_trimmed` lexes a command and returns it trimmed that way with its
tokens, and `tokens_until` gives the tokens of a prefix. A segment is lexed
once, and its tokens are handed to the env-prefix split, the wrapper and
redirect splits and classification. A configured `transparent_prefixes`
entry is matched as text and can end inside a quote; the command behind it
is lexed on its own, and the blanks between where that lex ends it and where
the segment's lex did are emitted as written. `head`, `tail` and `cat` are
recognised by their first word, and `cat`'s options are classified through
`arg_tokenizer`.

`core/cmdline/rtk.rs` answers whether a command runs rtk, from its words:
`rtk_invocation` reads the first word with its quotes and escapes removed,
as bash does before it looks the command up, and says whether the second,
read the same way, is `proxy`. The rewriter returns such a command as it is
unless its tokens hold an unquoted `&&`, `||`, `;`, `|` or `&` that joins
another command to it, classification ignores it, and `rtk discover` and
`rtk session` count it as adoption unless it is `rtk proxy`. The discover
report takes a command's first two words from the lexer's words too.

Word boundaries are bash's `$IFS` wherever a command line is read. The
lexer's `is_ifs`, `split_ifs` and `trim_ifs*` helpers serve the segmenter,
classification and the permission gate's pattern normalisation. The rule
patterns in `discover/rules.rs` and the built-in filters' `match_command`
spell a separator `[ \t\n]` and end a command word with `(?:[ \t\n]|$)`;
a rule also ends one at a metacharacter glued to it,
because classification reads a segment with its redirects kept. Tests reject
`\b`, `\s` and `\S` in a rule pattern and in a built-in filter. Project and
user-global filters are matched as written, and the filter docs and
`rtk init` templates show the `[ \t\n]` form. A subcommand capture that needs
one spacing joins its words with single spaces through `squeeze_blanks`, and
so does the permission gate before it compares a command with a pattern.

The permission gate cuts a line at every unquoted `\r` and lexes each piece
on its own, as it does at a `\n`, so that no command hides behind one.

`core/cmdline/source.rs` reads a text as bash's parser does before it has
words, and says which `#` opens a comment and which `\<newline>` joins two
lines. One flat quote state cannot say: bash reads quoting afresh in a `$( )`
inside double quotes, a `#` is text in `${x#y}` and `$(( 16#ff ))` and a comment
in `$(ls # c<newline>)`, and a `)` in that comment closes nothing. So it follows
the nesting. Commands stand in `$( )`, `( )`, `<( )`, a backquote and on a
heredoc's line, text in `${ }`, `$(( ))`, `$[ ]` and a heredoc's body, and `(( ))`
is arithmetic if it closes so. A text with no `#` and no `\<newline>` is not read.

The tokenizer emits a comment as one `Comment` token, from its `#` through the
end of its line, and the scan restarts after it, so a quote in comment text opens
nothing and a `\` at its end escapes nothing. Every reader takes comments from
there: segmentation closes a segment at one and cuts at a bare `\r` only outside
one, a rewrite gives a command's comment back, and the multi-line rewrite reads
`without_comments` and the unattestable check `placed_code`.

A line continuation is joined where bash joins it, by the lexer's
`join_continuations`, the one reader of continuations. The rewrite reads a line
through it, and the permission gate and the hook's own substitution check read the
line through it before anything else, so what they check is the text the rewrite
emits; the gate and the rewrite do the same for the script of a single-quoted `-c`
wrapper, which the shell it starts joins. It replaces
`collapse_line_continuations` and the two regexes behind it in
`discover/registry.rs`, and the gate's own `\<newline>` removal.

A text is too complex where something in it never closes, past 16 levels of
nesting or a read that costs too much, or where bash reads it two ways:
`a[1 # 2]=b` is a subscript where a command may start and a comment elsewhere,
`a>#b` starts a comment in bash and a word in zsh, a quote in `"${x:-'}'}"` holds
what the operator decides about, and in `$(time -p case a in a) b;; esac)` a `case`
that may be text decides which `)` closes what. So is a heredoc delimiter holding
an expansion, `<<$(a)`. `join_continuations` then
returns a `TooComplex`, and nothing is rewritten. If a deny rule names a command
on what the reader made of the line, on the same with its comments read as
commands, or on one flat quote state's reading, the gate says so as it would
anywhere; otherwise its verdict is `TooComplex`, whatever an allow rule names. The
Claude hook asks for that line as it stands, saying why, unless the session's
permission mode never prompts (`bypassPermissions`, `dontAsk`, `auto`), and every
other caller leaves it to its host, since it cannot show an ask without a rewrite.
Settings with no deny entry or ask rule, and either `Bash(*)` or `Bash` allowed or
no allow rule at all, leave nothing to ask about: the host runs the line or asks by
itself, as it does without RTK, so such a line stays with it too.
A script a shell wrapper holds is read the same way. A line whose every command
opts out on all those readings, through `RTK_DISABLED` or `exclude_commands`, stays
with its host, and the audit log records the rest as `skip:too_complex`.

On a line the reader does read, rules hold for what it calls commands. A comment
stays a token that the rewrite gives back, and the permission checks ignore it. A
rule is read through `join_continuations` too, so one spelled across a continuation
names what bash joins it into.

`rtk discover` reads a line as the hook does, so a `\<newline>` is no word in its
report.

Behaviour, as the code implements it:
- Words split only on space, tab and newline, as in bash. A `\r` is a word
  byte, so `git status\r` keeps `\r` in its last word and a CRLF line is not
  rewritten: `git status\r\ngit log` rewrites the second line only.
- A vertical tab, form feed, non-breaking space or carriage return next to a
  word is part of that word: `\x0b2>&1` is the command `\x0b2` with a `>&1`
  redirect, and `git status\u{a0}` runs git with the subcommand
  `status\u{a0}`.
- For rules and built-in filters alike, a command word ends at space, tab,
  newline or the end of the line. `helm-docs` is not `helm`, `make\r` is not
  `make`, `dotnet build-server` is not `dotnet build`, and
  `mvn install:install-file` is not the `install` phase; `g++ -c x.cpp`
  takes the gcc filter. The mvn and mvnd rules list `test-compile`. The
  command word `exclude_commands` names ends there too, so excluding `mytool`
  leaves `mytool\x0bx` alone.
- An escaped trailing blank stays in its word, and so does a trailing blank
  inside a quote left open: `cat f\ ` becomes `rtk read f\ `, and
  `git log | head\ ` is not rewritten, because its last stage runs the
  program `head ` rather than `head`. Those blanks are emitted as written
  when a configured prefix ends inside the quote: with the prefix `x 'a`,
  `x 'a ls -la & ` becomes `x 'a rtk ls -la & `, and with the prefix
  `sh -c "`, `sh -c " rtk git status ` is left as it is.
- `head`, `tail`, `cat` and `rtk` followed by a tab are handled as when
  followed by a space: `tail\t-n 5 f` becomes `rtk read f --tail-lines 5`,
  `cat\t-A f` is not rewritten, and `rtk\tgit status` is left as it is. A
  bare `head`, `tail` or `cat` has nothing to map or check and goes to the
  filters like any other command.
- A first word runs rtk when it is `rtk` once its quotes and escapes are
  removed, as in bash: `'rtk' git status`, `"rtk" git status` and
  `\rtk git status` run rtk, and `'rtk git' status` does not.
- A line whose first word runs rtk is left as it is unless an unquoted
  `&&`, `||`, `;`, `|` or `&` joins another command to it, whatever blanks
  sit around the operator: `rtk git status\t&\tgit log` and
  `rtk git status &git log` become `rtk git status\t&\trtk git log` and
  `rtk git status &rtk git log`, while `rtk grep 'a|b' src` and
  `rtk git commit -m "a && b"` are left as they are.
- `rtk discover` and `rtk session` count a command as already rtk when its
  first word runs rtk and its second is not `proxy`: `rtk\tgit status`,
  `rtk` alone and `\rtk git status` count, `rtk\tproxy git status` does
  not. The report files `git  status` under the subcommand `status` and
  shows it as `git status`, and shows `grep 'a b' src` as `grep 'a b'`.
- A `\` before a newline goes with the newline outside single quotes, and
  nothing else does: `git di\⏎ff` is `git diff`, `git commit -m 'a\⏎b'`
  keeps its message, the blanks of `printf "a \⏎  b"` stay in its word, and
  neither `\\⏎` nor `\␍⏎` is a continuation, so `\␍⏎git diff HEAD~1`
  rewrites its second line only. `bash -c 'git \⏎status'` is a wrapper the
  gate and the rewrite read inside, joined: it becomes
  `bash -c 'rtk git status'`. `ls "$\⏎(rm Y)"` substitutes a command, as
  bash joins it, and is decided about as `ls "$(rm Y)"` is.
- A continuation is read where it stands: `"$(echo "a \⏎ b")"` joins it,
  `"$(echo 'a\⏎b')"` keeps it, and a comment holds it, except in a backquote,
  where bash takes every `\⏎` out before reading the text.
- A line too complex to read asks through the Claude hook, and is not
  rewritten: `a[1 # 2]=b; ls`, `echo a>#b` and `echo "$['1\⏎+1']"` ask where a rule
  names some commands or holds some back. A deny rule that names a command on the
  line as far as it reads comes first: `echo "$['1\⏎+1']"; touch f` is denied by `touch:*`.
- A quote in a comment opens nothing, a `\` at its end escapes nothing and the line
  after it is read as its own, and text in it is neither a command nor a
  substitution. `git status # don't⏎git diff` becomes
  `rtk git status # don't⏎rtk git diff`, `git status ${x} # note` becomes
  `rtk git status ${x} # note`, and a `#` in `${x#y}` or `$((16#ff))` is text.
- A rule does not read comment text: with `more:*` denied and `echo a` allowed,
  `echo a # note; more` is allowed, where a comment's `;` used to split the line.
- A `#` after an escaped or quoted `|`, `&`, `;`, `(` or `)` starts no
  comment: the line `echo a\;#b` is one command, not a command and a comment.
- `cat` with arguments is rewritten only when it names a file and every
  option it receives is a bare `-n`, wherever the option sits and however
  it is quoted: `cat f -A`, `cat '-A' f`, `cat -- f` and `cat -n` are not
  rewritten, and `cat -` becomes `rtk read -`.

`QuoteScan` reads a backslash in an ANSI-C quote as bash does, as escaping the
byte after it, so the quote ends at the first `'` that none escapes. A `$` pairs
with the one before it, so only an odd run of `$` opens one. The tokenizer, the
comment and continuation readers and the rewrite end a word where the shell
does, and the separate check for lines the flat reader ended differently is
removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@KuSh
KuSh force-pushed the lex/12-segment-edits branch from 307c12d to bccad55 Compare November 29, 2026 01:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant