Compare commits

...
Author SHA1 Message Date
Nicolas Le Cam d402152ffa Merge pull request #1422 from JackDanger/fix/suppress-hook-warn-during-init
fix: suppress hook warning during rtk init and verify
2026-09-14 01:20:47 +02:00
Nicolas Le CamandClaude Opus 5 06d538728c test: cover which commands get the daily hook reminder
Pins both directions: the commands that report hook state themselves stay
quiet, and the filtered commands still warn. Also pins the reason the
suppression is worth having — `maybe_warn` touches the once-a-day marker, so
warning on a meta command would leave the next filtered command silent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 01:01:14 +02:00
Nicolas Le Cam cfe248c1f6 Merge pull request #3941 from iliaal/fix/faithful-head-tail-windows
fix(read): make head/tail rewrites faithful to the native commands
2026-09-14 00:59:57 +02:00
Nicolas Le CamandClaude Opus 5 784d347011 test(read): isolate the rewrite test from the developer's rtk config
`rewritten_head_spellings_match_native_on_non_utf8_files` isolates
`CLAUDE_CONFIG_DIR` but reads the ambient `XDG_CONFIG_HOME`, so a config
carrying `exclude_commands = ["head", "tail"]` suppresses the rewrite and
the exit-code-3 assertion fails. Clean runners have no such config, so the
test passes in CI and fails only for the developers most likely to have
opted out of these very rewrites.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 00:45:35 +02:00
Nicolas Le CamandClaude Opus 5 e224b159af docs(read): point the head/tail rewrite docs at --head-lines
The pipeline diagram, the discover walkthrough and the `rtk read` option
table still described the `--max-lines` mapping this branch replaced, and
the repo's own suggest hook still proposed `--max-lines N` for `head -N`
— the mapping this branch exists to correct.

Drop the `head -` disjunct in the rewrite guard: every string with that
prefix also has the `head ` prefix that sits next to it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 00:45:35 +02:00
Nicolas Le Cam 2ff2f71711 Merge pull request #1298 from rtk-ai/fix/tracking-weighted-aggregations
fix(tracking): weighted savings rate in low_savings_commands and avg_savings_per_command
2026-09-14 00:37:18 +02:00
Nicolas Le CamandClaude Fable 5.1 cb5e5994e1 fix(tracking): align the telemetry rates with rtk gain and pin them in memory
`get_by_command` moved to the volume-weighted rate while this branch was
open (#891), summing every call and guarding the division at group level.
The two telemetry queries now use the same shape: the row-level
`WHERE input_tokens > 0` is gone, so a call with no input that still
printed something counts against its command exactly as it does in the
By Command table, and `HAVING SUM(input_tokens) > 0` keeps commands that
never had any input out of both, as before.

`low_savings_commands` lists net-regressing commands: `sav > 0.0` became
`sav <> 0.0`, so only exact 0% stays with `passthrough_top`. A command
that emits more than it saves is the filter to fix first, and with the
weighted rate the old bound also dropped commands the unweighted query
used to list.

The two regression tests opened the on-disk tracker, so every `cargo test`
wrote ten synthetic rows (one at 100k input tokens) into whichever history
database `Tracker::new()` resolves to, on a developer machine the real one.
They now use `Tracker::new_in_memory()` like the rest of the module, and
`test_avg_savings_per_command_inner_weighted` only asserted a `0..=100`
range that the unweighted query also satisfied. Both tests now assert the
exact weighted figures, check each listed rate against `get_summary()`,
and fail when either query goes back to `AVG`, to the row filter, or to
the positive bound.

Tests are numbered 18 and 19 after the ones develop already carries as
14-17. The `low_savings_commands` doc no longer points at a PR, and both
telemetry field tables describe the new semantics.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 21:05:32 +02:00
Nicolas Le Cam 4b6c0f00ef Merge remote-tracking branch 'upstream/develop' into pr-1298-merge 2026-09-13 20:35:13 +02:00
Nicolas Le Cam b6a171242c Merge pull request #891 from rtk-ai/fix/gain-weighted-avg
fix(gain): use weighted savings rate in per-command stats
2026-09-13 20:30:32 +02:00
Ilia Alshanetsky 23a1be622f test(read): isolate rewrite permission settings 2026-09-13 12:35:05 -04:00
Ilia Alshanetsky 6f4913b37b fix(read): preserve non-UTF-8 head and tail windows 2026-09-13 12:27:47 -04:00
Nicolas Le CamandClaude Opus 5 9573488935 test(tracking): cover the weighted rate with isolated in-memory cases
Move the weighted-rate regression test off the real tracking database, which
it wrote two rows into on every run, and onto an in-memory tracker. Add the
long-tailed pair that pins the weighted rate against the mean of percentages,
the same assertion through get_summary(), and a zero-input group: without the
CASE guard that last one fails on a NULL rate, and no other test covers it.

Name the 4th field of GainSummary::by_command for what it now holds, and state
the rate formula on the CommandStats warning in percentage order, with the zero
guard, so that following it verbatim cannot reintroduce the NULL.

Head the column Total% rather than Rate, keeping the shape of the Avg% it
replaces and naming the total the figure is now taken over.

Drop the hand-written CHANGELOG entry: release-please generates it from the
commit subject, and CONTRIBUTING.md asks for that file to be left alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 17:51:27 +02:00
Nicolas Le Cam 86668b065a Merge remote-tracking branch 'upstream/develop' into pr-891 2026-09-13 17:25:52 +02:00
Nicolas Le Cam d0c2985155 Merge pull request #1122 from carlosdagos/fix/gh-pr-no-early-exit
fix(gh): don't early exit on failure for "pr checks"
2026-09-13 15:17:12 +02:00
Nicolas Le CamandClaude Opus 5 d105227193 fix(gh): account for every check bucket in the pr checks summary
Filtering a failing `gh pr checks` makes the summary the only thing the user
sees, so a bucket it does not count disappears. `parse_pr_check_line` dropped
every row that was not pass/fail/pending, which turned a cancelled run -- the
usual outcome when a new push supersedes CI -- into "Passed: 0, Failed: 0",
and left 5 of PR 3982's 15 checks out of the totals.

Count the remaining buckets and report them, so the summary always adds up to
the checks gh listed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 15:04:33 +02:00
Nicolas Le Cam 83b1957cca Merge remote-tracking branch 'upstream/develop' into pr-1122-clean 2026-09-13 15:04:33 +02:00
Nicolas Le Cam 0cd3eba80b Merge pull request #3542 from uuzzrm/fix/gh-checks-watch-deduplicate
fix(gh): deduplicate watched PR checks
2026-09-13 14:47:27 +02:00
Nicolas Le Cam 718c18530d Merge pull request #3857 from Micaso/feat/ast-grep-support
feat(ast-grep): add ast-grep filter (rtk ast-grep)
2026-09-13 14:37:39 +02:00
Nicolas Le CamandClaude Opus 5 83f87f92f3 test(gh): use gh's real row shape in the pr checks tests
`gh pr checks` spells a pending bucket `pending`, never `*`, and prints five
tab-separated fields with the description last. The transition test used a
shape gh does not emit; the new case carries the trailing description column
and a pending row that resolves across polls.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 12:33:46 +02:00
Nicolas Le CamandClaude Opus 5 3d2d244406 fix(ast-grep): account for every dropped line and stop wrecking scan output
Two defects in `filter_ast_grep`, both verified against ast-grep 0.45.3.

`ast-grep scan` diagnostics parse only on their locator line, so filtering
line by line kept `  ┌─ a.rs:2:13` and dropped the rule id, severity,
message and source line — at exit code 0, so it read as success. The
whole-output fallback never fired because `order` was not empty.
`unparsed_signal()` now passes any shape through untouched when a single
non-blank line fails to parse, which is what `search.rs` already does for
grep/rg. This also covers `--heading` mode and Windows drive-letter paths,
where `[^:]+` cannot match `C:\src\a.rs`.

The per-file overflow hint was computed as `entries.len() - max_per_file`,
which ignores `max_total` cutting a file short: a file under its own cap
lost its remainder with no hint at all, and a file over it under-reported
the drop. Both now count against what was actually printed.

The hint said "matches" while counting lines. ast-grep prints one line per
matched source line and a structural match spans several, so a repo search
reported "19 more matches" where five matches remained.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:16:33 +02:00
Nicolas Le CamandClaude Opus 5 f64d1d4808 fix(ast-grep): adopt PipelineSafety after merging develop
`RtkRule::pipeline_final_safe` was replaced by the `PipelineSafety` enum
on develop (#3171). The ast-grep rule still set the old field, so the
branch merged cleanly but failed to compile (E0560).

`ProducerOnly` keeps the rule's original intent: safe as a pipeline's
first stage, never as its final stage, since run() execs with stdin null.
Adding a producer-safe rule also requires listing it in
`test_pipeline_producer_safe_rule_set`, which pins the exact set.

`savings_pct` was left at the 60.0 default; the repo-wide measurement is
84.6%, which is what README and what-rtk-covers.md already claim.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:11:52 +02:00
Nicolas Le Cam 8b4c445815 Merge branch 'develop' into feat/ast-grep-support 2026-09-13 12:11:52 +02:00
Nicolas Le Cam 5626e94a63 Merge pull request #3552 from yeahjack/feat/codex-direct-hook
feat(hooks): add direct Codex command rewriting
2026-09-13 12:01:14 +02:00
Nicolas Le CamandClaude Opus 5 ce6e277cce refactor(permissions): group rule-less hosts into one match arm
Codex and Vibe both return empty rule vectors; keeping them as separate
arms multiplies branches that have to stay in sync. Group them, sorted,
with one comment covering both.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 11:42:31 +02:00
Yijie Xu 0d7e4fba32 fix(codex): use shared hook decisions and preserve audit reasons 2026-09-13 16:57:04 +08:00
Yijie Xu 484b7ce583 fix(codex): adapt upstream changes and explain sandbox tracking access 2026-09-13 16:50:19 +08:00
Yijie Xu d597302268 fix(hooks): preserve best-effort multi-file cleanup 2026-09-13 16:50:19 +08:00
Yijie Xu eefcb23fb4 refactor(hooks): share PreToolUse rewrite payload builder 2026-09-13 16:50:19 +08:00
Yijie Xu 1cf7df68d0 refactor(hooks): centralize hook JSON file I/O 2026-09-13 16:50:19 +08:00
Yijie Xu 285fb68717 fix(hooks): address Codex integration review feedback 2026-09-13 16:50:19 +08:00
Yijie Xu 7f2788a1b4 feat(hooks): add direct Codex command rewrite 2026-09-13 16:50:19 +08:00
Nicolas Le Cam 0f8b26c7cf Merge pull request #3087 from lntutor/fix/2663-npm-subcommands
fix(npm): recognize extended subcommands
2026-09-13 03:13:40 +02:00
Nicolas Le Cam 79b96a44c2 Merge pull request #3772 from KuSh/fix/stdout-only-filters-swallow-stderr
fix(core): stdout-only filters silently swallow a tool's stderr
2026-09-12 23:16:47 +02:00
Nicolas Le CamandClaude Opus 5 baf3a10aeb test(core): pin stdout-only stderr handling
Six cases over a fake tool on PATH, covering both halves of the contract: the
tool's own stderr has to reach the user, and rtk must not invent a stdout
message in its place.

The prettier case is the one that is easy to get wrong. It writes its report to
stderr and nothing to stdout even on a successful run, so a filter's empty-input
placeholder ("Error: prettier produced no output") would be printed over a run
that worked. An empty stdout from a command that printed nothing on stdout is
the correct answer.

Also pinned: stderr is not replayed onto stdout on top of being forwarded, a
genuinely silent command stays silent, forwarding is not golangci-specific, and
exit codes propagate -- including golangci-lint's exit 1, which means issues
were found and is reported without failing the build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 22:59:02 +02:00
Nicolas Le CamandClaude Opus 5 3a4daef6f3 fix(core): forward stderr from stdout-only filters and count it
`RunOptions::stdout_only()` is documented as "stdout-only to filter, stderr
passthrough", but the passthrough half was never implemented: stderr was captured
and dropped on every path except `skip_filter_on_failure`. A tool that reports on
stderr and leaves stdout empty therefore produced nothing at all.

golangci-lint is the visible case -- a config or build error goes to stderr, the
filter is handed an empty stdout, and the never-worse guard replaces its
"JSON parse failed" fallback with the empty string, so both streams end up
silent. The same shape applies to every other stdout-only filter: ruff, pytest,
rspec, rubocop, gh, glab, prettier, tree, wc.

Savings are also measured against running the command directly, so the stderr
that is forwarded has to be counted as emitted. Comparing stdout to stdout while
printing stderr as well booked a passed-through stream as if it had been
filtered away.

The guard keeps comparing against stdout. stderr is forwarded verbatim on both
sides, so it cancels: never-worse reduces to `filtered <= stdout`, and widening
the baseline to the combined output would let rtk emit more than the command it
replaces.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 22:59:02 +02:00
Nicolas Le Cam 8b891a5cf4 Merge pull request #3681 from KuSh/feat/arg-tokenizer
feat(core): add arg_tokenizer and migrate git/grep/dotnet/golangci arg parsing onto it
2026-09-12 22:58:13 +02:00
Nicolas Le CamandClaude Opus 5 6e16ad847f Merge upstream/develop into feat/arg-tokenizer
develop rewrote `run_show`'s routing underneath this branch (#3265, eight
commits) into `ShowRoute` with a `cat-file` probe for blob detection. That
structure is newer and better than what this branch had, so it is kept whole
and this branch's contribution is folded into it rather than the other way
round.

`commit_or_stat_route` now classifies with the tokenizer instead of scanning
strings. develop matched `a == "--stat"` and `a.starts_with("--pretty")`,
which reads a pathspec named `--stat` past the boundary as the flag and
`--prettyish` as `--pretty`, and covers three stat spellings where the set of
shapes the compaction cannot render is larger. `git show -- --stat` takes the
compact path again.

`consumes_next_token_as_value` is reimplemented on `log_takes_value` rather
than restored as its own table. develop's copy is a subset -- it omits
`--max-count`, `--ignore-matching-lines`, `--min-age`, `--max-age` and
`--stat-graph-width` -- and keeping both would be the two-lists-drift this
branch exists to remove. Its callers are unchanged, so blob-show keeps its
own grammar rules; the attachment distinction (`-M50` attaches, `-M 50` does
not) is what the tokenizer adds.

This branch's `is_blob_show_arg` and free-positional blob pre-filter are
dropped in favour of develop's, which also handles index and merge-stage
blobs (`:file`, `:2:file`) and probes with `cat-file` rather than trusting
the shape of the argument.

Verified: seven blob-show invocations byte-identical to develop, including
the `-wG a:b HEAD:blob` cluster their walker exists for; 3536 unit tests and
every integration suite green; clippy clean.

develop's `show_positionals` carries a `TODO(after #3681)` to replace its
hand-rolled short-cluster walk with the ValueSpec factorization. Left alone
deliberately -- that is follow-up on develop, as its author intended, not
something to change inside this merge.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-12 22:49:00 +02:00
Ilia Alshanetsky ed8480f3e2 fix(read): make head/tail rewrites faithful to the native commands
The hook rewrites `head -N FILE` to `rtk read FILE --max-lines N`, but
`--max-lines` routes through smart_truncate, which keeps a non-important
line only while kept_lines < max_lines / 2. Every rewritten `head -N`
therefore showed about half the requested lines, and `head -1` showed
none at all. Bare `head FILE` rewrote to an unbounded read of the whole
file, which a test asserted as intended.

Add `--head-lines N` for an exact first-N-lines window and point the
head rewrites at it, leaving `--max-lines` preview semantics unchanged
for existing callers. Both windows now slice on byte offsets at the Nth
newline instead of round-tripping through lines(), so CRLF endings and
an unterminated final line survive. The shipped `--tail-lines` path had
the same normalization loss. `--max-lines 0` returned a marker with no
content and underflowed max_lines - 1 on usize; it now returns empty,
matching `--tail-lines 0`.

Gate the rewrites on is_single_file_operand, an allowlist of characters
that cannot change an operand's word count or turn it into an option. A
whitespace-delimited token is not a shell operand: `head -n 1 *.rs`
expanded to sixteen files and lost the `==> name <==` banners,
`head -n 1 --help` printed rtk's own help, and a leading `#` opened a
comment that swallowed the appended flags. Uncertain operands stay with
the native binary, which costs coverage on quoted literals such as
'literal*.txt' and keeps behavior correct.

Separate a stripped trailing redirect from the appended flag value.
`head -n 1 a>b` produced `--head-lines 1>b`, which the shell reads as an
fd-1 redirect, leaving the flag without a value and the redirect target
empty.
2026-09-08 10:31:59 -04:00
Nicolas Le CamandClaude Opus 5 72722904a4 test(git): pin the diff/show/log routing against real git
Four behaviours that fuzzing found and that unit tests over the predicates
could not have caught, because each is about which git child RTK believes
rather than about how one flag classifies: the error `git diff -Uabc
nonexistent-ref` reports, the body surviving `--color` in all three
spellings plus the `color.ui` config form, the log limit announcing itself
only when it took something, and `--quiet` losing to a patch request from
either side while `-s` folds in order.

They run against the real binary in a temp repo with LC_ALL=C pinned, in
CI rather than behind #[ignore], because every one of them was a regression
that the suite as it stood reported as green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:24:50 +02:00
Nicolas Le CamandClaude Opus 5 f126a11f3d fix(git): --quiet is not a third spelling of -s in git show
Found by fuzzing `show` against real git rather than reasoning about it:
`git show -p --quiet` and `git show --quiet -p` both print the patch, so
`--quiet` loses to a patch request from either side. `-s` and `--no-patch`
do play last-flag-wins -- `show -s -p` prints the diff and `show -p -s` does
not -- and modelling all three as one group dropped a patch the user had
asked for, silently, because never_worse then kept the smaller summary.

The two rules are now separate: `-s`/`--no-patch` fold in order against a
patch request, and `--quiet` suppresses only when nothing else asked for
output. Thirteen rows measured against git 2.53 pin the difference,
including the mixed spellings (`--quiet -s -p` prints, `-p -s --quiet` does
not) where the two rules meet.

`run_diff` is unaffected: `--quiet` takes its raw route there, before any of
this is consulted, because in `diff` it really does mean no output plus a
non-zero exit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:23:18 +02:00
Nicolas Le CamandClaude Opus 5 4a2e58d423 fix(git): let the user's own command be the one that reports
Three from the latest fuzz batch, all in `run_diff`/`run_log`'s handling of
the children RTK runs alongside the user's command.

`git diff` ran its stat probe first and let that probe report failure. The
probe runs with the patch-shape flags stripped, so it answers a different
command than the one that was typed: `git diff -Uabc nonexistent-ref` is
`error: --unified expects a numerical value` (129) to git, and the stripped
probe reported `ambiguous argument` (128) instead. The user's own arguments
now run first and their result is the verdict; the probe is decoration, and
a failure there costs the header rather than the command.

The `[rtk] showing 10 commits` notice announced a truncation that had not
happened -- on a two-commit repo, and ahead of commands git then rejected
outright. When the limit applies the output is bounded by it, so that run is
captured rather than streamed and the notice is printed afterwards, only if
git really produced the full limit, and never when git failed. A non-default
`--format` makes the count unreadable; RTK then says nothing rather than
guessing.

Colour is stripped before the diff compaction parses it. `--color` re-shapes
the very columns the compaction keys on -- the escape sits at column 0, so
`diff --git` and `@@` never match and the body came back empty. RTK renders
its own output, so the colour was never going to survive compaction anyway.
This was reachable on develop for `--color` alone and became reachable for
`--color --unified=0` once `--unified` stopped taking the raw route; the
strip covers both, plus the `color.ui = always` config form that no argument
inspection could have caught (rtk-ai/rtk#3842).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:18:04 +02:00
Nicolas Le CamandClaude Opus 5 1b331545fb fix(git): stop the log limit and the body suppressor overreaching
Two consequences of earlier fixes on this branch, both caught by fuzzing
`log` and `show` against raw git.

The raw-shape `git log` passthrough capped every walk at 10, including one
the user had already bounded: `git log -p HEAD~15..HEAD` came back with 10
of the 15 commits it named. The cap exists because that route streams
straight to the terminal and an unbounded patch request printed the entire
history, so it stays -- but a revision range is an exact bound the user
chose, and it is now left alone. When the cap does apply it says so on
stderr, since there is no footer or tee on that path to notice the missing
commits from.

`run_show` read `-s`/`--no-patch`/`--quiet` as an order-independent "any",
where git resolves them against `-p`/`--patch`/`-U<n>` by last flag wins:
`git show -s -p` prints the diff and `git show -p -s` does not (git 2.53).
A patch requested last was therefore swallowed, and never_worse kept the
smaller summary, so it vanished without trace. `emits_word_diff` in the
same file already modelled this correctly.

`git show --oneline` no longer prints its summary line twice. The stat step
passes `--pretty=format:` to suppress the commit header, and the user's
`--oneline` outranked it by the same last-wins rule, so that step reprinted
the header the summary step had already produced. The step drops `--oneline`
from what it forwards rather than appending its own flag afterwards: past a
user `--` that flag would be a pathspec, which is the failure this branch
exists to prevent -- and an integration test caught the first attempt doing
exactly that.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 b6755bf4a2 fix(git,search,go,dotnet): adapt the consumers tuned to the old parse
A fuzz batch against raw git and develop caught five places where the
tokenizer is now right and the code reading it still assumed the old,
looser parse.

`diff` and `show` reported success for commands git refuses. Both run git
twice, and the stat probe runs with the patch-shape flags stripped, so it
succeeds on input the real command rejects -- `git diff -Uabc` exits 129,
`git show -pq` exits 128, and RTK compacted the empty result into a tidy
diffstat and exit 0. The child that runs the user's arguments verbatim is
git's actual verdict on the command, so its failure now propagates with its
stderr. This is also the `run_diff` half of #3843.

`--line-prefix` joins the shapes RTK cannot represent. It prefixes every
output line, the `diff --git` and `@@` markers included, so the compaction
matched nothing and printed a stat header over an empty `Changes:` section.
The attached spelling did this on develop too; the separate spelling only
started once the value was correctly linked to its flag rather than read as
a flag of its own.

grep's `-T`/`--initial-tab` joins them for the same reason: it pads and tabs
every match line, so RTK's forced `-H --null -n` parse read nothing back and
leaked the injected flags, a raw NUL included, into the output. The long
spelling did this on develop; the short one was reachable only once `-T`
stopped being treated as ripgrep's value-taking `--type-not` for grep too.

`checkout -B` claimed the branch name from the arguments *before* reading
what git said, so a created branch lost its `(new)` marker. `-B` creates or
resets and only git knows which, so the arguments are the fallback for when
the English scan misses -- never a short-circuit past it. Reading the glued
`-Bfoo` correctly is what made this reachable; the string scan it replaced
could not see the flag at all.

golangci-lint's value-taking short flags are solo-only. Cobra rejects a
value-taking shorthand inside a cluster ("unknown shorthand flag: 'c' in
-c", 2.13.1), so reading `-Egosec`'s trailing `c` as `--config` swallowed
`run`, and losing the subcommand lost every filter that depends on finding
it. `ValueSpec::solo_only` already expressed exactly this for `git log -n`.

`--results-directory` past the `--` is read per runner mode. In MTP bridge
mode the runner reads its own copy from there and that is where the TRX
lands; in Classic the flag belongs to the test app and dotnet writes to
./TestResults regardless. Reading it as dotnet's own in Classic suppressed
RTK's injection, so the TRX RTK itself asked for by injecting `--logger trx`
was left behind in the user's project, unclaimed and never cleaned up --
measured against a real SDK 9. Both lookups share one scope rule, since
scoping only the presence check would splice the app's path into dotnet's
own arguments; the runner mode is now resolved once instead of per consumer,
which also drops a duplicate filesystem walk.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 63da972432 style: name each predicate after the grammar it encodes, not the file
`golangci_takes_value` is not golangci's grammar -- it is the global one, the
flags valid before a subcommand, with `golangci_run_takes_value` alongside it
for `run`'s. The module prefix said the wrong thing and repeated the file name,
so they become `global_takes_value` and `run_takes_value`, matching how git.rs
names its per-subcommand grammars. `is_golangci_subcommand` loses the same
redundant prefix and now reads like its neighbour `find_subcommand_index`.

`bare_double_dash_flag` sat unprefixed between five `dotnet_*` token lookups
doing the same job; it joins them as `dotnet_has_bare_double_dash_flag`,
matching `dotnet_has_bare_loose_flag` directly above it.

Naming is per family, not per file: dotnet's `has_*_arg` feature detectors and
search's `is_*_token` flag classifiers are each internally consistent and stay
as they are.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 eec9f33986 refactor(core): one value spec per flag instead of three predicates
The tokenizer was asking three questions about the same key, `(TokenKind,
flag name)`, through three predicates: `takes_value`, `takes_separate_value`
and `claims_literal_dash_dash`. `search.rs` passed the same function for two
of them and `git.rs` kept `log_takes_separate_value`/`diff_takes_separate_value`
as second tables beside `log_takes_value` -- the two-lists-drift shape this
branch already fixed for `requests_diff_show_raw_shape` and for golangci's
output-flag list, reintroduced at the API level because a `bool` cannot carry
the answer.

`takes_value` now returns `Option<ValueSpec>`. `Attachment` says how the value
attaches (`AttachedOnly` for git's `-M`/`-U`/`-C`/`-B`, which take an optional
attached number and never the next token; `solo_only` for `-n`, which takes a
separate value only when it is the whole argument) and `claims_dash_dash` says
whether a literal `--` may be the value -- a per-tool split, since grep and rg
swallow it where git and cargo reject it. Each is stated once, per flag, in the
one table that already had to exist.

`AttachedOnly` now also applies to long flags, which the old
`takes_separate_value` could not express -- it was consulted only in the
short-cluster arm. Nothing needs it yet; it is tested rather than left as a
silent gap.

git's log and diff grammars become two predicates instead of one shared list
plus two exception tables, which is what the one-grammar-per-subcommand rule
asks for: they share the long flags all three subcommands parse the same way
and each states its own short grammar, where `-l` is log's solo-only limit and
diff's clustering rename limit.

Two entry points, split by whether the caller has a grammar at all rather than
by dialect: `tokenize(args)` for the callers asking only which arguments are
flags and where `--` is, and `tokenize_grammar(args, takes_value, dialect)` for
the rest. The five structural call sites no longer pass a `|_, _| None` closure
to say they have no flags with values, and `TokenizeOptions` is gone with the
predicates that motivated it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 7931993da8 fix(git,search,dotnet): correct the flag classes the last round got wrong
`-W`/`--function-context` does not make `git log` emit a patch -- checked
against git 2.53, where it is byte-identical to plain log -- so routing it raw
turned `rtk git log -W` into a 1 MB unfiltered dump of the whole history. The
flags that *do* imply a patch there are `-U<n>` and the combined-diff forms
`--cc`/`-c`/`--remerge-diff`, whose patch the log compaction was discarding
with no tee to recover it from.

That raw route is `run_passthrough`, which streams straight to the terminal, so
RTK's default limit has to be in the args or it never applies at all: every one
of those spellings printed the entire history, 411k lines against 50 for plain
`rtk git log`. It now carries `-10` whenever the user named no limit of their
own -- the limit only, since `--no-merges` would gut `--cc`/`-c`, whose whole
purpose is the merge diff.

`--exit-code` and `--quiet` are `diff`'s, not `log`'s. Both leave `git log`'s
output byte-identical to plain log, so there is no shape for it to escape to,
and claiming them cost the whole history for nothing. In `diff` they do earn
the raw route: the body is replaced by a report and git exits non-zero, which
RTK's stat probe inherited, its early return on failure then throwing the
entire diff away. They join `--check`, whose handling already existed for the
same reason.

`--quiet` then splits `diff` from `show`, so each states its own raw-output
grammar rather than sharing one. In `show` it is a synonym of `-s` -- exit 0,
body suppressed -- so it belongs on the compact path with `-s`/`--no-patch`,
where the summary is exactly what it asks for; claiming it raw-passed the very
header its synonyms compact.

That split's short-flag rule holds for `-p`/`-u`/`-U`, which only restate
`diff`/`show`'s patch default, but not for `-c`: it is `--cc`'s combined-diff
form, and `compact_diff` reads a combined diff's two marker columns as one, so
`git show -c` on a merge came back as `+54 -8` against git's own 156
insertions and 0 deletions. It takes the raw route its long form already took.

`--diff-merges=<format>` names those same shapes a second way, so it routes on
the format rather than on the flag: every value but `off`/`none` emits a patch,
which `log` cannot compact, while only `c`/`cc`/`combined`/`dense-combined`
produce the two marker columns, which is all `show` needs the raw route for.
Both value spellings count -- git takes the format attached or as the next
token, and `git log --diff-merges c` is accepted.

`--unified=5` and `-U5` are one option and now take one path.

`run_show`'s format gate keeps `--oneline` out, unlike `run_log`'s: there the
gate routes the whole command to a raw passthrough, and `--oneline` only means
the user's one-line summary outranks RTK's own one-line summary. Claiming it
gave up compaction entirely to fix that -- 116 KB against 31 KB on a real
commit, on the one metric this tool exists for.

`git worktree`'s write actions compact to "ok" again unless the user asked for
a report with `--dry-run`/`-n` or `--verbose`/`-v`. Keeping every non-empty
report was meant for `prune --dry-run`, whose list is the point of the command,
but `add` also speaks on success: its two progress lines came back instead of
"ok", and in the wrong order, since one is on stdout and the other on stderr.

search: the `=`-unwrapping applies to the attached spelling only. Applied to a
separate-token value it ate the first character of the user's pattern, so
`rtk rg -e '=='` searched for `=` and matched lines the real command does not.
And the filename negation is engine-specific in both directions -- grep's `-h`
is `--no-filename` where rg's is `--help`, and rg's `-I` is `--no-filename`
where grep's is `--binary-files` -- so rg's spelling was forwarded, beat RTK's
`--with-filename`, and ran the whole search a second time. `-N` and
`--no-line-number` are ripgrep's alone for the same reason: grep 3.12 exits 2
on both, so recognising them there reported a match for a command the engine
refuses to run.

Recursion is not a filename request. `-r`/`-R`/`--recursive` shared the
last-spelling-wins slot with `-H`/`-h`, which made the result depend on typing
order -- `grep -rh` dropped the prefix and `grep -hr` kept it, where real grep
drops it either way, because `-r` only makes the search span several files.
It now feeds the fallback that the paths already feed, and only `-H`/`-h`
override.

dotnet: the `-l` alias is single-dash only. `--l` is not a spelling dotnet
accepts, so treating it as the logger suppressed RTK's injection for a command
that then wrote no TRX at all.

Two tests were asserting less than they appeared to: the stdin fixture lived
inside the directory being searched, so an engine that ignored stdin and walked
the cwd still produced the asserted line, and the blob-show test built its
tokens with log's grammar where `run_show` uses diff's.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 e622c2e4b3 fix(dotnet,go,search): make the probes and lists say what they mean
`detect_test_runner_mode_in_dir`'s `scan_dir` promised tests an isolated
directory but only the project scan honoured it: the `global.json` and
`Directory.Build.props` walks still started from the real process cwd, so six
tests that pass a tempdir were decided by whatever the developer's checkout sat
under. All three probes start from `scan_dir` now, with a test that puts a
`global.json` above the scanned directory.

golangci listed the nine `--output.<format>.path` sinks twice, in the
value-taking predicate and again in the collision check, with nothing tying
them together; there is one list now, read by both.

Three comments were describing something other than the code: dotnet's
value-taking table called itself "not exhaustive" while the project scan
documented that it *required* exhaustiveness (it does not -- the extension
filter exists for exactly that reason); `has_trx_logger_arg`'s scoping now
carries the evidence for why it differs from its neighbours (`dotnet test
--help`: arguments after `--` go "to the application that is being run"); and
`stash_show_wants_patch`'s "nothing takes a value" predicate is git's actual
grammar for that question, not a placeholder.

`has_format_flag` goes through the module's shared tokenizer, so it cannot
classify an argument differently from `extract_pattern_path`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 04001e086c fix(search,git,go): honour the engines' own flag arbitration
Both engines settle `-h`/`-H` and `-n`/`-N` by last-one-wins; RTK's negation
was an unconditional veto, so `grep TODO -h -H a.txt b.txt` printed bare lines
where grep prints the filenames. DetectedFlags now records which spelling came
last, `None` meaning the user said neither and the paths decide. `-N` joins
`-h` in not being forwarded, for the same reason: RTK forces `-nH` to parse the
output, and the user's negation would win and leave nothing parseable.

`-e=PAT` gets the same `=`-unwrapping every other rg short flag already got, so
the pattern is no longer searched for with a literal `=`.

golangci: the json sink collides wherever it points -- one path per format --
while another format's *file* sink does not, so `--output.json.path /tmp/r.json`
suppresses RTK's injection again and `--output.text.path /tmp/r.txt` no longer
does.

git, all checked against 2.53 rather than assumed: `--binary` re-enables the
patch past `--no-patch --stat`, and a binary patch is meant to be fed back to
`git apply`, so it takes the raw route; `-W`/`--function-context` does *not*
re-enable it and is left alone; `-U<n>`/`-W` make `git log` emit a patch the
one-line compaction cannot represent, and `--compact-summary` left an empty
"Changes:" section, so both take the raw route too. `git show`'s diff step
keeps the user's `-U5`, which sets the context width of the very patch RTK is
about to compact -- stripping it there cost the user the context they asked
for. And a `worktree` write action that reported something keeps its report:
`prune --dry-run` names the worktrees it would remove, on stderr, and that list
is the entire point of the command.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 e507aa50d9 refactor(search): one tokenizer entry point for the module
`run()`'s pre-checks tokenized with plain `tokenize` while `extract_pattern_path`
used `claims_literal_dash_dash`, so the two could disagree about whether a `--`
belonged to a flag -- and the args were tokenized twice per invocation either
way. Both go through `tokenize_search_args` now.

Also drops a `let args = args.clone()` left behind when the restore moved to the
top of `run()`: a full copy of the argument vector on every `rtk grep`/`rtk rg`,
under a comment describing a restore that no longer happened there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 0907594978 fix(git,search,go): drop the header's rival flags instead of outranking them
The insert point added last round tried to place RTK's `--no-patch --stat`
where it would win git's last-one-wins rule. It could not: git accepts options
after a revision, so `git diff HEAD~1 -p` still outranked it, and splicing at
the first free positional broke two other things. `rtk git diff -pl 100` died
with `fatal: ambiguous argument '100'` because every short flag in a cluster
shares one source_index, so dropping the arg took `-l` with it; and
`rtk git diff --max-age N` died with `fatal: '--no-patch': not a number of
seconds since epoch`, because a value-taking flag missing from the table left
its value looking like a positional and RTK spliced its own flags in between.

So the header goes back in front, and the user's patch-shape flags are removed
from it instead -- rebuilt per token, so `-pl 100` keeps its `-l`. With nothing
left to outrank, position stops mattering and a gap in the table is harmless
again. `--max-age`/`--min-age` are added regardless, and the insert point is
gone.

`git show -s` printed the diffstat it exists to suppress: run_show never
consulted suppresses_diff_body, and moving RTK's `--stat` in front let it win.
It now prints the summary and stops, as git does.

golangci: only a sink pointing at **stdout** collides with RTK's own, so
`--output.text.path /tmp/report.txt` gets RTK's JSON injected alongside it
again rather than leaving nothing to parse. The nine sink names are enumerated
rather than prefix-matched, per this PR's own rule 6.

search: `-h`/`--no-filename` is honoured when printing instead of being
forwarded -- as the later flag it beat RTK's forced `-H`, every line failed the
NUL parse, and the entire search ran a second time (verified: one engine exec
now, two before). A value-taking flag left without its value hands the command
over untouched, so `grep --regexp` keeps its own "requires an argument" error
instead of succeeding silently. And rg's `-A=1` is unwrapped where rg would
unwrap it; GNU grep rejects that spelling, so its args are left alone.

Refuted against a real .NET 9 SDK rather than changed: `dotnet test`'s `-r` is
`--runtime`, not `--results-directory`, and `--`'s payload goes "to the
application that is being run", so a forwarded `--logger trx` is not dotnet's
logger and RTK still has to inject its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 6fcd48928c fix(git,dotnet,search): scope each rule to the grammar that owns it
A review round found the previous two batches over-applied two ideas.

**`--` is not a boundary for every lookup.** Scoping all of dotnet's to the
region dotnet parses broke the ones whose flag legitimately lives past it: the
runner's `--results-directory` is where the TRX actually lands, a `-bl` past
`--` is still the binlog that gets written, and `--write` is RTK's own
pseudo-flag with no dotnet counterpart at all -- so `dotnet format -- --write`
ran check mode and handed dotnet an unknown flag. Those three read the whole
command line again; `--logger`/`-nologo`, whose forwarded spelling belongs to
the MTP runner, stay scoped.

**One grammar per subcommand, including diff vs log.** `-l` clusters in
`git diff` (rename limit) but not in `git log`, so `git diff -wl 100` had its
100 read as a pathspec; diff/show now tokenize with their own predicate. Two
options git's completion helper lists as value-taking were missing entirely --
`--ignore-matching-lines` and `--stat-graph-width` -- so RTK spliced its header
flags between flag and value and git answered `fatal: bad revision '^#'`. And
`-s`/`--no-patch` ask diff for no body but ask show for the commit summary,
which is exactly what the compact form prints: routing show through raw cost
every byte of that saving.

The header could not win by position either -- git accepts options after a
revision, so `git diff HEAD~1 -p` outranked it and RTK printed the patch raw
and then again compacted, 1.8x the raw output. It drops the user's patch flags
instead of trying to outrank them.

Also: passthrough prints stdout verbatim before checking the exit code, since
`--check`'s report *is* trailing whitespace and it exits 2; `git add --` shows
git's own "nothing added" hint rather than nothing at all; `git stash show --`
decides on the output it got, because any extra argument flips git to a patch;
`worktree` compacts only a bare list, gives write actions the terse ok, and
passes everything else -- `repair`, `list --porcelain` -- through verbatim;
`checkout` runs in the user's locale again, per git_cmd_c_locale's own
contract, since the args-based fallback already names the branch; rg's `-0` is
`--null`, not grep's `-NUM` context shorthand; and `--no-compact=1` is stripped
rather than leaked to git.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 3606e631a4 fix(go,git,arg_tokenizer): close the last three from the review round
golangci-lint 2.x has one `--output.<format>.path` per format, but RTK only
recognized `output.json.path` and `out-format`, so a user asking for text
output got RTK's JSON sink added alongside it -- two reports on stdout, and the
JSON parse then fails on whichever lands first. Any output destination counts
now. Its value-taking list also grew the flags a real `golangci-lint run
--help` lists (2.13.1) plus the 1.x ones RTK still supports: `--concurrency`,
`-e`/`--exclude`, `-p`/`--presets`, `--skip-dirs`, `--skip-files`,
`--deadline`. Missing them made `run -e '--out-format'` read the exclude
pattern as an output flag and skip RTK's injection entirely.

`git show` prepended its own shape flags, so a user `-p`/`-u`/`--patch`/`-U5`
won last and re-enabled the patch in the summary and stat steps -- the result
stopped being smaller than raw and never_worse discarded it, returning the full
commit after four git subprocesses. They go where git still reads them and
after the user's own now, the same placement run_diff uses: `git show -p` on a
real commit is 25kB instead of 52kB.

`Token::value` indexed `tokens[idx]` unchecked, which only held because every
caller happened to pass the whole vec -- `before_dashdash` now hands out slices
routinely, and a panic inside a filter is the one thing RTK must never do. It
also answered a consumed positional with the *name* of the flag that consumed
it; that direction of `linked` means "my owner", not "my value".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 702d3d7889 fix(git,search): flags whose value or meaning the old scans got wrong
`--min-parents=N` only counted as "the user wants merges" for exactly N=2, so
`git log --min-parents=3` collected RTK's `--no-merges` too and the two
constraints selected nothing -- an octopus merge that real git prints came back
empty.

`git checkout` parses its own success message, so it now runs in the C locale
like RTK's other parses do: in any other language the scan missed and RTK
reported whatever argument came first, which for `git checkout -` was the
literal `-`. That argument is also skipped now -- `-` is git's "the branch I
was on", not a name to echo. And `--conflict`/`--pathspec-from-file` join the
value-taking set (git 2.53 answers "requires a value" for both), so their
values stop being reported as the branch.

search's `--version`/`--help` short-circuit was the one `--`-blind scan left in
the file: `rtk grep -- --version f.txt` printed grep's banner instead of
searching for that string, and `rtk grep -- -h f.txt` found nothing. It reads
tokens before the boundary now, and knows `-h` is rg's help but grep's
--no-filename. The restore moved to the top of `run()`, since every check below
it classifies these args.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 056c391929 fix(git,search): repair the regressions the last round introduced
`git diff <pathspec>` died outright: the stat header spliced `--no-patch
--stat` at the `--` boundary, which is args.len() when there is none, so git
saw an option after a non-option argument and refused the whole command. The
insert point now stops at the first positional too -- a git rule, not a shared
one, so it lives in git.rs rather than being forced on dotnet, whose own test
caught me doing exactly that.

That same header overrode flags whose entire job is to suppress the diff body:
`git diff --check` reported a diffstat and exit 0 where git reports whitespace
errors and exit 2. `--check`/`-s`/`--no-patch` now take the passthrough path,
which in turn had to stop discarding stdout on a non-zero exit -- `--check`
prints its report and *then* exits 2.

Three more from the same batch: stripping `--no-compact` by a single index
leaked the second copy of a repeated flag to git; ignoring `--` only when it
was the sole token dropped `git status -sb --` off the compact path; and
`git worktree -- add x` answered with a worktree list where real git errors.

`paths.is_empty()` meant "the engine walked the cwd" for rg but "read stdin"
for grep, so grep prefixed every match with `(standard input):` whenever stdin
was a terminal. The new stdin tests also guard on the engine they drive, the
convention the other search integration tests document.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 66901427f0 docs: require arg_tokenizer for new commands, flags and arg fixes
The module landed with no statement of when to use it, so the next command or
flag can still be written with a string scan -- which is how every bug this
migration fixed got in.

States the rule where each audience meets it: the non-negotiable list agents
load (`.claude/rules/rust-patterns.md`), the checklist for adding a filter
(`src/cmds/README.md`), and the architecture map (`ARCHITECTURE.md`), all
pointing at one place -- `src/core/README.md` -- for the four rules the
migration paid for: one grammar per subcommand, scope the lookup to the region
the tool parses, inject before the boundary, detect and act with one rule.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 f897c7bca8 fix: scope every flag lookup to the region the tool actually parses
A review round found the same defect wearing four different shapes, so the
fixes are structural rather than per-site.

The tool's own args end at `--`. Msbuild keeps classifying past the boundary
because it forwards arguments, so every dotnet lookup read what the user meant
for the test runner: `dotnet test -- --logger trx` suppressed RTK's own logger
injection and `dotnet build -- -bl` its binlog. `before_dashdash` now scopes
the five dotnet lookup primitives at once, and `--report-trx` -- legitimate in
either region -- says so where it reads both.

Injected flags belong before that boundary too. `dotnet format -- ./src` put
`--verify-no-changes` after it, where dotnet parks it unread: format rewrote
the tree while RTK reported check mode. `git diff --stat` had the same shape.
Both go through `injection_point` now.

Detection and the action on it have to share one rule. `--no-compact` was
detected as a token and stripped as a string, deleting a pathspec of that name;
`--write` was detected bare-and-unforwarded but stripped everywhere. They now
strip the tokens detection actually saw.

`stash` broke restore_double_dash's precondition: clap carves its subcommand
out of the same trailing region, so restoring from the remainder sliced one
token short -- `git stash -- -p` ran an interactive `push -p` where real git
errors on the pathspec. The region is reassembled before restoring.

Also from the round, each verified against the real tool: `-f`/`--file`
supplies patterns like `-e`, so `grep -f pats.txt a.txt` no longer answers "no
matches" (or hangs) by stealing the path as the pattern; grep's `-NUM` is
`--context=NUM`, so its blocks keep their `--` separators; a single matching
file found by walking the cwd keeps its name, as real rg prints it; `git diff
-p` stopped printing the patch raw and then again compacted, 2.4x the raw
output; `/Other.csproj` is a path, not an MSBuild switch, so it no longer
adopts an unrelated project's runner mode; and `/l:trx` is MSBuild's logger
assembly, not dotnet's `--logger`, which the tokenizer now records as
`Token::slash`.

git's remaining string-scanning handlers move to the tokenizer with the rest:
`git status --` keeps its compact path, a blob spec is a free positional rather
than any arg containing a colon, and a worktree action is the subcommand rather
than any arg spelling one.

The two stdin regressions move to tests/ where CI actually runs them -- they
were `#[ignore]`d, and CI never passes `--ignored` -- and the show_line/context
tests now drive the production detector instead of test-only twins of it, which
let a deleted production arm stay green. The twins are gone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 92c6755315 fix(git): tokenize emits_word_diff instead of scanning raw args
develop's emits_word_diff scans the raw args, so a --word-diff that git itself
never reads as a word diff request still forces passthrough. Confirmed against
git 2.53.0: `git diff --author --word-diff` emits an ordinary line diff (the
flag is --author's value) and `git diff -- --word-diff` treats it as a
pathspec; both lost RTK's compaction.

Takes tokens now, so both cases classify the way git parses them. `git stash
show` passes log's grammar rather than stash_show_wants_patch's: it parses
-p/-u itself but hands the rest to the revision machinery, which does consume
a following --word-diff as --author's value.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 ddff880a95 refactor: trim comment bloat across arg_tokenizer.rs and its callers
Per review feedback: many doc comments in this branch had grown longer
than the code they documented, narrating investigation history
("confirmed via Docker/real git X.Y.Z", commit hashes, issue numbers)
instead of stating the non-obvious fact a reader actually needs, or
simply restating what a well-named function/type already says.

Trimmed every multi-paragraph comment across the 5 files this branch
touches down to 1-2 lines, keeping only the load-bearing why. Also:

- dropped comments that only restated a well-named call
  (restore_double_dash, dotnet_takes_value's Dialect::Msbuild) or a
  callee's own doc (run_diff/run_show's tokenize call sites duplicated
  requests_diff_show_raw_shape's rationale)
- renamed git_log_tokens/dotnet_tokens to tokenize_git_log_args/
  tokenize_dotnet_args so the call site reads as an action without
  needing a comment
- trimmed several "Regression: X used to..." test comments down to
  the bare invariant under test
- documented the tokenizer's design in src/core/README.md, kept light
  (no consumer list, no bug writeup, just the rule and one example)

Comment-line counts in the diff against develop: from roughly 18% of
added lines down to ~16%. No logic changes anywhere in this commit:
comments, blank lines, and two function renames only, verified via
cargo fmt/clippy/test after every step.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 88d6785b02 docs(core): document arg_tokenizer.rs and the per-subcommand grammar rule
Reviewer asked that this system be documented in the relevant
READMEs. Adds an Argument Tokenizer section to src/core/README.md
covering what the module provides and the design rule two confirmed
bugs this round came from: never reuse a sibling command's grammar
predicate wholesale (stash_show_wants_patch's -u/-p conflation,
requests_diff_show_raw_shape's list-drift). Cross-links from
src/cmds/git/README.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 a0e55f572a fix(search): route on whether the engine reads stdin, not on a terminal check
`!is_terminal()` treats any redirect as "the engine reads stdin", but real grep
and rg only read it when it is a regular file, FIFO or socket -- with
`< /dev/null` (a character device) both search the cwd instead. RTK took the
streaming path there, which cannot know it is searching several files, so
filenames were stripped: `rtk rg -z foo < /dev/null` in a 4-file directory lost
every prefix that develop and real rg both print.

Matches ripgrep's own is_readable_stdin rule, so a `< file.log` redirect still
streams and a `< /dev/null` one groups by file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 2c21662456 fix(search): let grep/rg value-taking flags claim a literal -- as their value
grep -e -- f (and any other value-taking grep/rg flag followed by a
literal --) was misparsed: the tokenizer's -- boundary guard is correct
for git/cargo, which always reject -- as a pending value, but grep/rg
both consume -- unconditionally as any value-taking flag's value
(confirmed for -A/-m/-e/--context/--file across both engines). RTK
treated -- as the end-of-options boundary instead, so `rtk grep -e --
f` searched for pattern "f" in /dev/null instead of "--" in file "f".

Adds Scanner::claims_literal_dash_dash, exposed as an opt-in field on
a new TokenizeOptions passed to tokenize_with_options -- defaults to
false everywhere except search.rs, which reuses its own takes_value
predicate for it. Folds the now-redundant tokenize_dialect and
tokenize_with_separate_value into the same options struct so the
module doesn't keep growing one wrapper function per axis.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f29760b2e2 fix(git): stop stash_show_wants_patch from treating -u as patch mode
-u means --include-untracked for git stash show, not -p (unlike git
log, where -u is a -p synonym). Conflating them routed -u's stat-only
output through compact_diff, which only renders patch content,
producing silently empty output where a stat summary was expected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 79f71fa1df fix(git): stop stash_show_wants_patch from swallowing -p as a log-only option's value
stash_show_wants_patch reused git log's separate-value grammar
(log_takes_value/log_takes_separate_value), under which --author is a
value-taking Long flag. git stash show's real grammar is much
narrower ([-u] <diff-options> [<stash>]) and doesn't recognize
--author at all -- confirmed against real git 2.53.0 that
`git stash show --author -p` produces full patch output, since
--author consumes no value there. The old code swallowed the
following -p as --author's value, causing patch content to render
through the stat-only compact_stash_stat path instead of compact_diff.

Now tokenizes with a predicate that never treats any flag as taking a
separate value, since this detector only needs to spot a bare
-p/-u/--patch token -- that can only ever false-positive, never
silently swallow a real one.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 0a32e22951 refactor(git): delegate requests_diff_show_raw_shape to requests_raw_diff_shape
Was duplicating requests_raw_diff_shape's Long-flag list verbatim
(minus "patch") instead of delegating and excluding the patch-only
cases. Same list-drift pattern that already caused the git diff -p/
git show -p regression fixed by 7533879 -- delegating rules out the
two lists silently diverging again.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 210d67f953 fix(dotnet): reject attached-value spellings in has_report_trx_arg
--report-trx is a pure boolean flag, same class as --write/--nologo
(already fixed earlier in this branch). The non-bare dotnet_has_flag
lookup let a broken spelling like --report-trx:true count as "already
present," skipping RTK's own injection while still forwarding the
unrecognized flag straight through to real dotnet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 9b40423edc refactor(arg_tokenizer): rename tokenize_git to tokenize_with_separate_value
tokenize_git had exactly one caller in the whole codebase (git.rs's own
git_log_tokens()), and zero git-specific code -- it's a thin wrapper fixing
Dialect::Posix while leaving takes_separate_value customizable, reusable by
any POSIX-ish tool with the same short-flag clustering quirk. Naming a
shared, mechanism-generic function after its only current caller was
misleading: either it should generalize (drop the git-specific name) or it
should live in git-specific code. Since the git-specific rationale (the
-n/-M-family rules) was already documented at git.rs's own
log_takes_separate_value, not lost by renaming, generalizing was the smaller
change.

Trimmed the moved function's doc comment down to the general mechanism,
pointing to log_takes_separate_value for the git-specific quirks it
originally listed inline. Pure rename, no behavior change: cargo test --all
passes the same 2765 tests before and after.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 8b2b18affd fix(dotnet): fix Windows CI unused-import/dead-code in dotnet_double_dash_test.rs
The test itself is #[cfg(unix)] (it spawns a /bin/sh stub using unix file
permissions), but its Command import and shell_quote helper weren't gated
the same way -- on Windows the test compiled out entirely, leaving both
genuinely unused and tripping -D unused-imports / -D dead-code.

Nest both inside the test function's body instead of gating them separately:
since the whole function is already #[cfg(unix)], that one attribute now
covers everything, and Linux/macOS behavior is unaffected (cargo test --all
still passes the same 2765 tests).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 25d0de6263 refactor(arg_tokenizer): share one token() constructor across construction sites
The DashDash, digit-run Short, and cluster-loop Short token pushes each
hand-built a full Token{...} struct literal instead of reusing the
positional()-style constructor already used elsewhere in the same function
(and push_atomic_flag's Long push did the same). Token gaining a new field
later -- a growth pattern this module's own docs already anticipate, citing
takes_separate_value as precedent -- meant updating 4 literals instead of 1
call site, with a forgotten field at one of them silently defaulting wrong
instead of failing to compile.

Generalize positional() into token(kind, text, source_index, double_dash),
have positional() call it, and update every other construction site to build
on it via struct-update syntax the same way link_next_value already does on
top of positional(). Pure refactor, no behavior change: cargo test --all
passes the same 2765 tests before and after.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 71fe7645a5 fix(git): stop git diff -p / git show -p from bypassing RTK's compaction
requests_raw_diff_shape's -p/-u/--patch match was correct for run_log (whose
default output has no diff content at all, so an explicit -p is a genuine
request for something the filtered path never produces) but was wrong when
run_diff/run_show started sharing that same predicate this branch: diff/show's
default output already IS patch text, so an explicit -p/-u/--patch is
redundant with the default, not a request for an incompatible shape. Sharing
the full list meant `git diff -p` / `git show -p <rev>` silently skipped
RTK's stat + compacted-diff pipeline and returned full raw output instead --
a real token-savings regression for a very common invocation, caught by
/code-review high with zero test coverage.

Add requests_diff_show_raw_shape, the same shape-flag list minus patch/p/u,
and point run_diff/run_show at it while leaving run_log on the original
requests_raw_diff_shape. --patch-with-raw/--patch-with-stat still trigger the
raw path for diff/show since they mix patch text with a raw/stat format
RTK's own extra --stat step would double up against.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 15b52c7166 fix(search): compute context/show_file/show_line from tokens, not reconstructed strings
has_short_flag scanned the reconstructed flags: Vec<String>, which also
contains value-taking flags' own separate-token values as bare,
unmarked strings alongside real flags -- a value starting with '-' and
containing the queried letter was misread as the real flag (e.g.
`rtk rg --replace '-Chart' pattern src` misdetected a -C context flag
from --replace's own value).

Added DetectedFlags (show_file/show_line/context), computed directly
from token kind/linked in extract_pattern_path's own walk -- the same
technique already used for has_format_flag, extended to cover
has_context_flag/show_file/show_line's letters (H/r/R/n/N/A/B/C) too.
A consumed value token is never examined as a candidate flag at all,
regardless of its text, since it's classified Positional+linked rather
than re-derived from a reconstructed string.

show_file's -r/-R check is engine-aware (only counts for Grep: rg's -r
is --replace, an unrelated value-taking flag, not recursive-descent;
rg has no -R at all), matching the is_format_flag_token/
is_short_value_flag precedent already established for -L/-z/-T/-r
elsewhere in this file.

show_file/show_line/has_context_flag/has_short_flag become
suite unchanged; the now-fully-dead show_file (paths+flags combined)
production wrapper is replaced by wants_show_file (the paths-only half,
combined with DetectedFlags::show_file at each call site) since it had
no direct test callers of its own.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 234e88b359 docs(dotnet): document explicit_projects' filesystem-backstop limitation
explicit_projects has no filesystem backstop and relies entirely on
dotnet_takes_value's allowlist being exhaustive; a real dotnet flag
missing from it (e.g. --property/-p, --collect, --diag, --settings,
--blame, --output/-o, --source, --sln) whose value ends in a project
extension would still be misread as an explicit project path, the same
class of bug three earlier commits in this branch each closed one flag
at a time. Same root cause as arg_tokenizer.rs's Msbuild
single-segment-path limitation (real MSBuild needs a stat() call to
resolve the analogous ambiguity) -- documented as a known, deliberate
tradeoff rather than fixed, since teaching this function to stat()
every candidate would be a materially different, slower design.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f36eff27ff refactor(arg_tokenizer): replace push_atomic_flag's 8 params with a Scanner struct
push_atomic_flag/link_next_value threaded 7-8 positional parameters
(tokens, args, i, dialect, takes_value, takes_separate_value,
emitted_dash_dash) by hand, carrying #[allow(clippy::too_many_arguments)].
Introduced a Scanner<'a, 'p, T> struct grouping this shared scan state,
with push_atomic_flag/link_next_value as &mut self methods.
tokenize_dialect_ex now owns one Scanner instance instead of five loose
local variables threaded through free functions -- a future addition
to the scan state (this module already had to add one,
takes_separate_value) means one new field instead of a parameter
threaded through every helper and call site.

Pure refactor, no behavior change: full test suite (2762 tests) passes
unchanged, clippy is clean with no allow needed anymore. Verified the
one pre-existing --ignored test failure (test_git_status_not_a_repo_exits_nonzero)
is an unrelated, pre-existing locale-dependent flake by reproducing it
identically on the pre-refactor commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 95620f9a46 refactor(golangci): golangci_run_takes_value composes golangci_takes_value
golangci_run_takes_value hand-duplicated golangci_takes_value's 5 flag
names (color/config/cpu-profile-path/mem-profile-path/trace-path)
instead of building on it, even though golangci_takes_value's set is a
strict subset (every pre-run flag is also valid after run). That
duplication is exactly how the "out-format" gap (fixed earlier this
branch) came about -- one list got a new entry, the other didn't. Pure
refactor, behavior-preserving (confirmed by the full existing test
suite, unchanged).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 ead95f1882 refactor(dotnet): dedupe has_nologo_arg/has_write_mode_override's shared predicate
Both hand-rolled the identical "Long flag, no attached value,
case-insensitive name match" shape (differing only in whether
double_dash is required), because neither arg_tokenizer.rs primitive
checks `attached` at all. Factored into dotnet_has_bare_loose_flag/
dotnet_has_bare_double_dash_flag, matching the existing
dotnet_has_loose_flag/dotnet_has_flag naming split.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 35305f1ef3 refactor(git): add git_log_tokens() helper, dedupe 9 tokenize_git call sites
log_takes_value/log_takes_separate_value were passed to tokenize_git
at 9 separate call sites across run_log/run_diff/run_show/run_stash and
their test helpers. Added git_log_tokens(args), mirroring dotnet_cmd.rs's
dotnet_tokens() consolidation, and switched every call site to it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 0008b73ff3 refactor(arg_tokenizer): add dashdash_index()/has_dashdash(), dedupe 4 call sites
Finding the `--` boundary token's position was hand-rolled
independently at dotnet_cmd.rs:713,864 and git.rs:1328,1352. Added
arg_tokenizer::dashdash_index (index into the tokens slice;
tokens[i].source_index recovers the original-args position) and
has_dashdash (presence check), and switched all 4 call sites to them.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 d05a705c9a refactor(arg_tokenizer): add Token::is_free_positional(), dedupe 4 call sites
"Positional kind, and not consumed as some preceding flag's value" was
hand-spelled identically in git.rs (x2), golangci_cmd.rs, search.rs,
and dotnet_cmd.rs. Added Token::is_free_positional() to the shared type
and switched all 5 call sites to it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 7cacddb2f4 refactor(arg_tokenizer): dedupe double-dash-flag predicate; derive seen_dash_dash
- has_double_dash_flag/double_dash_flag_value/double_dash_flag_values
  shared the same 3-part match condition inline three times; factored
  into is_double_dash_flag(). double_dash_flag_value keeps its own
  find() (not double_dash_flag_values().next()) since that would subtly
  change semantics: "first match regardless of whether it has a value"
  vs "first match that has a value".
- seen_dash_dash was always exactly emitted_dash_dash && dialect ==
  Posix (only ever set true immediately after emitted_dash_dash inside
  the Posix branch); removed the redundant variable and derived the
  condition directly. Pure refactor, no behavior change either way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 c108f2491a fix(golangci): add missing out-format to golangci_run_takes_value
golangci_run_takes_value's allowlist omitted "out-format" even though
has_output_flag explicitly checks for it -- its separate-token value
(e.g. `--out-format json`) tokenized independently as an unlinked
Positional instead of being linked, the same bug class already fixed
for --path-prefix and other run-level flags in this same file.
out-format is a v1-only legacy flag (golangci-lint 2.x's --help no
longer lists it), kept for v1 installs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 08ec6ebf44 fix(dotnet): expand dotnet_takes_value, and keep /flag from eating a value
dotnet's `-c`/`-f`/`-r`/`-a`/`-l` and their long forms all take a value;
without them the value tokenizes as a free positional and lands in the
project-path detection. `-l` is also the alias `has_trx_logger_arg` was blind
to, so `dotnet test -l trx` had RTK inject a second trx logger over the user's.

The single letters overlap MSBuild's own switches, which the Msbuild dialect
spells uniformly: `/r` is MSBuild's boolean `restore`, not dotnet's
`-r <rid>`. An MSBuild switch attaches its value with `:` (`/bl:x.binlog`) and
never consumes the next argument, so the tokenizer no longer links one for the
slash spelling -- otherwise `dotnet build /r -bl:my.binlog` hid the user's own
binlog from has_binlog_arg and RTK injected a second `-bl` on top of it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f7bd37468c fix(git): run_stash's patch-mode check needs -- boundary awareness too
run_stash's "show" branch used a raw arg == "-p" scan for patch-mode
detection, the same bug class already fixed for sibling run_log/
run_diff/run_show -- a pathspec literally named "-p" or "--patch" after
`--` was wrongly treated as the real patch flag, routing to compact_diff
instead of RTK's compact_stash_stat summary. Extracted into a testable
stash_show_wants_patch(args) function using tokenize_git +
log_takes_value/log_takes_separate_value, matching only the patch-mode
flags (not the full requests_raw_diff_shape list, since --stat et al.
correctly stay on the compact_stash_stat branch here).

An end-to-end integration test proved impractical: real git's own
`git stash show -- <pathspec>` unconditionally shows full patch content
whenever limited by any pathspec, regardless of -p, so the final git
output can't distinguish flag-vs-pathspec interpretation -- verified
this with a direct git session before settling on a unit-level test
against the extracted predicate instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 2bdea450ae fix(search): make -r value-taking detection engine-aware
is_short_value_flag treated -r as unconditionally boolean, but
confirmed via real rg (`rg -rn hello file` prints "n", `rg -rXXX hello
file` prints "XXX" -- proof -r consumes the cluster remainder as its
--replace value) that ripgrep's -r takes a value (grep's -r/-R is
--recursive, boolean, with no equivalent to rg's -r at all).
`rtk rg -rREPLACEMENT pattern src` was misread as a boolean cluster
instead of -r's attached replacement value, corrupting the actual
command RTK executes -- extract_pattern_path's reconstructed
patterns/paths/flags feed directly into building the invoked command,
not just filtering, so this was a real command-substitution bug.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 ac8e54439b fix(git): has_limit_flag must require -n to have actually captured a value
has_limit_flag matched any Short "n" token by text alone, even one
clustered with another short flag where log_takes_separate_value's
is_solo gate correctly refuses to link a value (e.g. "-cn 2" leaves "n"
with no attached/linked value at all, per the earlier clustering fix).
RTK would then believe the user explicitly set a commit-count limit
(skipping its own --no-merges default) even though no value was ever
captured. Extracted has_limit_flag into its own testable function
(matching parse_limit_from_tokens's convention) and required t.value()
to be Some for the "n" case.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Opus 5 361057e3f8 fix(search): give grep and rg each their own value-taking flag table
One table served both engines, so every disagreement had to be discovered as a
bug and patched as an exception: `-T` (--initial-tab vs --type-not), `-r`
(--recursive vs --replace), `-L`/`-z`, then `--color` (attached-only in grep,
a separate token in rg) and the nine `--include`-family options grep requires
a value for and rg doesn't have. `rtk grep --include '*.txt' -r match .` made
the glob the pattern and `match` a file operand; `rtk grep --color match
a.txt` lost the pattern outright.

Measured against grep 3.11 and rg 14, the grammars barely overlap: 6 of 39
long flags are shared, and 7 of 13 short ones. What looked like a shared table
was rg's grammar with a few grep-compatible entries in it -- which is why `-E`
(grep's boolean --extended-regexp, rg's value-taking --encoding) was missing
from it too.

Now one function per engine, each transcribed from that engine's own --help,
sharing nothing: the intersection costs 13 duplicated entries and buys an
invariant worth more -- one function, one tool, one --help to check it
against. The tests that passed rg-only flags (`-g`, `--glob`, `--engine`,
`--type-clear`, `-M`, `-t`) while asking for the grep engine now ask for rg,
which is what they were exercising all along.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 1ae287bb65 docs(arg_tokenizer): restore flag_name_matches's own doc comment
An earlier edit inserted is_digit_run's doc block directly above
flag_name_matches's without a blank line and without flag_name_matches's
own doc reattached to its signature, so cargo doc rendered
flag_name_matches's explanation on is_digit_run and left
flag_name_matches itself undocumented. Reordered so each function keeps
its own doc block.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 23dd5ff049 fix(git): run_diff/run_show now share run_log's full raw-diff-shape flag list
run_diff's wants_stat and run_show's wants_stat_only only recognized
--stat/--numstat/--shortstat, narrower than requests_raw_diff_shape
(already used by run_log in this same branch), which also covers
--dirstat/--name-only/--name-status/--raw/--summary/--patch(-with-raw/
-with-stat)/-p/-u. `rtk git diff --name-only` (or --raw, -p, etc.) fell
through to RTK's default stat+compacted-diff path instead of a raw
passthrough of git's own output for that flag.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 0701098702 fix(arg_tokenizer,git): git's short-flag clustering doesn't match grep's
Added tokenize_git, a git-specific tokenizer entry point handling two
confirmed real-git behaviors tokenize()'s generic Short-cluster logic
didn't capture:

- -M/-U/-C/-B (rename/copy/rewrite/context-detection shorthand) accept
  only an attached value ("-M50"), never a separate token, standalone
  or clustered (confirmed: even `git log -U 3` fails with "ambiguous
  argument '3'"). Without these letters recognized as taking a value at
  all, a glued form like "-M50" decomposed into per-char Short tokens
  "M"/"5"/"0" instead of one "M" token with attached "50" -- the stray
  "5"/"0" tokens were then misread by parse_limit_from_tokens as if a
  bare "-5" limit flag had been passed.

- -n/-l accept a separate-token value only when written as their own
  standalone arg: `git log -n 2` succeeds, but `git log -cn 2`
  (clustered with -c) fails with "ambiguous argument '2'" -- unlike
  grep, which does let a clustered value-taking short flag consume a
  separate token (`grep -im 2 pattern file` works). Before this fix,
  RTK's tokenizer always linked the separate token as -n's value
  regardless of clustering, so `rtk git log -cn 2` would wrongly
  believe the user set an explicit commit-count limit of 2.

tokenize_git takes a second predicate, takes_separate_value(name,
is_solo), letting log_takes_separate_value express exactly this: false
for M/U/C/B, is_solo for n/l, true (unchanged, pre-existing behavior)
for everything else. tokenize()/tokenize_dialect keep their existing
signatures and behavior unchanged for every other caller (search.rs,
dotnet_cmd.rs, golangci_cmd.rs).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 a62bd30e35 fix(golangci): scope has_output_flag's value predicate to run-level flags
has_output_flag applied golangci_takes_value (scoped to flags valid
*before* run) to run_args (post-run) -- a run-level value-taking flag
missing from that list left its separate-token value unlinked, so a
value spelled like a recognized flag name (e.g. `--path-prefix
--output.json.path`) tokenized as its own genuine Long token and was
misdetected. Verified golangci-lint 2.13.1's actual flag set via Docker
(both `--help` output and empirical `golangci-lint run <flag> <value>`
checks for flags not shown as boolean) and added golangci_run_takes_value,
a correctly-scoped predicate covering run's real value-taking flags
(--disable, --enable, --timeout, --path-prefix, --output.*.path, etc.).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 e901af4064 docs(golangci): document has_output_flag's global-vs-run-level scope gap
golangci_takes_value's doc scopes it to golangci-lint's global
(pre-run) flags, but has_output_flag applies the same predicate to
run_args (post-run). has_flag's presence check only matches genuine
Long tokens (safe as long as no run-level value-taking flag is missing
from the list), but if one is missing and its value is itself spelled
like a recognized flag, it would be misdetected -- the same bug class
fixed elsewhere in this branch. Not fixed here since a correct fix needs
golangci-lint's actual complete run-level flag inventory, and no local
golangci-lint binary was available to verify it against.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 a5879d5a19 fix(git): run_branch's -u short flag must link its upstream value
branch_takes_value only recognized --set-upstream-to's long form as
value-taking, not its short form -u -- `git branch -u origin/main` left
"origin/main" as an unlinked Positional token instead of -u's linked
value. Currently masked in run_branch's own has_action_flag/
has_positional_arg decision (short "u" is already matched independently
by has_action_flag), but the token classification itself was still
wrong and would misfire for any future code consuming these tokens
directly. Also made has_positional_arg exclude linked tokens
(t.linked.is_none()), matching the established pattern elsewhere in
this migration (e.g. checkout_branch_arg).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 fcda021aac fix(dotnet): explicit_projects must stop at the user's own -- boundary
Dialect::Msbuild keeps classifying tokens past `--` (it's a forwarding
boundary for the test runner, not an end-of-options marker), so a
VSTest/MTP filter expression after -- that coincidentally ends in a
project extension (e.g. `dotnet test -- FullyQualifiedName~Foo.csproj`)
was picked up by explicit_projects as if it were a real project
reference, skipping the working-directory scan and risking the wrong
TestRunnerMode. Confirmed against a real dotnet 9 SDK that this exact
invocation runs the real project in cwd, not a nonexistent project
named after the filter text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 e55b41575c docs(search): document has_short_flag's reconstructed-string ambiguity
has_short_flag can misread a value-taking flag's own value (e.g.
--replace's value) as a real short flag if that value starts with a
literal '-' and contains the queried letter -- a real gap, but fixing
it needs token-level tracking threaded out of extract_pattern_path's
walk (restructuring its return type and the existing has_context_flag
unit tests, which test directly against reconstructed-string input) for
a narrow trigger condition. Documented as a known limitation rather than
forcing that refactor now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f9a53d046d fix(dotnet): detect_test_runner_mode must not scan flag values as project paths
explicit_projects scanned every token's raw text for a
.csproj/.fsproj/.vbproj suffix, so a value-taking flag's own value
(e.g. `--results-directory /tmp/MyResults.csproj`) satisfied it too --
making explicit_projects non-empty skips scanning the working directory
entirely, missing the real project there and picking the wrong
TestRunnerMode (and thus the wrong trx-reporting injection). Filtered to
unconsumed Positional tokens only (t.linked.is_none()).

Also extracted detect_test_runner_mode_in_dir(tokens, scan_dir) so the
directory-scan branch takes its target directory as a parameter instead
of hardcoding ".", making the new regression test deterministic (an
isolated tempdir) instead of racing on the real process cwd across
parallel test threads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f83be1920f fix(search): make format-flag detection engine-aware for -L/-z
is_format_flag_token (and the has_format_flag/extract_pattern_path call
sites) treated -L and -z identically for grep and rg, but confirmed
against real grep --help/rg --help that they mean unrelated things per
engine: grep's -L is --files-without-match (a real shape/format flag)
and -z is --null-data (input line terminator), while rg's -L is
--follow (symlinks) and -z is --search-zip (search compressed files) --
neither an rg format flag. `rtk rg -L pattern src` was misdetected as
already-minimal output and wrongly routed to raw passthrough, skipping
RTK's own match compression/grouping. Threaded Engine through
extract_pattern_path/is_format_flag_token so the check is per-engine.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 413eb1b4b2 fix(git): restore -- boundary awareness in run_diff's wants_stat/wants_compact
run_diff was the one migrated handler still using raw arg == "--stat"
string scans for wants_stat/wants_compact, missed when run_show and
run_log got the same fix earlier -- a file literally named "--stat"
after -- was misdetected as the real --stat flag and routed to the
raw-passthrough branch instead of RTK's stat+compacted-diff path.
Migrated onto arg_tokenizer, sharing log_takes_value like run_show does.

Also documents (arg_tokenizer.rs) a known, deliberately-unfixed
limitation surfaced by review: a single-segment Msbuild-dialect '/'
path (e.g. "/app", "/tmp") is structurally indistinguishable from a
switch name -- confirmed via Docker that real dotnet/MSBuild itself
only resolves this with a filesystem stat() call, which this tokenizer
can't replicate as a pure function.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 74be125f77 refactor(search): compute has_format_flag in extract_pattern_path's own token pass
The production call site re-tokenized the `flags` Vec<String> that
extract_pattern_path had already reconstructed from its own tokenize
pass over the full args -- two tokenize passes per rtk grep/rg
invocation with a pattern, the exact inefficiency arg_tokenizer.rs was
built to eliminate. extract_pattern_path now also returns
has_format_flag, computed from the same token walk; has_format_flag
itself becomes a #[cfg(test)]-only convenience wrapper, matching the
established pattern for git.rs's real_flag_args/requests_raw_log_output.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f17ffbd84d refactor(arg_tokenizer,git): dedupe the digit-run predicate
git.rs's own is_digit_run duplicated the identical predicate already
inlined in arg_tokenizer::tokenize_dialect's own cluster segmentation.
Exposed arg_tokenizer::is_digit_run as the single shared definition and
had git.rs use it instead of keeping a second copy that could drift.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 9c314a4470 refactor(git): centralize restore_double_dash at the run() dispatcher
restore_double_dash was called ad hoc inside 6 of 13 git subcommand
handlers (run_diff, run_show, run_log, run_add, run_checkout,
run_branch), while run_status, run_commit, run_push, run_pull,
run_fetch, run_stash, and run_worktree got none -- any future
boundary-sensitive logic added to one of those seven would silently
operate on clap's --stripped args unless its author remembered this
per-function convention, the exact class of omission issue #1215 was
about. restore_double_dash is a no-op when -- wasn't stripped, so
calling it once in the dispatcher is safe and free for every handler
that doesn't need it, and closes the gap for ones that will.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 9ecd50c4c1 test(git): pin checkout -b/-B's glued short-flag capability against real git
The tokenizer migration widened checkout_new_branch_arg/checkout_reset_branch_arg
to recognize a glued short-flag spelling (-bmy-branch), where the
pre-migration hand-rolled match only matched a literal "-b"/"-B" arg
requiring a separate value token. Confirmed against real git 2.51 that
`git checkout -bmy-branch` does create "my-branch", same as the
separate-token form -- this was a genuine correctness widening, just
missing a regression test to pin it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 8f20216db2 fix(arg_tokenizer): a multi-segment '/'-prefixed token is positional, not a flag
Under Dialect::Msbuild, any token starting with '/' (other than bare "/")
was classified as a Long flag regardless of internal '/'s, so an
absolute Unix path like "/tmp/results" or a real project path like
"/home/user/proj/MyProject.csproj" tokenized as a flag named
"home/user/proj/MyProject.csproj" instead of Positional. Confirmed via
a real dotnet 9 SDK (Docker) that `dotnet build /abs/path/Project.csproj`
correctly builds the absolute path as the project positional -- real
MSBuild never treats a multi-segment "/a/b" as a switch attempt. Fixed
by requiring the flag-name portion (before any ':'/'=' attached-value
separator) to contain no further '/'; a genuine single-segment switch
like "/nologo" or "/p:OutDir=/tmp/out" (value may contain '/', just not
the name) still classifies as Long.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 7ddaabf98c refactor(dotnet): swap has_flag naming so the safe strict lookup is the short name
dotnet_has_flag was the loose, case-folding matcher (-flag/--flag//flag
interchangeable), correct only for a handful of legacy MSBuild.exe
switches, while the strict double-dash-only matcher -- correct for
every other dotnet_cmd.rs flag -- had the longer name
dotnet_has_double_dash_flag. That shape invites reaching for the
shorter, wrong one by default: commit a1c8302 exists because exactly
that happened once already. Swapped: dotnet_has_flag is now the strict
lookup, and the loose one is dotnet_has_loose_flag -- deliberately
longer and named for what makes it dangerous. Pure rename, no behavior
change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 831fbc43c6 fix(search): migrate has_format_flag off its own inline mini-tokenizer
has_format_flag reimplemented its own per-arg flag scan (manual "--"
prefix check, manual short-cluster char scan) instead of reusing
arg_tokenizer::tokenize + search_takes_value, which extract_pattern_path
in this same file already depends on. Real bug fixed by the migration:
the old scan checked every raw arg string independently with no notion
of "this token is another flag's value", so `-e --json` (where "--json"
is -e's pattern) was misdetected as the real --json format flag.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 fd32fc2f09 refactor(dotnet): reuse the already-tokenized -- position in inject_report_trx_into_args
inject_report_trx_into_args hand-rolled its own args.iter().position(|a|
a == "--") scan instead of reusing the DashDash token already computed by
dotnet_tokens for this same invocation. Pure refactor, no behavior change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 796c97425e fix(git): restore -- boundary and migrate run_branch to arg_tokenizer
run_branch never called restore_double_dash despite git branch using
trailing_var_arg, and has_action_flag/has_list_flag/has_positional_arg
were raw, --boundary-unaware string scans (has_positional_arg in
particular: `!a.starts_with('-')`). A branch name starting with '-'
after -- was misclassified as a flag rather than the positional name to
create, so rtk silently ran a harmless empty `git branch -a` list
instead of attempting the creation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 f7720d8841 fix(dotnet): has_nologo_arg must not match an attached-value spelling
-nologo is a pure boolean MSBuild.exe switch (confirmed via a real
dotnet 9 SDK, Docker: "-nologo:true" fails with "MSB1002: This switch
does not take any parameters"). has_nologo_arg used the loose
dotnet_has_flag lookup, which ignores Token::attached entirely, so it
treated the broken "-nologo:true" spelling as "user already passed
-nologo" -- RTK skipped its own -nologo injection while still
forwarding the invalid flag straight through to real dotnet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 5f570c5bea test(git): add real-process regression for run_show's -- boundary fix
Mirrors the existing git_log_dash_p_pathspec_after_double_dash test:
stages a file literally named "--stat" past the -- separator and asserts
`rtk git show -- --stat` stays on RTK's compacted-diff path instead of
being misdetected as the --stat summary flag.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 1bec7f56b8 fix(git): restore -- boundary in run_add and migrate run_show to arg_tokenizer
run_add never called restore_double_dash, so `rtk git add -- -weird-filename`
lost its -- before reaching git, which rejected the flag-like filename
instead of staging it.

run_show's wants_stat_only/wants_format checks were raw, --boundary-unaware
string scans (arg == "--stat", arg.starts_with("--pretty")) -- a pathspec
literally named "--stat" or "--pretty" after -- was misdetected as the real
flag. Migrated onto arg_tokenizer (sharing git log's value-taking-flag
predicate) with restore_double_dash up front, matching the fix already
applied to run_log/run_diff/run_checkout. wants_blob_show/is_blob_show_arg
is left as-is: its own dash-prefix guard already makes it boundary-safe.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 b7eec873fa fix(golangci): restore -- boundary before classifying invocation args
run() never called restore_double_dash despite clap's trailing_var_arg
stripping the literal "--", so both classify_invocation's -- detection
and the raw args forwarded to the real binary were missing the user's
own --.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 49041f408b fix: address lower-severity findings from third /code-review high pass
- dotnet_cmd.rs: has_write_mode_override matched an attached-value
  spelling ("--write=true") as a force-write override via
  dotnet_has_double_dash_flag (which only checks the flag name, not
  whether it has a value), but build_effective_dotnet_format_args's
  strip filter only ever removed the exact bare "--write" token. So RTK
  would skip its own --verify-no-changes injection *and* still forward
  the unrecognized "--write=true" to real dotnet, which has no --write
  option at all (confirmed via Docker) and would reject it. --write was
  never meant to take a value, so detection now requires attached ==
  None too -- an attached-value spelling is simply not recognized as
  the --write pseudo-flag, matching how any other unrecognized argument
  passes through untouched (consistent with, not silently swallowed by,
  the strip filter).

- golangci_cmd.rs: run_filtered called build_filtered_args (which
  tokenizes invocation.run_args) twice -- once to build the real
  command, once again just to render the verbose debug log line.
  Compute it once and reuse it for both.

Investigated but found NOT to be real bugs (verified against a real
dotnet 9 SDK via Docker before concluding, rather than assuming):
- arg_tokenizer.rs's split_attached splitting on both ':' and '=' for
  every Dialect::Msbuild Long token, including double-dash-only options
  like --results-directory/--report: confirmed `--results-directory:val`
  and `--report:val` both work correctly against real dotnet test/format,
  so the existing behavior is correct, not over-permissive.

Not changed, judged intentional/established rather than problems:
dotnet_cmd.rs's per-flag wrapper functions (has_nologo_arg etc.) --
named predicates over hardcoded string literals, matching the
pre-existing convention from before this session's migration; Token::
double_dash being meaningful only under Dialect::Msbuild -- normal for
a field on a struct shared across dialects with different needs;
git.rs's #[cfg(test)]-only wrappers (real_flag_args, parse_user_limit,
requests_raw_log_output) -- a deliberate tradeoff from an earlier commit
in this branch to keep production on the single-tokenization path
without rewriting ~15 existing test call sites.

Also noted but out of scope for this branch (per user instruction):
run_show/run_diff's own `--`-boundary gap, already tracked as a known
follow-up since commit 7049983.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 8d37891819 fix(arg_tokenizer): never let a value-taking flag swallow the boundary --
Critical finding from the third /code-review high pass, independently
verified against real git before fixing: both push_atomic_flag
(Long/Msbuild-atomic flags) and the Short-cluster value-consumption branch
consumed the next raw arg as a value-taking flag's value via args.get(...)
unconditionally, with no check for the literal "--" separator. So
`rtk git log --grep -- pattern` or `rtk git checkout -b -- file.txt`
silently swallowed "--" as the flag's value and never emitted a DashDash
token at all -- breaking anything downstream that depends on finding that
boundary (e.g. git.rs's checkout_restored_count/checkout_branch_arg).

Verified against real git 2.51 that this exact swallowing is wrong:

  $ git log --grep -- fix
  fatal: Option '--grep' requires a value
  (git refuses to let --grep claim "--", even though --grep needs a value)

  $ git log --grep -- -- foo
  fatal: Option '--grep' requires a value
  (still refuses -- only the FIRST/boundary "--" is protected)

  $ git log -- -- fix
  (succeeds -- once past the boundary, a later "--" is ordinary text and
  fair game as a value)

So the fix is precise, not a blanket "never consume --": guard value
consumption on the tokenizer's own emitted_dash_dash state (already
tracked for the Msbuild-forwarding-boundary fix) -- refuse to link the
still-unseen boundary "--" as a value, but still allow a later "--" once
the boundary was already emitted. Threaded emitted_dash_dash into
push_atomic_flag as a parameter; the short-cluster branch already had it
in scope.

Also extracted the shared link_next_value() helper both consumption
sites now call, addressing a related cleanup finding from the same
review: the duplicated consume-next-token-as-value logic is exactly
what let the original bug exist in two places at once instead of one.

Three new regression tests (verified to fail against the prior
implementation before restoring the fix): a value-taking Long flag
before --, a value-taking Short flag before --, and a value-taking flag
after the boundary was already emitted (which must still consume normally).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 8fd8b14d2b fix(dotnet): most dotnet_cmd.rs flags are double-dash-only, not -/--// interchangeable
Verified against a real dotnet 9 SDK (Docker, mcr.microsoft.com/dotnet/sdk:9.0)
that the earlier claim behind the Msbuild dialect's uniform prefix widening
("dotnet's actual System.CommandLine parser treats -/--// as interchangeable
prefixes for every option") was wrong. Only a handful of options are genuine
legacy MSBuild.exe passthrough switches valid via all three prefixes
(-nologo/--nologo/nologo, -bl, -v/-verbosity) -- confirmed working. Every
other dotnet_cmd.rs flag (--verify-no-changes, --report for `dotnet format`;
--logger, --results-directory for `dotnet test`) is double-dash-only, and a
single-dash or slash spelling doesn't just get rejected -- it gets
*misparsed* as an unrelated MSBuild switch:

  $ dotnet format -verify-no-changes
  Argument 'erify-no-changes' not recognized. Must be one of: 'q' 'quiet' ...
  (parsed as -v with attached value "erify-no-changes")

  $ dotnet test -results-directory /tmp/out
  MSBUILD : error MSB1001: Unknown switch.

  $ dotnet test -logger trx
  MSBUILD : error MSB1007: Specify a logger.
  (collides with MSBuild's own -logger switch, which wants an assembly spec)

  $ dotnet format /verify-no-changes
  Unhandled exception: FileNotFoundException: 'verify-no-changes' does not
  appear to be a valid project or solution file.
  (positional argument fallback, same as -write / --write's actual behavior)

Added Token::double_dash (true only for a literal `--` prefix; -flag/­/flag
under Dialect::Msbuild are false) plus has_double_dash_flag/
double_dash_flag_value/double_dash_flag_values, and switched
has_trx_logger_arg/has_results_directory_arg/has_report_arg/
has_report_trx_arg/extract_report_arg/has_verify_no_changes_arg/
extract_results_directory_arg/has_write_mode_override to the strict variants
-- has_nologo_arg/has_binlog_arg/has_verbosity_arg keep the loose has_flag,
since those three are the actual legacy-switch exceptions. --write is RTK's
own pseudo-flag (stripped before forwarding to real dotnet, never validated
by it) but kept double-dash-only too for consistency with its dotnet-format
siblings rather than inventing a laxer convention with no real reference
behavior to match.

Removed the now-unused loose flag_value/flag_values (nothing needs
loose-prefix *value* extraction, only loose presence checks for the three
legacy switches) and dotnet_cmd.rs's now-dead dotnet_flag_value wrapper.

Regression test (test_double_dash_only_flags_reject_single_dash_and_slash_spellings)
verified to fail against the prior (loose) implementation before restoring
the fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 9457a7fdc8 fix(go): give has_output_flag -- boundary awareness
has_output_flag was the last hand-rolled string scan left in
golangci_cmd.rs (find_subcommand_index/golangci_takes_value were already
migrated), and had no `--` awareness: `golangci-lint run -- --out-format`
(a package path literally named "--out-format" passed to the linted
target after the separator) would be misdetected as the user requesting
a custom output format, silently skipping RTK's own default
--output.json.path/--out-format=json injection.

Migrated onto arg_tokenizer::tokenize + has_flag, consistent with the
rest of the file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 e8caef420b refactor(dotnet): tokenize args once per invocation, not per helper call
dotnet_tokens(args) re-tokenized from scratch inside every has_*/extract_*
helper (has_nologo_arg, has_trx_logger_arg, has_results_directory_arg,
has_report_arg, has_report_trx_arg, extract_report_arg,
has_verify_no_changes_arg, has_write_mode_override,
extract_results_directory_arg, has_binlog_arg, has_verbosity_arg) --
unlike git.rs's run_log, which already tokenizes once and shares the
result. A single `dotnet test`/`dotnet format` invocation could
re-tokenize the same args up to 5+ times across run_format's own checks
plus build_effective_dotnet_format_args, or run_dotnet_with_binlog's
should_expect_binlog plus resolve_trx_results_dir plus
build_effective_dotnet_args's several checks.

Every one of these helpers now takes `tokens: &[Token<'_>]` directly
instead of `args: &[String]`, with the tokenization itself hoisted to a
single `dotnet_tokens(args)` call at the top of run_format and
run_dotnet_with_binlog, threaded down through resolve_trx_results_dir,
resolve_format_report_path, build_effective_dotnet_args, and
build_effective_dotnet_format_args. `args` itself stays a parameter
alongside `tokens` where still needed for non-classification purposes
(raw forwarding to the dotnet subprocess, detect_test_runner_mode's
filename-extension scan, inject_report_trx_into_args's positional
Vec-splice).

Also migrated has_binlog_arg/has_verbosity_arg (previously hand-rolled
starts_with string scans) onto the tokenizer as part of this pass, since
they were two of the remaining "cleanup opportunity" holdouts sitting a
few lines above the already-migrated helpers.

No intended behavior change; full suite (2731 tests, including the
dotnet_double_dash_test.rs real-process regression test) passes
unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 70874e4aff refactor(arg_tokenizer): genericize over AsRef<str>, simplify search.rs
tokenize/tokenize_dialect were hardcoded to &[String], forcing search.rs's
extract_pattern_path to clone every arg into a fresh Vec<String> just to
satisfy that signature even for its one production caller, which already
owns a Vec<String> from restore_double_dash (worked around last commit
by splitting into a test-only generic wrapper + an _owned zero-copy
variant). Genericizing tokenize/tokenize_dialect/push_atomic_flag over
T: AsRef<str> removes the need for that split entirely: String and &str
both satisfy the bound, so every existing call site (all of which pass
&[String]) needed zero changes, and search.rs collapses back to one
extract_pattern_path<T: AsRef<str>> used directly by both its production
call site and its ~29 &[&str]-literal tests, with no cloning either way.

Not extended to OsStr/OsString: unlike str, OsStr exposes almost no
string-manipulation API by design (no strip_prefix, split_once,
char-boundary slicing), so tokenizing it would mean re-deriving that
machinery byte-by-byte the way clap_lex does internally -- a much bigger
change for a case rtk doesn't hit today (its own CLI parsing already
assumes UTF-8 args for every subcommand this module serves).

Also documents why tokenize() doesn't just call restore_double_dash (or
std::env::args()) internally: restore_double_dash's result has to be an
owned Vec<String> the caller holds in its own `let`, and Token<'a>
borrows straight from `args` -- tokenizing a Vec<String> built inside
this module would tie every Token to a value dropped when the function
returns. Same root cause as why this module doesn't build on clap_lex.

Also: dotnet_cmd.rs's has_trx_logger_arg no longer needs an intermediate
`let has_trx = ...; has_trx` binding to dodge a tail-position temporary
lifetime issue -- an explicit `return` avoids it more simply. And added
a regression test + doc trail for the earlier -5x malformed-input
question: verified against real git (`git log -5x` fails with "fatal:
'5x': not an integer", exit 128) that run_log's internal limit
computation for this input is never observable either way, since
run_log bails out on !result.success() before the formatting code that
would use it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 3698b9417a fix: address second /code-review high pass (4 verified findings)
- dotnet_cmd.rs: has_trx_logger_arg only checked the first --logger
  occurrence via flag_value's .find(). dotnet test's --logger can
  legitimately repeat (`--logger "console;verbosity=normal" --logger
  trx`, a documented VSTest pattern); a trx logger that isn't the first
  occurrence was silently missed, causing a duplicate --logger trx
  injection. Added arg_tokenizer::flag_values (every occurrence, not
  just the first) and switched has_trx_logger_arg to it. Verified the
  new multi-logger regression test fails without the fix.

- arg_tokenizer.rs: TokenKind::DashDash's doc promised "emitted exactly
  once," but under Dialect::Msbuild seen_dash_dash was never set, so
  every literal `--` produced its own DashDash token (Posix already got
  this for free via its seen_dash_dash-gated positional catch-all).
  Added a separate emitted_dash_dash flag so only the first `--` becomes
  DashDash in either dialect; later ones fall back to plain Positional
  text "--". Latent today (no dotnet_cmd.rs caller reads DashDash
  position yet) but was a real violation of the module's own invariant.

- golangci_cmd.rs: find_subcommand_index stopped scanning (returning
  None/Passthrough) the moment it hit a bare "-" token, since
  arg_tokenizer classifies a lone "-" as Positional. The old hand-rolled
  scanner treated any "-"-prefixed token, including bare "-", as
  skippable/unrecognized and kept scanning for the real subcommand.
  Excluded "-" specifically from the stopping condition. Verified the
  new regression test fails without the fix.

- search.rs: extract_pattern_path cloned every arg into a fresh
  Vec<String> to satisfy arg_tokenizer::tokenize's &[String] signature,
  even though its one production caller already owns a Vec<String> from
  restore_double_dash. Split into extract_pattern_path_owned(&[String])
  (used by the real call site, zero-copy) and kept the generic
  T: AsRef<str> wrapper as #[cfg(test)]-only for the ~29 existing test
  call sites that pass &[&str] literals.

Also assessed and intentionally left unfixed (see conversation for
detail): run_show/run_diff's own --stat-style checks have the same
`--`-boundary gap run_log had, but touching them is new scope beyond
this session's migrated code, not a regression this diff introduced;
dotnet_cmd.rs's flag-prefix widening (-/--// treated as interchangeable
for every dotnet_cmd.rs flag) rests on an unverified assumption about
dotnet's System.CommandLine parser I can't confirm without a real SDK;
a few remaining hand-rolled string scans (has_binlog_arg,
has_verbosity_arg, has_output_flag) are consistency nitpicks, not bugs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 d976d6829f fix(git): stop tokenizing run_log's args twice
run_log's own comment said "tokenize once and share it," but
requests_raw_log_output(args) tokenized internally to decide on raw
passthrough, and when it returned false the code tokenized args again
right after for the shared `tokens` variable -- silently contradicting
its own stated intent. Found by /code-review high.

run_log now tokenizes once up front and checks
tokens.iter().any(requests_raw_diff_shape) directly for the raw-passthrough
decision, reusing the same tokens for everything else.
requests_raw_log_output stays as a #[cfg(test)] convenience wrapper (its
existing unit tests still call it directly with a &[String]) but is no
longer part of the real run_log path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 6988a45730 refactor(arg_tokenizer): make case-insensitive flag lookup a Dialect property
dotnet_cmd.rs's dotnet_flag_value/dotnet_has_flag each hardcoded their
own .eq_ignore_ascii_case() call. Case-insensitive flag names aren't a
dotnet-CLI particularity though -- it's a broader Windows/MSBuild-ecosystem
convention (classic MSBuild.exe's /nologo and /NoLogo are equally valid,
not just dotnet's System.CommandLine parser), so it belongs on Dialect
itself, not left to each caller to remember.

Token::text can't be case-folded once at tokenize time without giving up
the zero-copy &'a str contract (there's no borrowed "lowercased" view of
a str), so the fix lives in new shared lookup helpers instead:
flag_value(tokens, dialect, name) / has_flag(tokens, dialect, name),
which pick exact vs ASCII-case-insensitive comparison from the dialect
via a small flag_name_matches() (Long tokens only -- Msbuild never
produces Short, and conflating Long/Short by text alone would be wrong
for Posix). dotnet_cmd.rs's local helpers now just forward to these.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 396ef174b8 style: alphabetize match arms/enums/lists, prefer _ over spelled-out catch-alls
Consistency sweep across everything touched in this arg_tokenizer work:

- `TokenKind::X | TokenKind::Y => false` catch-alls (naming exactly the
  two variants not otherwise handled) become `_ => false`/`_ => {}`.
- match arms on TokenKind reordered alphabetically (Long before Short,
  etc.), matching the convention already used by most of them.
- matches!() flag lists reordered alphabetically where they weren't
  (dotnet_takes_value's report/results-directory, run_log's format-flag
  and wants_merges checks, parse_limit_from_tokens' arm order).
- search.rs's VALUE_FLAGS_SHORT/VALUE_FLAGS_LONG and golangci_cmd.rs's
  GOLANGCI_SUBCOMMANDS (&[&str] consts checked via .contains()) converted
  to matches!() functions (is_short_value_flag/is_long_value_flag/
  is_golangci_subcommand), consistent with every other flag-list
  predicate in this codebase.
- TokenKind and Dialect enum variants reordered alphabetically at their
  declaration site too (DashDash/Long/Positional/Short,
  Msbuild/Posix).

No behavior change; cargo fmt/clippy/test --all clean throughout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 8311fa3c22 refactor(go): migrate golangci_cmd.rs subcommand detection onto arg_tokenizer
find_subcommand_index/split_flag_name/golangci_flag_takes_separate_value
hand-rolled the same flag/value classification arg_tokenizer now
centralizes (GLOBAL_FLAGS_WITH_VALUE was its own one-off "which global
flags take a separate value" list). Replaced with a single
arg_tokenizer::tokenize(Dialect::Posix) call plus a small predicate
(golangci_takes_value); find_subcommand_index now just walks the
resulting tokens for the first free positional, using Token::source_index
to translate back to the position in the original `args` for the caller
(classify_invocation slices global_args/run_args off that index).

No intended behavior change: all existing classify_invocation tests
pass unchanged. Added two regression cases the prior hand-rolled scanner
didn't have tests for: `-c value` (short flag consuming a separate-token
value, previously untested) and `--` before any subcommand is found
(must fall through to Passthrough, matching golangci-lint's own parser
taking over from there).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 84f85166db fix(arg_tokenizer): Msbuild's -- is a forwarding boundary, not end-of-options
Discovered this refining the previous commit: dotnet's `--` doesn't mean
what git/POSIX `--` means. Git's `--` ends option parsing -- everything
after is a literal positional/pathspec, never a flag again. dotnet's `--`
is an argument-*forwarding* boundary: what follows is still real flags,
just meant for a different receiving parser (the VSTest/MTP test host),
which can and does share flag names with dotnet test's own CLI (e.g.
--logger, --results-directory are forwarded VSTest-console options, and
--report-trx is meaningful on either side of `--` depending on
TestRunnerMode::MtpVsTestBridge).

The previous commit's dotnet_cmd.rs fix (with_dotnet_tokens stripping
`--` out before tokenizing) reproduced the right observable behavior but
for the wrong reason -- it papered over the mismatch in the caller
instead of naming it. Moved the fix to where it actually belongs:
tokenize_dialect now only stops classifying at `--` for Dialect::Posix;
Dialect::Msbuild still emits a DashDash token (so callers can find `--`'s
position) but keeps classifying flags normally past it. This also let
dotnet_cmd.rs drop the owned-copy-plus-closure workaround entirely --
dotnet_tokens() is back to a plain function borrowing straight from the
caller's args, same shape as every other tokenizer call site.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 637a0139c1 refactor(arg_tokenizer): add Msbuild dialect, migrate dotnet_cmd.rs flag checks
dotnet's CLI grammar isn't POSIX/GNU: `-flag`, `--flag`, and `/flag` are
all one atomic flag name (no short-flag clustering, e.g. `-nologo` must
stay one token, not decompose into per-char short flags), and a value
can attach via `:` as well as `=` (`--logger:trx`). Added Dialect::{Posix,
Msbuild} to arg_tokenizer, threaded through a new tokenize_dialect();
tokenize() itself is now a thin Dialect::Posix wrapper, so git.rs/search.rs
are untouched.

Migrated dotnet_cmd.rs's flag/value helpers (has_nologo_arg,
has_trx_logger_arg, has_results_directory_arg, has_report_arg,
has_report_trx_arg, extract_report_arg, has_verify_no_changes_arg,
has_write_mode_override, extract_results_directory_arg) onto
tokenize_dialect(Msbuild), replacing ~9 hand-rolled peekable/prefix
scans with two small shared helpers (dotnet_has_flag/dotnet_flag_value).

Two things the migration had to account for, not just carry over:
- dotnet_cmd.rs's checks were never `--`-boundary aware (--report-trx is
  meaningful on either side of `--` depending on TestRunnerMode, and the
  original code just flat-scanned the whole arg list) -- unlike git/grep,
  where `--` genuinely ends option parsing. tokenize_dialect always stops
  classifying at `--` (correct for git.rs/search.rs), so dotnet_cmd.rs's
  new with_dotnet_tokens() strips `--` out before tokenizing to reproduce
  the original scan-everything behavior. Caught by
  test_vstest_bridge_respects_existing_report_trx (would otherwise
  double-inject --report-trx when the user already placed it after --).
- has_nologo_arg previously matched only "-nologo"/"/nologo" (not
  "--nologo"), and has_results_directory_arg/has_report_arg/
  has_verify_no_changes_arg/has_write_mode_override previously matched
  only the "--" form -- both incidental gaps from scanning raw strings
  per-flag rather than a unified prefix model. Since dotnet's actual
  System.CommandLine parser treats -/--/ / as interchangeable prefixes
  for every option, recognizing all three forms uniformly for every flag
  here is a correctness improvement, not a behavior risk.

inject_report_trx_into_args is untouched: it's pure `--`-relative Vec
splicing, not flag/value classification, so it doesn't need tokenizing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 978a575ee9 fix(dotnet): restore -- before build/test/restore/format arg handling
dotnet_cmd.rs never called args_utils::restore_double_dash despite
Build/Test/Restore/Format all using trailing_var_arg = true in
main.rs, the same clap-strips-`--` hazard git.rs/cargo_cmd.rs/search.rs
already hit and fixed (issue #1215). Concretely: `rtk dotnet test --
FullyQualifiedName=MyFilter` lost its `--`, so
inject_report_trx_into_args (VsTestBridge MTP mode) couldn't find one
to reuse and appended a fresh `-- --report-trx` at the end instead —
landing the user's MTP-runtime filter expression BEFORE the separator
(misread as a dotnet-test-level arg) instead of after it, and stranding
--report-trx with nothing following it.

Added the missing restore_double_dash call to both entry points that
feed `args` into `--`-sensitive logic (run_dotnet_with_binlog for
build/test/restore, run_format). Regression test stubs `dotnet` on
PATH (no dotnet SDK in this environment) to capture the real argv rtk
would hand it; verified it fails without the fix and passes with it.

Not migrated onto arg_tokenizer: investigated during this pass and
dotnet's CLI grammar isn't POSIX/GNU-style — has_nologo_arg accepts
single-dash multi-letter flags (`-nologo`, `/nologo`) as one atomic
name rather than a short-flag cluster, and --logger:trx uses `:` as
an attach separator, both incompatible with arg_tokenizer's current
clustering model. A caller-selectable dialect (no clustering, `/`
prefix, `:`-or-`=` attach) could support this later; not attempted
here to keep this fix minimal and low-risk.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 b11e0d0342 refactor(search): migrate grep/rg arg parsing onto arg_tokenizer
search.rs's VALUE_FLAGS_SHORT/VALUE_FLAGS_LONG/ClusterResult/parse_cluster
reimplemented the same flag/value/-- classification arg_tokenizer now
centralizes. Migrates extract_pattern_path onto arg_tokenizer::tokenize,
keeping the flag lists as data (now dash-free, matching Token::text) and
the -e/--regexp-routes-to-patterns special case as extract_pattern_path's
own business logic (not something tokenize needs to know about).

Reconstructing the exact flags: Vec<String> shape (grep/rg-facing, not
just internal) needed one thing tokenize()'s per-character Short model
didn't originally have: knowing whether "-r" and "-n" were typed as one
cluster ("-rn", reconstructed glued) or two separate args ("-r" "-n"),
since existing tests pin the glued form for one-arg clusters. Added
Token::source_index (which original args slot a token came from) to
close that gap generically -- every Short token from one cluster shares
a source_index, a consumed separate-token value always has its own.
Also added Token::value() (attached-or-linked) as a small shared
convenience, used here and to simplify git.rs's now-redundant
linked_value/flag_value helpers.

Note: this is a reconstruction-format detail, not a behavior change --
grep/rg parse "-rn" and "-r -n" identically via standard getopt
clustering, and rtk's own has_short_flag() already checks via substring
so it doesn't care which form it sees either.

No intended behavior change. parse_cluster/ClusterResult's own unit
tests are removed (that internal API no longer exists); the existing
extract_pattern_path tests already exercise the same short-cluster/
value-taking/-e behavior end-to-end and all still pass unchanged.

Follow-up (not in this commit): golangci_cmd.rs, and dotnet_cmd.rs
(which has a latent restore_double_dash gap of its own).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Nicolas Le CamandClaude Sonnet 5 86c10c84b5 refactor(core): add shared arg_tokenizer, migrate git.rs onto it
Every src/cmds/** filter that needs to know "does this flag consume the
next token as its value, and where does -- end options" was reimplementing
that question independently. git.rs alone racked up 9 one-off bugfix
commits on its own LogArg/consumes_next_token_as_value/log_arg_tokens
(hardcoded matches! lists edited piecemeal, -- handling gaps), and a
codebase survey found the same shape of bug already hit or latent in
search.rs, golangci_cmd.rs, and dotnet_cmd.rs.

Adds src/core/arg_tokenizer.rs: a single tokenize() that classifies an
already-restore_double_dash'd args slice into Long/Short/Positional/
DashDash tokens, linking each value token to the flag that consumes it
and vice versa, with a caller-supplied `takes_value(kind, name)`
predicate (each wrapped CLI's value-flag list stays exactly as
data — only the token-walking around it is now shared). Digit-only
short suffixes (git log/head/tail's `-N` shorthand) are kept as one
token rather than decomposed into per-digit "flags", since no real CLI
defines boolean digit flags.

Migrates git.rs's run_log (LogArg/log_arg_tokens/consumes_next_token_as_value
-> log_takes_value + tokenize) and run_checkout's four separate hand-rolled
scanners (checkout_new_branch_arg/checkout_reset_branch_arg/
checkout_branch_arg/checkout_restored_count) onto one shared tokenization
each, keeping their existing flag lists as the predicate body. No
intended behavior change; arg_tokenizer's own unit tests encode a
regression case for every prior git.rs bugfix commit, and git.rs's
existing test suite (updated only where it asserted internal token
shape, e.g. dash-free flag text) plus the real-process integration
tests in tests/guard_integration_test.rs still pass unchanged.

Follow-up (not in this commit): migrate search.rs, dotnet_cmd.rs (which
has a latent restore_double_dash gap of its own), and golangci_cmd.rs
onto the same tokenizer.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 12:14:09 +02:00
Christian Marbach ba802ac82d docs(ast-grep): document rtk ast-grep in README and usage guides
Adds the ast-grep row/section to README.md, what-rtk-covers.md, and
FEATURES.md, matching how rtk grep/rg are documented there.
2026-09-07 10:34:00 +02:00
Christian Marbach 905ca3a852 refactor(ast-grep): avoid stdout clone in --json passthrough path
Review nit: --json is the largest-payload path, so borrow rather
than clone result.stdout when skipping the filter.
2026-09-05 13:54:31 +02:00
Christian Marbach d5364b814e feat(ast-grep): filter ast-grep output like grep/rg
Groups matches by file, caps at 5/file and 50 total. --json passes
through untouched. ~85% savings on a repo-wide test search.

Closes #3856
2026-09-03 18:56:13 +02:00
Ruiming Zhao 656a8640e6 fix(gh): deduplicate watched PR checks
Signed-off-by: Ruiming Zhao <267482477+uuzzrm@users.noreply.github.com>
2026-08-11 15:58:58 -07:00
Loi Nguyen 56519c4937 fix(npm): recognize extended subcommands 2026-07-20 07:24:09 +07:00
Jack DangerandClaude Sonnet 4.6 3b4ab8735a fix: suppress hook warning during rtk init and verify
Running `rtk init -g` showed a spurious "No hook installed" warning
because maybe_warn() ran before the init completed. Skip the warning
for Init and Verify commands — they manage the hook themselves.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 12:50:15 -07:00
Florian BRUNIAUXandClaude Sonnet 4.6 0f45992a0d fix(tracking): use weighted savings rate in low_savings_commands and avg_savings_per_command
AVG(savings_pct) over rows produces an unweighted mean: a handful of 0%-savings
passthrough calls dilute a filter that genuinely performs well on high-volume
invocations. Same root cause as PR #891 (get_by_command).

Changes:
- low_savings_commands: AVG(savings_pct) → SUM(saved)*100/SUM(input). A command
  with 1 big call (95%) + 4 small calls (0%) now shows 94.6%, not 19%. Filters
  correctly excluded from the "needs improvement" list shipped in telemetry.
- avg_savings_per_command: inner per-command rate is now weighted (SUM/SUM);
  outer average across command names stays unweighted (intentional, each filter
  counts once). Documented in TELEMETRY.md.
- Two regression tests added (conn.execute direct inserts for DB isolation).
- docs/TELEMETRY.md updated to reflect the weighted formula.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-14 11:44:00 +02:00
Florian BRUNIAUX de0450d26f docs(changelog): add entry for gain weighted savings rate fix
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-13 14:57:33 +02:00
Florian BRUNIAUXandClaude Sonnet 4.6 f3e0094183 fix(gain): use weighted savings rate in per-command stats
AVG(savings_pct) produced a simple unweighted mean that diluted the
reported rate for high-volume commands — grep showed 14.8% while the
true weighted rate was 98.6%, a 84-point gap.

Replace AVG(savings_pct) with SUM(saved_tokens)*100.0/SUM(input_tokens)
in the per-command SQL query so the rate reflects actual byte savings
rather than an average of per-invocation percentages.

Also:
- Rename "Avg%" column header to "Rate" (more accurate label)
- Add doc warning on CommandStats type alias against using AVG()
- Add regression test proving weighted != unweighted on skewed data

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-13 14:54:43 +02:00
Carlos D ecdf332a3d fix(gh): don't early exit on failure for "pr checks"
if there are failing checks in the PR, then `gh` will return a status of
`1` and `rtk` will refuse to parse the output due to using
`early_exit_on_failure`.

remove the use of `early_exit_on_failure` so it can still parse the
output.

now if there is an error, we will still get the summarised output with
all `0`s, and we'll also pass through the stderr.

example if a repository does not exist:

```
CI Checks Summary:
  [ok] Passed: 0
  [FAIL] Failed: 0
GraphQL: Could not resolve to a Repository with the name 'some-org/some-repo'. (repository)
```

with the error passed through to the output regardless, the error
handling downstream by the LLM should still work well.
2026-04-10 11:36:21 +10:00
49 changed files with 12464 additions and 1516 deletions

No files matched your search

+3 -3
View File
@@ -85,15 +85,15 @@ elif echo "$FIRST_CMD" | grep -qE '^find\s+'; then
elif echo "$FIRST_CMD" | grep -qE '^diff\s+'; then
SUGGESTION=$(echo "$CMD" | sed 's/^diff /rtk diff /')
elif echo "$FIRST_CMD" | grep -qE '^head\s+'; then
# Suggest rtk read with --max-lines transformation
# Suggest rtk read with --head-lines transformation
if echo "$FIRST_CMD" | grep -qE '^head\s+-[0-9]+\s+'; then
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
SUGGESTION="rtk read $FILE --max-lines $LINES"
SUGGESTION="rtk read $FILE --head-lines $LINES"
elif echo "$FIRST_CMD" | grep -qE '^head\s+--lines=[0-9]+\s+'; then
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
SUGGESTION="rtk read $FILE --max-lines $LINES"
SUGGESTION="rtk read $FILE --head-lines $LINES"
fi
# --- JS/TS tooling ---
+4
View File
@@ -11,6 +11,10 @@ These override general Rust conventions:
3. **Lazy regex** — Put fixed patterns reused across calls in `LazyLock<Regex>`; keep runtime-dependent patterns local.
4. **Fallback pattern** — If filter fails, execute raw command unchanged. Never block the user.
5. **Exit code propagation** — `std::process::exit(code)` if underlying command fails.
6. **Parse args with `arg_tokenizer`** — every new command, flag, or arg-handling fix classifies
arguments through `tokenize`/`tokenize_with_options`, never a `starts_with('-')` or
`arg == "--flag"` scan. See [`src/core/README.md`](../../src/core/README.md#argument-tokenizer-arg_tokenizerrs)
for the four rules that go with it.
## Error Handling
+2 -1
View File
@@ -45,6 +45,7 @@ RTK intercepts shell commands and compresses their output before your agent read
| `ls` / `tree` | Tree format with file counts instead of one line per entry |
| `cat` / `read` | Smart file reading: signatures and structure over full bodies |
| `grep` / `rg` | Truncates long lines, groups matches by file |
| `ast-grep` | Groups structural matches by file, caps overflow |
| `git status` | Compact stat format, grouped by state |
| `git diff` | Reduced context, headers stripped |
| `git log` | Hash, author and subject only |
@@ -421,7 +422,7 @@ RTK supports 17 AI coding tools. Each integration rewrites shell commands to `rt
| **GitHub Copilot CLI** | `rtk init -g --copilot` | PreToolUse deny-with-suggestion (CLI limitation) |
| **Cursor** | `rtk init -g --agent cursor` | preToolUse hook (hooks.json) |
| **Gemini CLI** | `rtk init -g --gemini` | BeforeTool hook |
| **Codex** | `rtk init -g --codex` | AGENTS.md + RTK.md instructions |
| **Codex** | `rtk init -g --codex` | PreToolUse hook (`updatedInput`) + AGENTS.md |
| **Windsurf** | `rtk init -g --agent windsurf` | .windsurfrules (project-scoped) |
| **Cline / Roo Code** | `rtk init --agent cline` | .clinerules (project-scoped) |
| **OpenCode** | `rtk init -g --opencode` | Plugin TS (tool.execute.before) |
+2 -2
View File
@@ -62,8 +62,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|-------|---------|---------|
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% savings — these need filters |
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands averaging <30% savings — filters to improve |
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands with weighted savings rate <30%, net-negative ones included — filters to improve. Rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. |
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume). Each command's individual rate is weighted by volume before the outer average; commands that never had any input are skipped. |
| `recall_mode` | `sqlite` | Which recovery mode is active (`sqlite`/`tee`/`disabled`) |
| `recall_stats` | `[{"filter":"grep","mode":"sqlite","elisions":142,"recalls":9}]` | Per-filter counters: how often elided output is retrieved — calibrates filter caps. Filter names come from a fixed allowlist of rtk filter families; anything else is folded into `other`. No hashes, no paths, no command arguments, no output content. |
+12 -6
View File
@@ -38,7 +38,7 @@
### Hook Architecture (v0.9.5+)
> For the hook interception diagram and agent-specific JSON formats, see [TECHNICAL.md](TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](hooks/README.md).
> For the hook interception diagram and agent-specific JSON formats, see [TECHNICAL.md](TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](../../src/hooks/README.md).
Two hook strategies:
@@ -181,7 +181,7 @@ Savings by ecosystem:
### Module Breakdown
- **Command Modules**: `src/cmds/` — organized by ecosystem (git, rust, js, python, go, dotnet, cloud, system, ruby). Each ecosystem README lists its files.
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, retriever (recall store), tee, tee_file, config, toml_filter, display_helpers, telemetry
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, retriever (recall store), tee, tee_file, config, toml_filter, display_helpers, telemetry, arg_tokenizer
- **Hook System**: `src/hooks/` — init, rewrite, permissions, hook_cmd, hook_check, hook_audit, verify, trust, integrity
- **Analytics**: `src/analytics/` — gain, cc_economics, ccusage, session_cmd
@@ -571,7 +571,13 @@ When adding Python/Go module support:
### Utilities Layer
> For the full utilities API (`truncate`, `strip_ansi`, `execute_command`, `ruby_exec`, etc.), see [src/core/README.md](src/core/README.md). Used by most command modules.
> For the full utilities API (`truncate`, `strip_ansi`, `execute_command`, `ruby_exec`, etc.), see [src/core/README.md](../../src/core/README.md). Used by most command modules.
### Argument Handling
Every command that inspects its own arguments — which flags were passed, which tokens are paths, what to inject or strip — classifies them with `src/core/arg_tokenizer.rs`. String scans (`starts_with('-')`, `arg == "--flag"`) miss a flag's own value, attached values, short clusters and everything past `--`, which is where this module's whole bug class lives.
> For the predicate contract and the four rules that come with it (one grammar per subcommand, scope the lookup to the region the tool parses, inject before the boundary, detect and act with one rule), see [src/core/README.md](../../src/core/README.md#argument-tokenizer-arg_tokenizerrs).
### Package Manager Detection Pattern
@@ -872,7 +878,7 @@ Modules with Exit Code Preservation:
### Configuration
> For config file format, recall/tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
> For config file format, recall/tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](../../src/core/README.md).
Two tiers: **User settings** (`~/.config/rtk/config.toml`) and **LLM integration** (CLAUDE.md via `rtk init`).
@@ -997,7 +1003,7 @@ Overhead Sources:
## Extensibility Guide
> For the complete step-by-step process to add a new command (module file, enum variant, routing, tests, documentation), see [src/cmds/README.md — Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter).
> For the complete step-by-step process to add a new command (module file, enum variant, routing, tests, documentation), see [src/cmds/README.md — Adding a New Command Filter](../../src/cmds/README.md#adding-a-new-command-filter).
---
@@ -1035,7 +1041,7 @@ Overhead Sources:
## Resources
- **[TECHNICAL.md](TECHNICAL.md)**: Guided tour of end-to-end flow
- **[CONTRIBUTING.md](CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
- **[CONTRIBUTING.md](../../CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
- **CLAUDE.md**: Quick reference for AI agents (dev commands, build verification)
- **README.md**: User guide, installation, examples
- **Cargo.toml**: Dependencies, build profiles, package metadata
+3 -3
View File
@@ -166,7 +166,7 @@ rewrite_segment(seg, excluded) [src/discover/registry.rs]
| Step 4 — Already RTK → return as-is
|
| Step 5 — Special cases (short-circuit before classification)
| head -N / --lines=N → rewrite_line_range() → "rtk read file --max-lines N"
| head -N / -n N / --lines[= ]N / bare → rewrite_line_range() → "rtk read file --head-lines N"
| tail -N / -n N / --lines N → rewrite_line_range() → "rtk read file --tail-lines N"
| head/tail with unsupported flag (-c, -f) → None (skip rewrite)
| cat with incompatible flag (-A, -v, -e) → None (skip rewrite)
@@ -320,7 +320,7 @@ Start here, then drill down into each README for file-level details.
| [`cursor/`](../hooks/cursor/README.md) | Cursor IDE | Shell hook, empty JSON response requirement |
| [`cline/`](../hooks/cline/README.md) | Cline / Roo Code | Rules file (prompt-level, no programmatic hook) |
| [`windsurf/`](../hooks/windsurf/README.md) | Windsurf / Cascade | Rules file (workspace-scoped) |
| [`codex/`](../hooks/codex/README.md) | OpenAI Codex CLI | Awareness document, AGENTS.md integration |
| [`codex/`](../hooks/codex/README.md) | OpenAI Codex CLI | Native `PreToolUse` processor, hooks.json registration, AGENTS.md awareness |
| [`opencode/`](../hooks/opencode/README.md) | OpenCode | TypeScript plugin, zx library, in-place mutation |
---
@@ -338,7 +338,7 @@ RTK supports the following LLM agents through hook integrations:
| Gemini CLI | Rust binary | `rtk hook gemini` reads JSON | Yes (`hookSpecificOutput`) |
| Cline/Roo Code | Rules file | Prompt-level guidance | N/A (prompt) |
| Windsurf | Rules file | Prompt-level guidance | N/A (prompt) |
| Codex CLI | Awareness doc | AGENTS.md integration | N/A (prompt) |
| Codex CLI | Rust binary | `rtk hook codex` reads JSON | Yes (`updatedInput`) |
| OpenCode | TS plugin | `tool.execute.before` event | Yes (in-place mutation) |
> **Details**: [`hooks/README.md`](../hooks/README.md) has the full JSON schemas for each agent. [`src/hooks/README.md`](../src/hooks/README.md) covers installation, integrity verification, and the rewrite command.
@@ -41,7 +41,7 @@ Agent runs "cargo test"
| Factory Droid | Shell hook (`PreToolUse`, matcher `Execute`) | Yes |
| Cline / Roo Code | Rules file (prompt-level) | N/A |
| Windsurf | Rules file (prompt-level) | N/A |
| Codex CLI | AGENTS.md instructions | N/A |
| Codex CLI | Rust binary (`PreToolUse`) | Yes |
| Kilo Code | Rules file (prompt-level) | N/A |
| Google Antigravity | Rules file (prompt-level) | N/A |
| Mistral Vibe | Rust binary (`pre_tool`) | Yes |
@@ -210,10 +210,14 @@ rtk init --global --agent windsurf # creates .windsurfrules in current projec
### Codex CLI
```bash
rtk init --codex # project-scoped (AGENTS.md)
rtk init --global --codex # user-global (~/.codex/AGENTS.md)
rtk init --codex # project-scoped (.codex/hooks.json + AGENTS.md)
rtk init --global --codex # user-global ($CODEX_HOME or ~/.codex/)
rtk init --codex --uninstall # remove project-scoped integration
rtk init --global --codex --uninstall # remove user-global integration
```
Restart Codex after installation. Project-scoped hooks must be trusted when Codex prompts. The native `rtk hook codex` processor rewrites supported `Bash` commands through `PreToolUse.updatedInput`; Codex then applies its normal approval and sandbox checks to the rewritten command.
### Kilo Code
```bash
@@ -261,7 +265,7 @@ Strips only RTK's `[[hooks]]` block and the `~/.vibe/prompts/rtk.md` file. Any o
| **Plugin** | TypeScript, JavaScript, or Python in agent's plugin system | Transparent, in-place mutation when the agent allows it |
| **Rules file** | Prompt-level instructions | Guidance only — agent is told to prefer `rtk <cmd>` |
Rules file integrations (Cline, Windsurf, Codex, Kilo Code, Antigravity) rely on the model following instructions. Full hook integrations (Claude Code, Cursor, Gemini) are guaranteed — the command is rewritten before the agent sees it. Plugin integrations (OpenCode, Pi) use in-place mutation via the agent's TypeScript extension API.
Rules file integrations (Cline, Windsurf, Kilo Code, Antigravity) rely on the model following instructions. Full hook integrations (Claude Code, Cursor, Gemini, Codex) rewrite the command before execution. Plugin integrations (OpenCode, Pi) use in-place mutation via the agent's TypeScript extension API.
## Windows support
+2 -2
View File
@@ -67,8 +67,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|-------|---------|---------|
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% bash output reduction — these need filters |
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands averaging <30% bash output reduction — filters to improve. The example is a placeholder, not a measured value |
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands with a weighted bash output reduction <30%, net-negative ones included — filters to improve. The rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. The example is a placeholder, not a measured value |
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume); each command's own rate is weighted by volume before the outer average, and commands that never had any input are skipped |
### Ecosystem distribution
+1
View File
@@ -116,6 +116,7 @@ Every percentage below measures **bash output bytes removed** — the only thing
| `ls` | 80% | Tree format with file counts |
| `find` | 75% | Tree format |
| `grep` | 70% | Truncated lines, grouped by file |
| `ast-grep` | 85% | Grouped by file, capped overflow; `--json` passes through |
| `diff` | 65% | Context reduced |
| `wc` | 60% | Compact counts |
| `cat` / `head` / `tail <file>` | 60-80% | Smart file reading via `rtk read` |
+20 -2
View File
@@ -130,7 +130,9 @@ rtk read - [options] # Lecture depuis stdin
| Option | Court | Defaut | Description |
|--------|-------|--------|-------------|
| `--level` | `-l` | `minimal` | Niveau de filtrage : `none`, `minimal`, `aggressive` |
| `--max-lines` | `-m` | illimite | Nombre maximum de lignes |
| `--max-lines` | `-m` | illimite | Apercu structurel plafonne a N lignes (signatures et imports, pas les N premieres) |
| `--head-lines` | | illimite | Garde seulement les N premieres lignes, a l'octet pres |
| `--tail-lines` | | illimite | Garde seulement les N dernieres lignes, a l'octet pres |
| `--line-numbers` | `-n` | non | Afficher les numeros de ligne |
**Niveaux de filtrage :**
@@ -238,6 +240,21 @@ src/ls.rs:25:fn run_tree(...) src/ls.rs
---
### `rtk ast-grep` -- Recherche structurelle (AST)
**Objectif :** Remplace `ast-grep` avec une sortie groupee par fichier, plafonnee.
**Syntaxe :**
```bash
rtk ast-grep run -p '<pattern>' [chemin] [options]
```
Regroupe les correspondances par fichier, plafonnees a 5 par fichier et 50 au total ; le surplus est remplace par une note de comptage ("N more match line(s) in X" / "N more file(s) not shown"). ast-grep imprime une ligne par ligne source d'une correspondance, et une correspondance structurelle s'etend sur plusieurs lignes : le decompte porte donc sur les lignes, pas sur les correspondances. Les sorties que rtk ne sait pas decouper (`ast-grep scan`, `--heading`) passent telles quelles. Sur une recherche reelle dans ce depot, ~85% de reduction.
`--json` n'est pas filtre -- une demande explicite de sortie structuree passe telle quelle, sans compression.
---
### `rtk diff` -- Diff condense
**Objectif :** Diff ultra-condense entre deux fichiers (uniquement les lignes modifiees).
@@ -1276,6 +1293,7 @@ rtk verify
| `cargo test/build/clippy/check` | `rtk cargo ...` |
| `cat/head/tail <fichier>` | `rtk read <fichier>` |
| `rg/grep <pattern>` | `rtk grep <pattern>` |
| `ast-grep run -p <pattern>` | `rtk ast-grep run -p <pattern>` |
| `ls` | `rtk ls` |
| `tree` | `rtk tree` |
| `wc` | `rtk wc` |
@@ -1448,7 +1466,7 @@ Octets de sortie bash supprimes (voir [A propos de la reduction de sortie bash](
| Categorie | Commandes | Reduction sortie bash |
|-----------|-----------|-------------------|
| **Fichiers** | ls, tree, read, find, grep, diff | 60-80% |
| **Fichiers** | ls, tree, read, find, grep, ast-grep, diff | 60-85% |
| **Git** | status, log, diff, show, add, commit, push, pull | 75-92% |
| **GitHub** | pr, issue, run, api | 79-87% |
| **Tests** | cargo test, vitest, playwright, pytest, go test | 90-99% |
+35 -7
View File
@@ -2,7 +2,7 @@
## Scope
**Deployed hook artifacts** — the actual files installed on user machines by `rtk init`. These are shell scripts, TypeScript plugins, and rules files that run outside the Rust binary. They are **thin delegates**: parse agent-specific JSON, call `rtk rewrite` as a subprocess, format agent-specific response. Zero filtering logic lives here.
**Deployed hook artifacts** — the files and agent-specific configuration installed on user machines by `rtk init`. External scripts and plugins are thin delegates to `rtk rewrite`; native processors such as Codex call the same Rust rewrite registry directly. Zero filtering logic is duplicated in this directory.
Owns: per-agent hook scripts and configuration files for 11 supported agents (Claude Code, Copilot, Cursor, Cline, Windsurf, Codex, OpenCode, Hermes, Pi, Oh My Pi, Mistral Vibe).
@@ -27,14 +27,14 @@ LLM agent integrations that intercept CLI commands and route them through RTK fo
Agent runs command (e.g., "cargo test --nocapture")
-> Hook intercepts (PreToolUse / plugin event)
-> Reads JSON input, extracts command string
-> Calls `rtk rewrite "cargo test --nocapture"`
-> Uses the shared RTK rewrite registry
-> Registry matches pattern, returns "rtk cargo test --nocapture"
-> Hook sends response in agent-specific JSON format
-> Agent executes "rtk cargo test --nocapture" instead
-> Filtered output reaches LLM (up to 90% fewer bash output bytes)
```
All rewrite logic lives in the Rust binary (`src/discover/registry.rs`). Hook scripts are **thin delegates** that handle agent-specific JSON formats and call `rtk rewrite` for the actual decision. This ensures a single source of truth for all 70+ rewrite patterns.
All rewrite logic lives in the Rust binary (`src/discover/registry.rs`). External hook scripts call `rtk rewrite`; native Rust hook processors call the registry directly. This keeps one source of truth for all 70+ rewrite patterns.
## Directory Structure
@@ -45,7 +45,7 @@ Each agent subdirectory has its own README with hook-specific details:
- **[`cursor/`](cursor/README.md)** — Shell hook, Cursor JSON format, empty `{}` response requirement
- **[`cline/`](cline/README.md)** — Rules file (prompt-level), `.clinerules` project-local installation
- **[`windsurf/`](windsurf/README.md)** — Rules file (prompt-level), `.windsurfrules` workspace-scoped
- **[`codex/`](codex/README.md)** — Awareness document, `AGENTS.md` integration, `$CODEX_HOME` or `~/.codex/` location
- **[`codex/`](codex/README.md)** — Rust binary hook (`rtk hook codex`), `PreToolUse.updatedInput`, `.codex/hooks.json` / `$CODEX_HOME/hooks.json`, plus `AGENTS.md` awareness
- **[`opencode/`](opencode/README.md)** — TypeScript plugin, `zx` library, `tool.execute.before` event, in-place mutation
- **[`pi/`](pi/README.md)** — TypeScript extension, `tool_call` event, local `isBashToolCallEvent` guard, in-place mutation, `~/.pi/agent/extensions/`; **shared with Oh My Pi (OMP)** — OMP installs the same file at `.omp/extensions/` via its `legacy-pi-compat` layer
- **[`hermes/`](hermes/README.md)** — Python plugin, `pre_tool_call` hook, in-place terminal command mutation
@@ -62,7 +62,7 @@ Each agent subdirectory has its own README with hook-specific details:
| Gemini CLI | Rust binary (`rtk hook gemini`) | Transparent rewrite | Yes (`hookSpecificOutput`) |
| Cline / Roo Code | Custom instructions (rules file) | Prompt-level guidance | N/A |
| Windsurf | Custom instructions (rules file) | Prompt-level guidance | N/A |
| Codex CLI | AGENTS.md / instructions | Prompt-level guidance | N/A |
| Codex CLI | Rust binary (`rtk hook codex`) | Transparent rewrite | Yes (`updatedInput`) |
| OpenCode | TypeScript plugin (`tool.execute.before`) | In-place mutation | Yes |
| Pi | TypeScript extension (`tool_call` event) | In-place mutation | Yes |
| Oh My Pi (OMP) | TypeScript extension (`tool_call` event, shared with Pi) | In-place mutation | Yes |
@@ -110,6 +110,34 @@ Each agent subdirectory has its own README with hook-specific details:
Returns `{}` when no rewrite (Cursor requires JSON for all paths).
### Codex CLI (Rust Binary)
**Input** (stdin):
```json
{
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"permission_mode": "default",
"tool_input": { "command": "git status" }
}
```
**Output** (stdout, when rewritten):
```json
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": { "command": "rtk git status" }
}
}
```
The `allow` value is required by Codex to accept `updatedInput`; Codex still runs its native approval and sandbox checks after applying the replacement. Those checks classify the rewritten command, and Codex does not currently unwrap the `rtk` binary for its safe/dangerous-command heuristics. Missing or unknown permission modes and other no-rewrite cases produce no stdout.
### Copilot CLI (Rust Binary)
**Input** (stdin, camelCase, `toolArgs` is JSON-stringified):
@@ -277,9 +305,9 @@ New integrations must follow the [Exit Code Contract](#exit-code-contract) and [
| Tier | Mechanism | Maintenance | Examples |
|------|-----------|-------------|----------|
| **Full hook** | Shell script or Rust binary, intercepts commands via agent's hook API | High — must track agent API changes | Claude Code, Cursor, Copilot, Gemini |
| **Full hook** | Shell script or Rust binary, intercepts commands via agent's hook API | High — must track agent API changes | Claude Code, Cursor, Copilot, Gemini, Codex |
| **Plugin** | TypeScript/JS/Python plugin in agent's plugin system | Medium — agent manages loading | OpenCode, Hermes, Pi, Oh My Pi |
| **Rules file** | Prompt-level instructions the agent reads | Low — no code to break | Cline, Windsurf, Codex |
| **Rules file** | Prompt-level instructions the agent reads | Low — no code to break | Cline, Windsurf |
### Eligibility
+34 -3
View File
@@ -4,6 +4,37 @@
## Specifics
- Prompt-level guidance via awareness document -- no programmatic hook
- `../rtk-awareness-full.md` is written to `RTK.md` and referenced from `AGENTS.md` via `@RTK.md`. No hook, so the `full` level is always used regardless of `awareness.level`
- Installed to `$CODEX_HOME` when set, otherwise `~/.codex/`, by `rtk init --codex`
- Native Rust `PreToolUse` processor: `rtk hook codex`
- Transparently rewrites `tool_input.command` with Codex's `updatedInput` response
- Registers a `Bash` matcher in `.codex/hooks.json` (project) or `$CODEX_HOME/hooks.json` (global)
- Writes the shared awareness document selected by `awareness.level` to `RTK.md`, referenced from `AGENTS.md`
- Installed by `rtk init --codex` (project) or `rtk init -g --codex` (global)
- Uninstalled by adding `--uninstall` to the corresponding project or global command
Codex requires `permissionDecision: "allow"` in the hook response for `updatedInput` to take effect. Codex applies the replacement before its normal command approval and sandbox checks, so those native checks still run on the rewritten command. Codex's command safety classifier does not currently unwrap the `rtk` binary, so classification is based on the rewritten command. This can add prompts for known-safe commands or obscure signals for wrapped mutating commands such as `git push`.
RTK rewrites the documented Codex permission modes. Missing or unknown permission modes, no match, malformed JSON, unsupported commands, heredocs, substitutions, and file redirections fail open: the hook exits successfully without stdout and Codex executes the original command.
The Codex handler uses RTK's shared hook decision pipeline through `Host::Codex`.
RTK does not parse Codex execution rules or reuse another agent's permission
files: Codex's native execution layer remains responsible for those rules.
An internal `AskRewrite` still emits the required protocol-level `allow` with
`updatedInput`; it is not recorded internally as an explicit permission grant.
This preserves transparent rewriting but does not remove the classifier
limitation described above.
## History in workspace-write sandboxes
Command rewriting can work even when the sandbox prevents RTK from writing its
SQLite history database. If recording reports `SQLITE_CANTOPEN`, run
`rtk init --codex` outside the sandbox to see an optional Codex configuration
snippet using the actual database parent directory. The path follows
`RTK_DB_PATH`, then `tracking.database_path`, then the platform default.
To opt in, merge the printed `sandbox_workspace_write.writable_roots` entry into
your Codex `config.toml`, preserving existing entries. SQLite needs directory
access for journal/WAL files as well as the database itself. RTK only prints the
snippet; it does not change sandbox settings. Review custom paths before granting
access, and prefer a dedicated RTK data directory.
See the [Codex configuration reference](https://developers.openai.com/codex/config-reference/).
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn run(
println!("{}", "─".repeat(table_width));
println!(
"{:>3} {:<cmd_width$} {:>count_width$} {:>saved_width$} {:>6} {:>time_width$} {:<impact_width$}",
"#", "Command", "Count", "Saved", "Avg%", "Time", "Impact",
"#", "Command", "Count", "Saved", "Total%", "Time", "Impact",
cmd_width = cmd_width, count_width = count_width,
saved_width = saved_width, time_width = time_width,
impact_width = impact_width
+1
View File
@@ -294,6 +294,7 @@ Adding a new filter or command requires changes in multiple places. For TOML-vs-
- Add `.tee("label")` when the filter parses structured output (enables raw output recovery on failure)
- **Exit codes**: handled automatically by `run_filtered()` — just return its result
- **Truncation**: if the filter caps any list at N items, emit `force_tee_tail_hint` (flat lists) or `force_tee_hint` (multi-line blocks) so the agent can recover hidden items — see [Internal Truncation Recovery](#internal-truncation-recovery). Use a named constant for the cap; derive the offset from it (`MAX_XXX + 1`)
- **Arguments**: if the filter inspects its args at all — which flags were passed, which are paths, what to inject or strip — classify them with [`arg_tokenizer`](../core/README.md#argument-tokenizer-arg_tokenizerrs), never a string scan. Write the `takes_value` predicate from the tool's own `--help` and check it against the real binary
2. **Register module**:
- Ecosystem `mod.rs` files use `automod::dir!()` — any `.rs` file in the directory becomes a public module automatically. No manual `pub mod` needed, but be aware: WIP or helper files will also be exposed. Only commit command-ready modules.
- Add variant to `Commands` enum in `main.rs` with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]`
File diff suppressed because it is too large. Load diff
+1
View File
@@ -5,6 +5,7 @@
## Specifics
- **git.rs** uses `trailing_var_arg = true` + `allow_hyphen_values = true` so native git flags (`--oneline`, `--cached`, etc.) pass through correctly
- Flag grammar (which flags take a value, what `-u`/`-p` mean) is per-subcommand, not shared wholesale between `log`/`diff`/`show`/`stash show` — see [`src/core/README.md`](../../core/README.md#argument-tokenizer-arg_tokenizerrs)
- Default `git status` uses `--porcelain -b` so the compact output never exceeds raw `git status` (an untracked directory collapses to a single line, matching git's default); branch/short-only flags reuse the compact path, other explicit args still pass through unchanged
- Global git options (`-C`, `--git-dir`, `--work-tree`, `--no-pager`) are prepended before the subcommand
- Exit code propagation is critical for CI/CD pipelines
+141 -16
View File
@@ -462,29 +462,54 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32>
"gh",
&label,
format_pr_checks,
RunOptions::stdout_only()
.early_exit_on_failure()
.no_trailing_newline(),
RunOptions::stdout_only().no_trailing_newline(),
)
}
fn format_pr_checks(stdout: &str) -> String {
let mut passed = 0;
let mut failed = 0;
let mut pending = 0;
let mut failed_checks = Vec::new();
// `gh pr checks --watch` appends each poll's table when stdout is not a TTY.
// Keep the latest row for each check so status transitions are reflected
// without inflating the summary.
let mut checks: Vec<(String, String, PrCheckStatus, String)> = Vec::new();
for line in stdout.lines() {
if line.contains("[ok]") || line.contains("pass") {
passed += 1;
} else if line.contains("[x]") || line.contains("fail") {
failed += 1;
failed_checks.push(line.trim().to_string());
} else if line.contains('*') || line.contains("pending") {
pending += 1;
let Some((name, link, status)) = parse_pr_check_line(line) else {
continue;
};
if let Some(check) = checks
.iter_mut()
.find(|check| check.0 == name && check.1 == link)
{
check.2 = status;
check.3 = line.trim().to_string();
} else {
checks.push((
name.to_string(),
link.to_string(),
status,
line.trim().to_string(),
));
}
}
let passed = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Passed)
.count();
let failed = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Failed)
.count();
let pending = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Pending)
.count();
let other = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Other)
.count();
let mut out = String::new();
out.push_str("CI Checks Summary:\n");
out.push_str(&format!(" [ok] Passed: {}\n", passed));
@@ -492,7 +517,14 @@ fn format_pr_checks(stdout: &str) -> String {
if pending > 0 {
out.push_str(&format!(" [pending] Pending: {}\n", pending));
}
if !failed_checks.is_empty() {
if other > 0 {
out.push_str(&format!(" [skip] Skipped/cancelled: {}\n", other));
}
let failed_checks = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Failed)
.map(|check| check.3.as_str());
if failed > 0 {
out.push_str("\n Failed checks:\n");
for check in failed_checks {
out.push_str(&format!(" {}\n", check));
@@ -501,6 +533,31 @@ fn format_pr_checks(stdout: &str) -> String {
out
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PrCheckStatus {
Passed,
Failed,
Pending,
Other,
}
fn parse_pr_check_line(line: &str) -> Option<(&str, &str, PrCheckStatus)> {
let mut fields = line.split('\t');
let name = fields.next()?.trim();
let status = match fields.next()?.trim() {
"pass" => PrCheckStatus::Passed,
"fail" => PrCheckStatus::Failed,
"pending" | "*" => PrCheckStatus::Pending,
// skipping, cancelled, and whatever a later gh adds. Counted rather than
// dropped, so the totals add up to the checks gh listed and a cancelled
// run cannot read as "nothing wrong".
_ => PrCheckStatus::Other,
};
let link = fields.nth(1).unwrap_or("").trim();
(!name.is_empty()).then_some((name, link, status))
}
fn pr_status(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32> {
if should_passthrough_pr_status(args) {
let mut passthrough_args = Vec::with_capacity(args.len() + 1);
@@ -1121,6 +1178,74 @@ mod tests {
assert!(extract_identifier_and_extra_args(&args).is_none());
}
// --- format_pr_checks tests ---
#[test]
fn test_format_pr_checks_counts_each_watch_snapshot_once() {
let output = concat!(
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
"Analyze (actions)\tpass\t42s\thttps://example.com/actions\n",
"Analyze (rust)\tpass\t2m\thttps://example.com/rust\n",
);
let result = format_pr_checks(output);
assert!(result.contains("Passed: 2"));
assert!(!result.contains("Passed: 4"));
}
#[test]
fn test_format_pr_checks_uses_final_status_for_each_check() {
let output = concat!(
"Lint\tpending\t0\thttps://example.com/lint\n",
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
"Lint\tpass\t30s\thttps://example.com/lint\n",
"Unit tests\tfail\t1m\thttps://example.com/unit\n",
);
let result = format_pr_checks(output);
assert!(result.contains("Passed: 1"));
assert!(result.contains("Failed: 1"));
assert!(!result.contains("Pending:"));
assert!(result.contains("Unit tests\tfail"));
}
#[test]
fn test_format_pr_checks_keeps_same_name_checks_with_different_links() {
let output = concat!(
"build\tpass\t1m\thttps://example.com/workflow-a\n",
"build\tfail\t1m\thttps://example.com/workflow-b\n",
);
let result = format_pr_checks(output);
assert!(result.contains("Passed: 1"));
assert!(result.contains("Failed: 1"));
}
/// Rows exactly as `gh` prints them when stdout is a pipe: five tab-separated
/// fields, the fifth (the description) usually empty. Captured from
/// `gh pr checks --watch` against a run that was still going, so the pending
/// rows here are the shape a real transition arrives in.
#[test]
fn test_format_pr_checks_handles_real_gh_row_shape() {
let output = concat!(
"test (macos-latest)\tpending\t0\thttps://example.com/job/1\t\n",
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
"test (macos-latest)\tpass\t3m1s\thttps://example.com/job/1\t\n",
"clippy\tpass\t28s\thttps://example.com/job/2\t\n",
"license/cla\tpass\t0\thttps://cla.example.com/pr/1\tContributor License Agreement is signed.\n",
);
let result = format_pr_checks(output);
assert!(result.contains("Passed: 3"), "got:\n{result}");
assert!(!result.contains("Pending:"), "got:\n{result}");
}
// --- parse_optional_identifier tests ---
#[test]
+1525 -441
View File
File diff suppressed because it is too large. Load diff
+270 -71
View File
@@ -1,5 +1,7 @@
//! Filters golangci-lint output, grouping issues by rule.
use crate::core::arg_tokenizer::{self, Dialect, TokenKind, ValueSpec};
use crate::core::args_utils;
use crate::core::config;
use crate::core::runner;
use crate::core::stream::exec_capture;
@@ -10,28 +12,94 @@ use serde::Deserialize;
use std::collections::HashMap;
use std::ffi::OsString;
const GOLANGCI_SUBCOMMANDS: &[&str] = &[
"cache",
"completion",
"config",
"custom",
"fmt",
"formatters",
"help",
"linters",
"migrate",
"run",
"version",
];
fn is_subcommand(name: &str) -> bool {
matches!(
name,
"cache"
| "completion"
| "config"
| "custom"
| "fmt"
| "formatters"
| "help"
| "linters"
| "migrate"
| "run"
| "version"
)
}
const GLOBAL_FLAGS_WITH_VALUE: &[&str] = &[
"-c",
"--color",
"--config",
"--cpu-profile-path",
"--mem-profile-path",
"--trace-path",
];
/// golangci-lint's *global* grammar: the value-taking flags accepted before a subcommand. `-c`
/// is `--config`'s shorthand; this list is wider than `--help`'s "Global Flags" section, which
/// omits several of these.
///
/// Solo-only, like every short flag here: Cobra does not let a value-taking shorthand sit
/// inside a cluster (`golangci-lint -vc foo.yml run` is "unknown shorthand flag: 'c' in -c",
/// verified against 2.13.1). Reading one as value-taking there swallowed the next token --
/// `-Egosec run` lost `run`, and with it the subcommand detection this list exists for.
fn global_takes_value(kind: TokenKind, name: &str) -> Option<ValueSpec> {
match kind {
TokenKind::Long => matches!(
name,
"color" | "config" | "cpu-profile-path" | "mem-profile-path" | "trace-path"
)
.then(ValueSpec::value),
TokenKind::Short => (name == "c").then(ValueSpec::solo_only),
_ => None,
}
}
/// The `run` subcommand's grammar -- a wider list than [`global_takes_value`], which is scoped
/// to the flags valid before a subcommand. Missing an entry here risks a value like
/// `--path-prefix --out-format` tokenizing as its own flag and being misdetected by
/// [`has_output_flag`].
fn run_takes_value(kind: TokenKind, name: &str) -> Option<ValueSpec> {
// The one exception to one-grammar-per-command (`src/core/README.md`), earned by a strict
// subset: every flag valid before `run` stays valid after it. Grammars that merely
// intersect get a table each instead.
if let Some(spec) = global_takes_value(kind, name) {
return Some(spec);
}
if OUTPUT_PATH_FLAGS.contains(&name) && kind == TokenKind::Long {
return Some(ValueSpec::value());
}
match kind {
TokenKind::Long => matches!(
name,
"build-tags"
| "concurrency"
| "default"
| "disable"
| "enable"
| "enable-only"
| "issues-exit-code"
| "max-issues-per-linter"
| "max-same-issues"
| "modules-download-mode"
| "new-from-merge-base"
| "new-from-patch"
| "new-from-rev"
// v1-only legacy flag (golangci-lint 2.x's --help no longer lists it, replaced
// by output.json.path/etc.), kept for v1 installs since has_output_flag checks
// for it explicitly.
| "out-format"
| "path-mode"
| "path-prefix"
// Deprecated in 2.x but still value-taking there ("flag needs an argument"),
// and current in the 1.x installs run_filtered still supports.
| "deadline"
| "exclude"
| "presets"
| "skip-dirs"
| "skip-files"
| "timeout"
)
.then(ValueSpec::value),
// `-e`/`-p` are 1.x's --exclude/--presets; 2.x rejects them outright either way.
TokenKind::Short => matches!(name, "D" | "E" | "e" | "j" | "p").then(ValueSpec::solo_only),
_ => None,
}
}
#[derive(Debug, PartialEq, Eq)]
struct RunInvocation {
@@ -123,6 +191,7 @@ pub(crate) fn detect_major_version() -> u32 {
}
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let args = &args_utils::restore_double_dash(args);
match classify_invocation(args) {
Invocation::FilteredRun(invocation) => run_filtered(args, &invocation, verbose),
Invocation::Passthrough => run_passthrough(args, verbose),
@@ -132,15 +201,16 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
fn run_filtered(original_args: &[String], invocation: &RunInvocation, verbose: u8) -> Result<i32> {
let version = detect_major_version();
let filtered_args = build_filtered_args(invocation, version);
let mut cmd = resolved_command("golangci-lint");
for arg in build_filtered_args(invocation, version) {
for arg in &filtered_args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!(
"Running: {}",
format_command("golangci-lint", &build_filtered_args(invocation, version))
format_command("golangci-lint", &filtered_args)
);
}
@@ -180,58 +250,28 @@ fn classify_invocation(args: &[String]) -> Invocation {
}
}
/// Finds the index in `args` of the first non-flag token, stopping (and returning `None`)
/// entirely at `--` or at a non-flag token that isn't a recognized subcommand — mirroring
/// golangci-lint's own arg parsing just enough to locate `run`, not fully replicate it.
fn find_subcommand_index(args: &[String]) -> Option<usize> {
let mut i = 0;
while i < args.len() {
let arg = args[i].as_str();
let tokens = arg_tokenizer::tokenize_grammar(args, &global_takes_value, Dialect::Posix);
if arg == "--" {
return None;
}
if !arg.starts_with('-') {
if GOLANGCI_SUBCOMMANDS.contains(&arg) {
return Some(i);
for token in &tokens {
match token.kind {
TokenKind::DashDash => return None,
// A bare "-" (e.g. a stdin placeholder) is unrecognized-flag-like, not a stopping
// condition -- keep scanning past it, same as any other unrecognized `-`-prefixed
// token, instead of treating it as "no subcommand found."
TokenKind::Positional if token.is_free_positional() && token.text != "-" => {
return is_subcommand(token.text).then_some(token.source_index);
}
return None;
_ => {}
}
if let Some(flag) = split_flag_name(arg) {
if golangci_flag_takes_separate_value(arg, flag) {
i += 1;
}
}
i += 1;
}
None
}
fn split_flag_name(arg: &str) -> Option<&str> {
if arg.starts_with("--") {
return Some(arg.split_once('=').map(|(flag, _)| flag).unwrap_or(arg));
}
if arg.starts_with('-') {
return Some(arg);
}
None
}
fn golangci_flag_takes_separate_value(arg: &str, flag: &str) -> bool {
if !GLOBAL_FLAGS_WITH_VALUE.contains(&flag) {
return false;
}
if arg.starts_with("--") && arg.contains('=') {
return false;
}
true
}
fn build_filtered_args(invocation: &RunInvocation, version: u32) -> Vec<String> {
let mut args = invocation.global_args.clone();
args.push("run".to_string());
@@ -249,12 +289,41 @@ fn build_filtered_args(invocation: &RunInvocation, version: u32) -> Vec<String>
args
}
/// The nine `--output.<format>.path` sinks golangci-lint 2.x accepts, enumerated rather than
/// pattern-matched: `starts_with("output.")` would also swallow spellings golangci rejects.
/// One list, read by both the value-taking predicate and the collision check, so they cannot
/// drift apart.
const OUTPUT_PATH_FLAGS: &[&str] = &[
"output.checkstyle.path",
"output.code-climate.path",
"output.html.path",
"output.json.path",
"output.junit-xml.path",
"output.sarif.path",
"output.tab.path",
"output.teamcity.path",
"output.text.path",
];
/// True when RTK's own `--output.json.path stdout` would collide with what the user asked for:
/// they already configured the json sink (whatever its destination -- golangci takes one path
/// per format), or they directed some other format at stdout, where two reports would
/// interleave and the json parse would choke on whichever landed first. A *file* sink for some
/// other format takes nothing away from stdout, so RTK still injects there or it is left with
/// nothing to parse.
fn has_output_flag(args: &[String]) -> bool {
args.iter().any(|a| {
a == "--out-format"
|| a.starts_with("--out-format=")
|| a == "--output.json.path"
|| a.starts_with("--output.json.path=")
let tokens = arg_tokenizer::tokenize_grammar(args, &run_takes_value, Dialect::Posix);
tokens.iter().any(|t| {
if t.kind != TokenKind::Long {
return false;
}
match t.text {
"out-format" | "output.json.path" => true,
other => {
OUTPUT_PATH_FLAGS.contains(&other)
&& t.value(&tokens).is_none_or(|dest| dest == "stdout")
}
}
})
}
@@ -533,6 +602,47 @@ mod tests {
);
}
#[test]
fn test_classify_invocation_with_short_flag_separate_value_uses_filtered_path() {
// -c takes a separate-token value; its value ("foo.yml") must not be mistaken for
// the subcommand.
assert_eq!(
classify_invocation(&[
"-c".into(),
"foo.yml".into(),
"run".into(),
"./...".into(),
]),
Invocation::FilteredRun(RunInvocation {
global_args: vec!["-c".into(), "foo.yml".into()],
run_args: vec!["./...".into()],
})
);
}
#[test]
fn test_classify_invocation_dashdash_before_subcommand_is_passthrough() {
// `--` ends option parsing before any subcommand was found; golangci-lint's own
// parser gets to decide what follows, not rtk's filter.
assert_eq!(
classify_invocation(&["--".into(), "run".into()]),
Invocation::Passthrough
);
}
#[test]
fn test_classify_invocation_bare_dash_before_subcommand_uses_filtered_path() {
// Regression: a bare "-" (e.g. a stdin placeholder) is unrecognized-flag-like, not a
// stopping condition -- must not be mistaken for "no subcommand found."
assert_eq!(
classify_invocation(&["-".into(), "run".into(), "./...".into()]),
Invocation::FilteredRun(RunInvocation {
global_args: vec!["-".into()],
run_args: vec!["./...".into()],
})
);
}
#[test]
fn test_classify_invocation_with_inline_value_flag_uses_filtered_path() {
assert_eq!(
@@ -589,6 +699,95 @@ mod tests {
);
}
#[test]
fn test_has_output_flag_ignores_positional_after_dashdash() {
// Regression: a positional argument literally named "--out-format" after `--` (e.g.
// a package path to lint) must not be mistaken for the real flag.
assert!(!has_output_flag(&[
"./...".to_string(),
"--".to_string(),
"--out-format".to_string(),
]));
assert!(has_output_flag(&["--out-format=json".to_string()]));
assert!(has_output_flag(&["--output.json.path".to_string()]));
}
#[test]
fn test_has_output_flag_sees_every_output_destination() {
// golangci-lint 2.x has one --output.<format>.path per format; RTK injecting a second
// sink makes it write two reports to stdout and the JSON parse then fails.
for flag in [
"--output.text.path",
"--output.tab.path",
"--output.sarif.path",
"--output.checkstyle.path",
"--output.code-climate.path",
"--output.html.path",
"--output.junit-xml.path",
"--output.teamcity.path",
"--output.json.path",
] {
assert!(
has_output_flag(&[flag.to_string(), "stdout".to_string()]),
"{flag} is a user-chosen destination"
);
}
assert!(!has_output_flag(&["--tests".to_string()]));
}
#[test]
fn test_run_level_value_flags_swallow_their_own_values() {
// `-e '--out-format'` is 1.x's --exclude pattern, not an output flag.
assert!(!has_output_flag(&[
"-e".to_string(),
"--out-format".to_string()
]));
assert!(!has_output_flag(&[
"--concurrency".to_string(),
"--output.json.path".to_string()
]));
}
#[test]
fn test_has_output_flag_does_not_misread_a_run_level_flags_value() {
// --path-prefix's separate-token value must not be misdetected as the real output flag.
assert!(!has_output_flag(&[
"--path-prefix".to_string(),
"--output.json.path".to_string(),
]));
assert!(!has_output_flag(&[
"--disable".to_string(),
"errcheck".to_string(),
]));
assert!(!has_output_flag(&["--timeout".to_string(), "30s".to_string()]));
}
#[test]
fn test_clustered_short_flag_does_not_swallow_the_subcommand() {
// Cobra rejects a value-taking shorthand inside a cluster ("unknown shorthand flag:
// 'c' in -c", golangci-lint 2.13.1), so reading `-Egosec`'s trailing `c` as --config
// and eating `run` lost the subcommand and with it all filtering.
let args: Vec<String> = ["-Egosec", "run"].iter().map(|a| a.to_string()).collect();
assert_eq!(find_subcommand_index(&args), Some(1));
// Solo, it still takes its value -- that spelling golangci-lint does accept.
let args: Vec<String> = ["-c", "cfg.yml", "run"].iter().map(|a| a.to_string()).collect();
assert_eq!(find_subcommand_index(&args), Some(2));
// And the attached spelling is untouched by the solo-only rule.
let args: Vec<String> = ["-cCfg.yml", "run"].iter().map(|a| a.to_string()).collect();
assert_eq!(find_subcommand_index(&args), Some(1));
}
#[test]
fn test_golangci_run_takes_value_links_out_format_separate_token_value() {
// --out-format is a v1-only legacy flag; its value must still link, not tokenize as an
// unlinked Positional.
let args = vec!["--out-format".to_string(), "json".to_string()];
let tokens = arg_tokenizer::tokenize_grammar(&args, &run_takes_value, Dialect::Posix);
assert!(tokens[0].linked.is_some(), "\"json\" must link to --out-format");
}
#[test]
fn test_filter_golangci_v2_fields_parse_cleanly() {
// v2 JSON includes Severity, SourceLines, Offset — must not panic
+43
View File
@@ -72,6 +72,21 @@ const NPM_SUBCOMMANDS: &[&str] = &[
"start",
"stop",
"restart",
"completion",
"edit",
"explore",
"find-dupes",
"help-search",
"hook",
"install-ci-test",
"install-test",
"ll",
"org",
"query",
"run-script",
"sbom",
"shrinkwrap",
"unstar",
];
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<i32> {
@@ -257,6 +272,34 @@ npm notice
assert!(!needs_run_injection(&["run", "build"]));
}
#[test]
fn test_extended_official_subcommands_do_not_inject_run() {
let subcommands = [
"completion",
"edit",
"explore",
"find-dupes",
"help-search",
"hook",
"install-ci-test",
"install-test",
"ll",
"org",
"query",
"run-script",
"sbom",
"shrinkwrap",
"unstar",
];
for subcommand in subcommands {
assert!(
NPM_SUBCOMMANDS.contains(&subcommand),
"npm {subcommand} must be routed as a native subcommand"
);
}
}
#[test]
fn test_filter_npm_output_empty() {
let output = "\n\n\n";
+230
View File
@@ -0,0 +1,230 @@
//! Filters `ast-grep run` plain-mode output by grouping matches by file and
//! capping how many are shown. `--json` is left near-passthrough (explicit
//! structured-output request — see Correctness vs Token Savings).
use crate::core::stream::exec_capture;
use crate::core::tracking;
use crate::core::utils::resolved_command;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::LazyLock;
/// Matches the `path:line:` prefix ast-grep emits for every match/context line.
static MATCH_LINE_RE: LazyLock<regex::Regex> =
LazyLock::new(|| regex::Regex::new(r"^(?P<file>[^:]+):(?P<line>\d+):(?P<content>.*)$").unwrap());
const DEFAULT_MAX_TOTAL: usize = 50;
const DEFAULT_MAX_PER_FILE: usize = 5;
/// Counts non-blank lines that are not `path:line:content`.
///
/// Plain `ast-grep run` output is made up entirely of that shape. Other modes
/// are not: in an `ast-grep scan` diagnostic only the ` ┌─ a.rs:2:13` locator
/// parses, while the rule id, severity, message and source line do not, and
/// `--heading` mode and Windows drive-letter paths (`C:\src\a.rs`, which
/// `[^:]+` cannot match) fail to parse the same way. Grouping such a shape
/// would keep whichever lines happen to parse and discard the rest, so any
/// non-zero count leaves the output alone. `search.rs::unparsed_signal` guards
/// grep/rg with the same rule.
fn unparsed_signal(raw: &str) -> usize {
raw.lines()
.filter(|line| !line.trim().is_empty() && !MATCH_LINE_RE.is_match(line))
.count()
}
/// Groups raw `ast-grep run` plain output by file, keeping at most
/// `max_per_file` lines per file and `max_total` lines overall. Every line the
/// caps hold back is counted in a hint, so nothing disappears silently; any
/// other output shape is returned unchanged.
fn filter_ast_grep(raw: &str, max_per_file: usize, max_total: usize) -> String {
if unparsed_signal(raw) > 0 {
return raw.to_string();
}
let mut by_file: HashMap<&str, Vec<(usize, &str)>> = HashMap::new();
let mut order: Vec<&str> = Vec::new();
for line in raw.lines() {
let Some(caps) = MATCH_LINE_RE.captures(line) else {
continue;
};
let file = caps.name("file").unwrap().as_str();
let line_num: usize = caps.name("line").unwrap().as_str().parse().unwrap_or(0);
let content = caps.name("content").unwrap().as_str();
if !by_file.contains_key(file) {
order.push(file);
}
by_file.entry(file).or_default().push((line_num, content));
}
if order.is_empty() {
return raw.to_string();
}
let mut out = String::new();
let mut shown_total = 0;
let mut skipped_files = 0;
for file in &order {
let entries = &by_file[file];
if shown_total >= max_total {
skipped_files += 1;
continue;
}
let mut shown_here = 0;
for (line_num, content) in entries.iter().take(max_per_file) {
if shown_total >= max_total {
break;
}
out.push_str(file);
out.push(':');
out.push_str(&line_num.to_string());
out.push(':');
out.push_str(content);
out.push('\n');
shown_total += 1;
shown_here += 1;
}
// `shown_here`, not `max_per_file`: `max_total` can cut a file short of
// its own cap, and the hint has to cover every line this loop skipped.
// ast-grep prints one line per matched source line and a structural
// match spans several, so the unit is lines rather than matches.
if entries.len() > shown_here {
out.push_str(&format!(
" … {} more match line(s) in {}\n",
entries.len() - shown_here,
file
));
}
}
if skipped_files > 0 {
out.push_str(&format!(
"… {} more file(s) with matches not shown (use --json or narrow the pattern)\n",
skipped_files
));
}
out
}
pub fn run(args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let real_cmd = format!("ast-grep {}", args.join(" "));
let is_json = args.iter().any(|a| a == "--json" || a.starts_with("--json="));
let mut cmd = resolved_command("ast-grep");
cmd.args(args);
let result = exec_capture(&mut cmd).context("Failed to execute ast-grep")?;
let filtered_owned;
let filtered: &str = if is_json {
&result.stdout
} else {
filtered_owned = filter_ast_grep(&result.stdout, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
&filtered_owned
};
let shown = crate::core::guard::never_worse(&result.stdout, filtered);
timer.track(&real_cmd, "rtk ast-grep", &result.stdout, shown);
print!("{}", shown);
if !result.stderr.is_empty() {
eprint!("{}", result.stderr);
}
Ok(result.exit_code)
}
#[cfg(test)]
mod tests {
use super::*;
fn count_tokens(s: &str) -> usize {
s.split_whitespace().count()
}
#[test]
fn test_groups_and_caps_by_file() {
let input = "\
src/a.rs:1:fn foo() {}
src/a.rs:2:fn bar() {}
src/a.rs:3:fn baz() {}
src/b.rs:10:fn qux() {}
";
let out = filter_ast_grep(input, 2, 50);
assert!(out.contains("src/a.rs:1:"));
assert!(out.contains("src/a.rs:2:"));
assert!(!out.contains("src/a.rs:3:"));
assert!(out.contains("1 more match line(s) in src/a.rs"));
assert!(out.contains("src/b.rs:10:"));
}
#[test]
fn test_empty_input() {
assert_eq!(filter_ast_grep("", 5, 50), "");
}
#[test]
fn test_unparseable_input_falls_back_unchanged() {
let input = "no colons here\njust plain text\n";
assert_eq!(filter_ast_grep(input, 5, 50), input);
}
/// A scan diagnostic parses only on its locator line, so grouping it would
/// keep ` ┌─ a.rs:2:13` and discard the rule id, severity, message and
/// source line.
#[test]
fn test_scan_diagnostic_shape_passes_through() {
let input = "\
warning[no-unwrap]: avoid unwrap
┌─ a.rs:2:13
│
2 │ let x = foo().unwrap();
│ ^^^^^^^^^^^^^^
";
assert_eq!(filter_ast_grep(input, 5, 50), input);
}
/// `max_total` can cut a file short before its own `max_per_file` cap is
/// reached; the per-file hint must still account for the remainder.
#[test]
fn test_total_cap_hints_lines_it_cut() {
let input = "\
a.rs:1:one
a.rs:2:two
a.rs:3:three
a.rs:4:four
a.rs:5:five
b.rs:1:six
b.rs:2:seven
b.rs:3:eight
";
let out = filter_ast_grep(input, 5, 6);
assert!(out.contains("b.rs:1:six"), "{out}");
assert!(!out.contains("b.rs:2:seven"), "{out}");
assert!(
out.contains("2 more match line(s) in b.rs"),
"cut lines must be hinted, got: {out}"
);
}
#[test]
fn test_real_fixture_savings() {
let input = include_str!("../../../tests/fixtures/ast_grep_lazylock_raw.txt");
let output = filter_ast_grep(input, DEFAULT_MAX_PER_FILE, DEFAULT_MAX_TOTAL);
let input_tokens = count_tokens(input);
let output_tokens = count_tokens(&output);
let savings = 100.0 - (output_tokens as f64 / input_tokens as f64 * 100.0);
assert!(
savings >= 60.0,
"ast-grep filter: expected >=60% savings, got {:.1}% ({} -> {} tokens)",
savings,
input_tokens,
output_tokens
);
}
}
+262 -22
View File
@@ -5,12 +5,14 @@ use crate::core::guard::never_worse;
use crate::core::tracking;
use anyhow::{Context, Result};
use std::fs;
use std::io::{self, Read as IoRead, Write};
use std::path::Path;
pub fn run(
file: &Path,
level: FilterLevel,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
line_numbers: bool,
verbose: u8,
@@ -22,8 +24,25 @@ pub fn run(
}
// Read file content
let content = fs::read_to_string(file)
let bytes = fs::read(file)
.with_context(|| format!("Failed to read file: {}", file.display()))?;
if level == FilterLevel::None && !line_numbers {
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
io::stdout()
.lock()
.write_all(window)
.context("Failed to write line window")?;
timer.track(
&format!("cat {}", file.display()),
"rtk read",
&String::from_utf8_lossy(&bytes),
&String::from_utf8_lossy(window),
);
return Ok(());
}
}
let content = String::from_utf8(bytes)
.with_context(|| format!("Failed to decode file: {}", file.display()))?;
// Detect language from extension
let lang = file
@@ -64,7 +83,7 @@ pub fn run(
);
}
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
let (raw, rtk_output) = if line_numbers {
(
@@ -88,12 +107,11 @@ pub fn run(
pub fn run_stdin(
level: FilterLevel,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
line_numbers: bool,
verbose: u8,
) -> Result<()> {
use std::io::{self, Read as IoRead};
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -101,11 +119,27 @@ pub fn run_stdin(
}
// Read from stdin
let mut content = String::new();
let mut bytes = Vec::new();
io::stdin()
.lock()
.read_to_string(&mut content)
.read_to_end(&mut bytes)
.context("Failed to read from stdin")?;
if level == FilterLevel::None && !line_numbers {
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
io::stdout()
.lock()
.write_all(window)
.context("Failed to write line window")?;
timer.track(
"cat - (stdin)",
"rtk read -",
&String::from_utf8_lossy(&bytes),
&String::from_utf8_lossy(window),
);
return Ok(());
}
}
let content = String::from_utf8(bytes).context("Failed to decode stdin")?;
// No file extension, so use Unknown language
let lang = Language::Unknown;
@@ -132,7 +166,7 @@ pub fn run_stdin(
);
}
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
let (raw, rtk_output) = if line_numbers {
(
@@ -162,20 +196,12 @@ fn format_with_line_numbers(content: &str) -> String {
fn apply_line_window(
content: &str,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
lang: &Language,
) -> String {
if let Some(tail) = tail_lines {
if tail == 0 {
return String::new();
}
let lines: Vec<&str> = content.lines().collect();
let start = lines.len().saturating_sub(tail);
let mut result = lines[start..].join("\n");
if content.ends_with('\n') {
result.push('\n');
}
return result;
if let Some(window) = byte_line_window(content.as_bytes(), head_lines, tail_lines) {
return String::from_utf8_lossy(window).into_owned();
}
if let Some(max) = max_lines {
@@ -185,6 +211,61 @@ fn apply_line_window(
content.to_string()
}
/// First `n` lines, sliced on byte offsets rather than round-tripped through
/// `lines()`, so CRLF endings and an unterminated final line survive verbatim.
/// `\n` is ASCII, so valid UTF-8 input also stays valid after slicing.
fn head_window(content: &[u8], n: usize) -> &[u8] {
if n == 0 {
return &[];
}
let mut seen = 0;
for (idx, &byte) in content.iter().enumerate() {
if byte == b'\n' {
seen += 1;
if seen == n {
return &content[..=idx];
}
}
}
content
}
/// Last `n` lines, byte-sliced for the same fidelity reasons as `head_window`.
/// A trailing newline terminates the final line instead of starting a new one,
/// so it is excluded before counting separators backwards — otherwise `n` would
/// select one line too few for newline-terminated input.
fn tail_window(content: &[u8], n: usize) -> &[u8] {
if n == 0 {
return &[];
}
let search_end = match content.last() {
Some(b'\n') => content.len() - 1,
_ => content.len(),
};
let mut seen = 0;
for idx in (0..search_end).rev() {
if content[idx] == b'\n' {
seen += 1;
if seen == n {
return &content[idx + 1..];
}
}
}
content
}
fn byte_line_window(
content: &[u8],
head_lines: Option<usize>,
tail_lines: Option<usize>,
) -> Option<&[u8]> {
if let Some(head) = head_lines {
Some(head_window(content, head))
} else {
tail_lines.map(|tail| tail_window(content, tail))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -203,7 +284,7 @@ fn main() {{
)?;
// Just verify it doesn't panic
run(file.path(), FilterLevel::Minimal, None, None, false, 0)?;
run(file.path(), FilterLevel::Minimal, None, None, None, false, 0)?;
Ok(())
}
@@ -217,21 +298,180 @@ fn main() {{
#[test]
fn test_apply_line_window_tail_lines() {
let input = "a\nb\nc\nd\n";
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
assert_eq!(output, "c\nd\n");
}
#[test]
fn test_apply_line_window_tail_lines_no_trailing_newline() {
let input = "a\nb\nc\nd";
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
assert_eq!(output, "c\nd");
}
#[test]
fn test_head_window_matches_native_head() {
let input = "1\n2\n3\n4\n5\n";
assert_eq!(
apply_line_window(input, None, Some(3), None, &Language::Unknown),
"1\n2\n3\n"
);
}
/// The defect this window exists to fix: `--max-lines N` keeps only about
/// N/2 lines, so it could never stand in for `head -N`.
#[test]
fn test_head_window_keeps_all_n_lines_unlike_max_lines() {
let input = (1..=200)
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let head = apply_line_window(&input, None, Some(10), None, &Language::Unknown);
assert_eq!(head.lines().count(), 10);
assert_eq!(head.lines().last(), Some("10"));
}
#[test]
fn test_head_window_single_line() {
let input = "1\n2\n3\n";
assert_eq!(
apply_line_window(input, None, Some(1), None, &Language::Unknown),
"1\n"
);
}
#[test]
fn test_head_window_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\n", None, Some(0), None, &Language::Unknown),
""
);
}
#[test]
fn test_head_window_n_exceeds_line_count() {
let input = "a\nb\n";
assert_eq!(
apply_line_window(input, None, Some(99), None, &Language::Unknown),
input
);
}
#[test]
fn test_head_window_empty_input() {
assert_eq!(apply_line_window("", None, Some(5), None, &Language::Unknown), "");
}
#[test]
fn test_head_window_unterminated_final_line() {
assert_eq!(
apply_line_window("a\nb\nc", None, Some(3), None, &Language::Unknown),
"a\nb\nc"
);
}
#[test]
fn test_head_window_preserves_crlf() {
assert_eq!(
apply_line_window("a\r\nb\r\nc\r\n", None, Some(2), None, &Language::Unknown),
"a\r\nb\r\n"
);
}
#[test]
fn test_tail_window_preserves_crlf() {
assert_eq!(
apply_line_window("a\r\nb\r\nc\r\n", None, None, Some(2), &Language::Unknown),
"b\r\nc\r\n"
);
}
/// Without discounting the terminal newline, counting separators backwards
/// selects one line too few for newline-terminated input.
#[test]
fn test_tail_window_unterminated_single_line() {
assert_eq!(
apply_line_window("a\nb\nc", None, None, Some(1), &Language::Unknown),
"c"
);
}
#[test]
fn test_tail_window_n_exceeds_line_count() {
let input = "a\nb\n";
assert_eq!(
apply_line_window(input, None, None, Some(99), &Language::Unknown),
input
);
}
#[test]
fn test_tail_window_empty_input() {
assert_eq!(apply_line_window("", None, None, Some(5), &Language::Unknown), "");
}
#[test]
fn test_max_lines_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\nc\n", Some(0), None, None, &Language::Unknown),
""
);
}
#[test]
fn test_head_window_mixed_line_endings() {
assert_eq!(
apply_line_window("a\r\nb\nc\r\n", None, Some(2), None, &Language::Unknown),
"a\r\nb\n"
);
}
#[test]
fn test_tail_window_mixed_line_endings() {
assert_eq!(
apply_line_window("a\r\nb\nc\r\n", None, None, Some(2), &Language::Unknown),
"b\nc\r\n"
);
}
#[test]
fn test_windows_preserve_multibyte_utf8() {
let input = "héllo\n日本語\nثالث\n";
assert_eq!(
apply_line_window(input, None, Some(2), None, &Language::Unknown),
"héllo\n日本語\n"
);
assert_eq!(
apply_line_window(input, None, None, Some(2), &Language::Unknown),
"日本語\nثالث\n"
);
}
#[test]
fn test_windows_on_blank_lines_only() {
assert_eq!(
apply_line_window("\n\n\n", None, Some(2), None, &Language::Unknown),
"\n\n"
);
assert_eq!(
apply_line_window("\n\n\n", None, None, Some(2), &Language::Unknown),
"\n\n"
);
}
#[test]
fn test_tail_window_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\n", None, None, Some(0), &Language::Unknown),
""
);
}
#[test]
fn test_apply_line_window_max_lines_still_works() {
let input = "a\nb\nc\nd\n";
let output = apply_line_window(input, Some(2), None, &Language::Unknown);
let output = apply_line_window(input, Some(2), None, None, &Language::Unknown);
assert!(output.starts_with("a\n"));
assert!(output.contains("more lines"));
}
+938 -484
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -111,6 +111,28 @@ Key functions available to all command modules:
| `ruby_exec(tool)` | Auto-detect `bundle exec` when `Gemfile` exists |
| `count_tokens(text)` | Estimate tokens: `ceil(chars / 4.0)` |
## Argument Tokenizer (arg_tokenizer.rs)
Shared classifier for an already-`--`-restored args slice (see `args_utils::restore_double_dash`) into flags, their values, and positionals. `tokenize_grammar` takes a `takes_value(kind, name)` predicate the caller supplies — the list of which flags take a value is per-tool, but the token-walking around it isn't. `tokenize(args)` is the structural-only entry point, for a caller asking which arguments are flags and where `--` is; it assumes **no flag takes a value**, so anything reading a value or counting free positionals needs `tokenize_grammar`.
**Use it for anything that decides what an argument is.** A new command filter, a new flag on an existing one, or a fix to how one is detected goes through `tokenize_grammar` — not `starts_with('-')`, not `args.iter().any(|a| a == "--flag")`. Those miss exactly what this module exists for: a flag's own value (`git log --grep -p` searches for the string "-p"), an attached value (`--flag=v`, `/bl:x`), a short cluster (`-rn`), and everything past `--`. Every bug the migration fixed was one of those four.
Four rules, each of which cost a real bug before it was written down:
- **One grammar per tool and subcommand.** Never reuse a sibling's predicate wholesale because it looks close enough — `-u` means `-p` in `git log` but `--include-untracked` in `git stash show`, and `-T` is `--initial-tab` in grep but `--type-not` in rg. Transcribe from the tool's own `--help` and verify against the real binary; grep and rg share 13 of ~50 value-taking flags, so one merged table is wrong for both.
- **Scope the lookup to the region the tool parses.** Everything past `--` is a pathspec or an argument forwarded to another program — `before_dashdash` gives the tool's own tokens. `Dialect::Msbuild` keeps classifying past the boundary (it forwards rather than ending option parsing), which makes this explicit slice mandatory there, not optional.
- **Inject before the boundary.** RTK's own flags go at `injection_point`, never appended: dotnet parks anything after `--` in UnparsedTokens and git reads it as a pathspec, so an appended `--verify-no-changes` silently does nothing.
- **Detect and act with one rule.** Strip or inject using the detected token's `source_index`; re-matching the text lets the two disagree, which deleted a pathspec named `--no-compact` and swallowed a forwarded `--write`.
`takes_value` returns `Option<ValueSpec>`, not a `bool`: one table per tool, answering every question the tokenizer has about a flag's value rather than one predicate per question, which is how two lists start drifting apart.
- `ValueSpec::value()` — `--flag=v` or `--flag v`, and a literal `--` is the boundary. The common case.
- `ValueSpec::attached_only()` — `--flag=v` only, the next argument is never the value (git's `-M`/`-U`/`-C`/`-B` take an optional attached number and nothing else).
- `ValueSpec::solo_only()` — a `Short` flag takes a separate value only when it is the whole argument: `git log -n 2` does, `git log -pn 2` does not. No meaning for a `Long` flag.
- `.claiming_dash_dash()` — lets a literal `--` be this flag's value. A per-tool split, not per-flag: grep and rg let any value-taking flag swallow it, git and cargo reject it whichever flag is asking.
The dialect is the one axis that is not per-flag, so it stays a parameter: `tokenize_grammar(args, takes_value, Dialect::Msbuild)`.
## Consumer Contracts
Core provides infrastructure that `cmds/` and other components consume. These contracts define expected usage.
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -318,6 +318,12 @@ pub fn get_filter(level: FilterLevel) -> Box<dyn FilterStrategy> {
}
pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> String {
// A zero budget shows nothing, matching `--tail-lines 0`/`--head-lines 0`.
// Returning early also keeps `max_lines - 1` below from underflowing.
if max_lines == 0 {
return String::new();
}
let lines: Vec<&str> = content.lines().collect();
if lines.len() <= max_lines {
return content.to_string();
@@ -346,7 +352,7 @@ pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> Stri
// Non-important lines beyond max_lines/2 are silently skipped —
// no inline markers that could be mistaken for file content.
if kept_lines >= max_lines - 1 {
if kept_lines + 1 >= max_lines {
break;
}
}
+1
View File
@@ -1,5 +1,6 @@
//! Building blocks shared across all RTK modules.
pub mod arg_tokenizer;
pub mod args_utils;
pub mod config;
pub mod constants;
+18 -6
View File
@@ -2,6 +2,7 @@
use anyhow::{Context, Result};
use regex::Regex;
use std::borrow::Cow;
use std::process::Command;
use std::sync::LazyLock;
@@ -138,6 +139,8 @@ where
raw
};
// stderr is forwarded unchanged below, so it costs the same whether or not rtk is
// in the way. What the guard must not inflate is the stdout it replaces.
let shown = if let Some(label) = opts.tee_label {
print_with_hint(&filtered, raw, raw_for_tracking, label, exit_code)
} else {
@@ -150,12 +153,21 @@ where
guarded
};
timer.track(
cmd_label,
&format!("rtk {}", cmd_label),
raw_for_tracking,
&shown,
);
// Stdout-only filters parse structured stdout; stderr still carries diagnostics
// (config errors, missing linters) that the user needs.
let forwarded_stderr = opts.filter_stdout_only && !result.raw_stderr.trim().is_empty();
if forwarded_stderr {
eprint!("{}", result.raw_stderr);
}
// Forwarded stderr reaches the user just as much as stdout does, so counting only
// stdout would book a passed-through stream as if the filter had removed it.
let emitted = if forwarded_stderr {
Cow::Owned(format!("{}{}", shown, result.raw_stderr))
} else {
Cow::Borrowed(shown.as_str())
};
timer.track(cmd_label, &format!("rtk {}", cmd_label), raw, &emitted);
Ok(exit_code)
}
+294 -10
View File
@@ -202,7 +202,7 @@ pub struct GainSummary {
pub total_time_ms: u64,
/// Average execution time per command (milliseconds)
pub avg_time_ms: u64,
/// Top 10 commands by tokens saved: (cmd, count, saved, avg_pct, avg_time_ms)
/// Top 10 commands by tokens saved: (cmd, count, saved, weighted_rate, avg_time_ms)
pub by_command: Vec<(String, usize, usize, f64, u64)>,
/// Last 30 days of activity: (date, saved_tokens)
pub by_day: Vec<(String, usize)>,
@@ -295,7 +295,16 @@ pub struct MonthStats {
pub avg_time_ms: u64,
}
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
/// Type alias for command statistics tuple: (command, count, saved_tokens, weighted_savings_rate, avg_time_ms)
///
/// # Warning
/// The 4th field is a **weighted** savings rate: `SUM(saved_tokens) / SUM(input_tokens) * 100.0`,
/// guarded so that a group whose every row has zero input reports 0.0 rather than NULL.
/// Do NOT aggregate this column with `AVG()` — that would produce an unweighted mean that
/// under-weights high-volume commands. Always recompute it as
/// `CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) / SUM(input_tokens) * 100.0 ELSE 0.0 END`
/// instead. `saved_tokens` is signed, so the rate can be negative where the 3rd field, being
/// unsigned, is clamped to 0.
type CommandStats = (String, usize, usize, f64, u64);
/// Current tracking-DB schema version, stored in the SQLite `user_version` pragma.
@@ -893,7 +902,9 @@ impl Tracker {
) -> Result<Vec<CommandStats>> {
let (project_exact, project_glob) = project_filter_params(project_path); // added
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens),
CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) * 100.0 / SUM(input_tokens) ELSE 0.0 END,
AVG(exec_time_ms)
FROM commands
WHERE (?1 IS NULL OR project_path = ?1 OR project_path GLOB ?2)
GROUP BY rtk_cmd
@@ -1312,12 +1323,21 @@ impl Tracker {
}
/// Count commands with low savings (<30%) — filters that need improvement.
///
/// Uses the same weighted rate as `get_by_command`, `SUM(saved_tokens) / SUM(input_tokens)`
/// over every call of the command, so that a handful of 0%-savings passthrough calls don't
/// dilute a filter that genuinely performs well on high-volume invocations, and so that the
/// figure sent here is the one `rtk gain` prints for the same command. A net-regressing
/// command (negative rate) is listed: it is the filter most in need of improvement. Exact
/// 0% is left out, `passthrough_top` already reports it, and a command whose calls never
/// had any input carries no signal, so it is skipped rather than reported as 0%.
pub fn low_savings_commands(&self, limit: usize) -> Result<Vec<(String, f64)>> {
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, AVG(savings_pct) as avg_sav FROM commands
WHERE input_tokens > 0
"SELECT rtk_cmd,
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS sav
FROM commands
GROUP BY rtk_cmd
HAVING avg_sav < 30.0 AND avg_sav > 0.0
HAVING SUM(input_tokens) > 0 AND sav < 30.0 AND sav <> 0.0
ORDER BY COUNT(*) DESC LIMIT ?1",
)?;
let rows = stmt.query_map(params![limit as i64], |row| {
@@ -1329,7 +1349,15 @@ impl Tracker {
Ok(rows.filter_map(|r| r.ok()).collect())
}
/// Average savings percentage per command (unweighted — each command name counts once).
/// Average savings percentage per command (unweighted across command names — each distinct
/// command counts once, regardless of how many times it was invoked).
///
/// The *inner* rate per command is weighted by volume (`SUM(saved)/SUM(input)`) so that
/// passthrough calls don't dilute a command's own rate. The *outer* average across command
/// names stays unweighted — this is intentional: it gives equal weight to every filter
/// instead of being dominated by the most-called one. Documented in `docs/TELEMETRY.md`.
/// A command whose calls never had any input carries no signal about its filter and is
/// skipped, not counted as 0%.
///
/// Keeps the honest signed value: a command whose filter consistently emits
/// more than it saves yields a negative average, mirroring `overall_savings_pct`
@@ -1338,10 +1366,12 @@ impl Tracker {
/// not on a `0..=100` floor.
pub fn avg_savings_per_command(&self) -> Result<f64> {
let avg: f64 = self.conn.query_row(
"SELECT COALESCE(AVG(avg_sav), 0.0) FROM (
SELECT rtk_cmd, AVG(savings_pct) as avg_sav
FROM commands WHERE input_tokens > 0
"SELECT COALESCE(AVG(cmd_rate), 0.0) FROM (
SELECT rtk_cmd,
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS cmd_rate
FROM commands
GROUP BY rtk_cmd
HAVING SUM(input_tokens) > 0
)",
[],
|row| row.get(0),
@@ -2535,4 +2565,258 @@ mod tests {
assert_eq!(categorize_command(cmd), "js", "{cmd}");
}
}
// 14. get_by_command uses weighted savings rate, not unweighted average
//
// Regression test for: AVG(savings_pct) gave wrong results when small invocations
// with 0% savings diluted the average of high-volume commands.
//
// Setup: one small command (10% savings) + one large command (95% savings).
// Unweighted avg would be ~52.5%. Weighted rate must be ~95%.
//
// Rows carry a project path so the project-filtered form of the query is the one
// under test.
#[test]
fn test_get_by_command_weighted_savings_rate() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
let cmd_name = "weighted_test";
let project = "/tmp/rtk_weighted_test";
// Override project_path by inserting directly via conn
let saved_small = 10_i64; // 100 in - 90 out = 10 saved → 10%
let saved_large = 95_000_i64; // 100_000 in - 5_000 out = 95_000 saved → 95%
tracker
.conn
.execute(
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
chrono::Utc::now().to_rfc3339(),
cmd_name, cmd_name, project,
100_i64, 90_i64, saved_small, 10.0_f64, 5_i64
],
)
.expect("Failed to insert small invocation");
tracker
.conn
.execute(
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
chrono::Utc::now().to_rfc3339(),
cmd_name, cmd_name, project,
100_000_i64, 5_000_i64, saved_large, 95.0_f64, 10_i64
],
)
.expect("Failed to insert large invocation");
let by_cmd = tracker
.get_by_command(Some(project))
.expect("Failed to get by_command stats");
let entry = by_cmd
.iter()
.find(|(name, _, _, _, _)| name == cmd_name)
.expect("Test command not found in by_command stats");
let (_name, _count, _saved, rate, _time) = entry;
// Weighted rate = (10 + 95_000) / (100 + 100_000) * 100.0 ≈ 94.9%
// Unweighted avg would be (10.0 + 95.0) / 2 = 52.5%
// The gap proves the fix works.
assert!(
*rate > 90.0,
"Expected weighted rate >90%, got {:.1}% — unweighted avg would be ~52.5%",
rate
);
}
// 15. The weighted rate tracks SUM(saved_tokens), not the mean of per-call percentages
//
// A long-tailed pair under one rtk_cmd: a 1M-token call saving 90% and a 100-token
// call saving 10%. The mean of the two percentages is 50%; the weighted rate is
// ~89.99% and is the figure consistent with the Saved column in the same row.
#[test]
fn test_weighted_rate_via_get_by_command() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("grep huge", "rtk grep", 1_000_000, 100_000, 50)
.expect("record huge");
tracker
.record("grep tiny", "rtk grep", 100, 90, 5)
.expect("record tiny");
let by_command = tracker.get_by_command(None).expect("get_by_command");
let (_cmd, count, saved, pct, _avg_time) = by_command
.iter()
.find(|(cmd, ..)| cmd == "rtk grep")
.expect("rtk grep row not found");
assert_eq!(*count, 2);
assert_eq!(*saved, 900_010);
let expected = 900_010.0 / 1_000_100.0 * 100.0;
assert!(
(pct - expected).abs() < 0.01,
"expected weighted rate ~{expected:.2}, got {pct:.2}"
);
assert!(
(pct - 50.0).abs() > 1.0,
"mean-of-percentages regression: got {pct:.2}"
);
}
// 16. The rate reaches the gain summary through get_summary(), not only get_by_command
#[test]
fn test_weighted_rate_via_get_summary() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("large grep", "rtk grep", 1000, 100, 10)
.expect("Failed to record large command");
tracker
.record("small grep", "rtk grep", 10, 9, 20)
.expect("Failed to record small command");
let summary = tracker.get_summary().expect("Failed to get summary");
let (_, count, saved, savings_pct, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == "rtk grep")
.expect("rtk grep stats not found");
assert_eq!(*count, 2);
assert_eq!(*saved, 901);
let expected_pct = 901.0 / 1010.0 * 100.0;
assert!(
(savings_pct - expected_pct).abs() < 1e-10,
"expected weighted rate {expected_pct}, got {savings_pct}"
);
}
// 17. A group whose every call has zero input reports 0%, not a division by zero
#[test]
fn test_by_command_zero_input_has_zero_savings_percentage() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("interactive command", "rtk proxy", 0, 0, 5)
.expect("Failed to record passthrough command");
let summary = tracker.get_summary().expect("Failed to get summary");
let (_, _, _, savings_pct, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == "rtk proxy")
.expect("rtk proxy stats not found");
assert_eq!(*savings_pct, 0.0);
}
// 18. low_savings_commands reports the same weighted rate as the `rtk gain` By Command
// table, including net-regressing commands, and nothing for commands without input.
//
// `rtk ls -R`: one 95% call plus four 0% passthrough calls. Unweighted AVG(savings_pct)
// over those five rows is 19%, under the 30% threshold, so the command would reach
// telemetry as low-savings while `get_by_command` shows it at ~94.6% in the same
// `rtk gain` run. Weighted, 95_000 / 100_400 ≈ 94.6%: not listed.
// `rtk grep`: 25% on one call, then a call with no input that still printed 10 tokens.
// Every row counts, as in `get_by_command`: (250 - 10) / 1_000 = 24%, listed at 24.
// `rtk read`: emits more than it saves, -50%. Listed: it is the filter to fix first.
// `rtk proxy`: never had any input. Nothing to say about its filter, not listed.
#[test]
fn test_low_savings_commands_matches_gain_weighted_rate() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
.expect("record big call");
for _ in 0..4 {
tracker
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
.expect("record passthrough call");
}
tracker
.record("grep x", "rtk grep", 1_000, 750, 5)
.expect("record 25% call");
tracker
.record("grep none", "rtk grep", 0, 10, 5)
.expect("record no-input call");
tracker
.record("read big.json", "rtk read", 100, 150, 5)
.expect("record regressing call");
tracker
.record("interactive", "rtk proxy", 0, 0, 5)
.expect("record zero-input call");
let low = tracker
.low_savings_commands(10)
.expect("low_savings_commands");
let listed: Vec<(&str, f64)> = low.iter().map(|(n, r)| (n.as_str(), *r)).collect();
assert_eq!(
listed.len(),
2,
"expected `rtk grep` (24%) and `rtk read` (-50%); ~94.6% weighted must not be \
listed (unweighted AVG(savings_pct) would put it at 19%), got {listed:?}"
);
assert_eq!(listed[0].0, "rtk grep");
assert!((listed[0].1 - 24.0).abs() < 1e-9, "got {listed:?}");
assert_eq!(listed[1].0, "rtk read");
assert!((listed[1].1 - (-50.0)).abs() < 1e-9, "got {listed:?}");
// The figure sent to telemetry is the one `rtk gain` prints for the same command.
let summary = tracker.get_summary().expect("get_summary");
for (name, rate) in &low {
let (_, _, _, gain_rate, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == name)
.unwrap_or_else(|| panic!("{name} missing from by_command"));
assert!(
(gain_rate - rate).abs() < 1e-9,
"{name}: telemetry says {rate}, rtk gain says {gain_rate}"
);
}
}
// 19. avg_savings_per_command weights each command's own rate by volume (every call
// counted, as in test 18), then averages the per-command rates without weighting: each
// command name counts once, and a command that never had any input is not counted.
//
// Same rows as test 18: `rtk ls -R` ≈ 94.6% (19% if the inner aggregate were
// AVG(savings_pct)), `rtk grep` 24%, `rtk read` -50%, `rtk proxy` skipped.
#[test]
fn test_avg_savings_per_command_inner_rate_is_weighted() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
.expect("record big call");
for _ in 0..4 {
tracker
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
.expect("record passthrough call");
}
tracker
.record("grep x", "rtk grep", 1_000, 750, 5)
.expect("record 25% call");
tracker
.record("grep none", "rtk grep", 0, 10, 5)
.expect("record no-input call");
tracker
.record("read big.json", "rtk read", 100, 150, 5)
.expect("record regressing call");
tracker
.record("interactive", "rtk proxy", 0, 0, 5)
.expect("record zero-input call");
let avg = tracker
.avg_savings_per_command()
.expect("avg_savings_per_command");
let ls_rate = 95_000.0 * 100.0 / 100_400.0;
let expected = (ls_rate + 24.0 - 50.0) / 3.0;
assert!(
(avg - expected).abs() < 1e-6,
"expected ({ls_rate:.1} + 24 - 50) / 3 = {expected:.1}%, got {avg:.1}% \
(an unweighted inner AVG(savings_pct) would give (19 + 12.5 - 50) / 3 = -6.2%)"
);
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
**Per-segment rewriting** — Each segment goes through:
1. Strip trailing redirects (`2>&1`, `>/dev/null`) — matched via lexer tokens, set aside, re-appended after rewriting
2. Short-circuit special cases — `head -20 file` → `rtk read file --max-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
2. Short-circuit special cases — `head -20 file` → `rtk read file --head-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
3. Classify the command — strip env prefixes (`FOO="bar baz"`), normalize paths (`/usr/bin/grep` → `grep`), strip git global opts (`git -C /tmp` → `git`), then match against 60+ regex patterns from `rules.rs`
4. Apply the rewrite — find the matching rule, replace the command prefix with `rtk <cmd>`, re-prepend the env prefix, re-append the redirect suffix
+264 -15
View File
@@ -80,10 +80,67 @@ static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
// Issue #1362: each capture expects a SINGLE file argument (`\S+$`). Multi-file
// invocations like `head -3 a b c` fail to match so the segment is passed through
// to the native `head`/`tail` binary — which already handles multi-file with
// `==> name <==` banners that `rtk read --max-lines` cannot reproduce.
// `==> name <==` banners that a single `rtk read` window cannot reproduce.
static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
static HEAD_LINES: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
// `-n N` and `--lines N` are the spellings `tail` already accepted below; `head`
// silently fell through to no rewrite at all without them.
static HEAD_N_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+-n\s+(\d+)\s+(\S+)$").unwrap());
static HEAD_LINES_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
// Bare `head FILE` means ten lines, not the whole file. Restricted to a single
// operand: multi-file and optioned forms stay with the native binary.
static HEAD_BARE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+(\S+)$").unwrap());
/// Re-attach a trailing redirect to a rewritten head/tail command.
///
/// `head -n 1 f>out` strips to a suffix with no leading space, and these
/// rewrites end in a bare number, so plain concatenation yields
/// `--head-lines 1>out` — which the shell reads as an fd-1 redirect, leaving
/// `--head-lines` with no value. A separating space keeps the flag intact.
///
/// Deliberately not applied to the shared prefix rewrites: those keep the
/// original argument/redirect boundary, where inserting a space could split a
/// descriptor-duplication form such as `1>&2` and demote the descriptor number
/// into an argument.
fn join_redirect_suffix(rewritten: &str, redirect_suffix: &str) -> String {
if redirect_suffix.is_empty() || redirect_suffix.starts_with(char::is_whitespace) {
format!("{}{}", rewritten, redirect_suffix)
} else {
format!("{} {}", rewritten, redirect_suffix)
}
}
/// Whether an operand is safe to hand to `rtk read` as one concrete file.
///
/// One whitespace-delimited token is not one shell operand: `*.rs`, `{a,b}` and
/// `$FILES` each expand to several at execution time, and `rtk read`
/// concatenates files where `head`/`tail` print `==> name <==` banners.
///
/// The token is raw shell source, not the argument the callee receives, so
/// character-class blocklists kept missing cases: `'--'` and `\--help` hide an
/// option behind a quote or backslash, and a leading `#` opens a comment that
/// swallows the flags this rewrite appends. Hence an allowlist: only characters
/// that cannot change the operand's word count or turn it into an option are
/// accepted, and anything else is left to the native binary. `~` is the one
/// shell-active character kept, because tilde expansion yields exactly one word
/// and the operand is passed through unchanged. Unicode alphanumerics stay
/// eligible so non-ASCII filenames still route.
///
/// The cost is deliberate: a quoted literal like `'literal*.txt'` also stays
/// native even though the quoting would prevent expansion. Losing a rewrite is
/// recoverable; changing what the user's command does is not.
fn is_single_file_operand(operand: &str) -> bool {
if operand.is_empty() || operand.starts_with('-') {
return false;
}
operand.chars().all(|c| {
c.is_alphanumeric()
|| matches!(c, '.' | '_' | '/' | '-' | '~' | '+' | '@' | ':' | ',' | '=')
})
}
static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
static TAIL_N_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
@@ -1242,14 +1299,23 @@ fn rewrite_compound(
}
fn rewrite_line_range(cmd: &str) -> Option<String> {
for re in [&*HEAD_N, &*HEAD_LINES] {
for re in [&*HEAD_N, &*HEAD_LINES, &*HEAD_N_SPACE, &*HEAD_LINES_SPACE] {
if let Some(caps) = re.captures(cmd) {
let n = caps.get(1)?.as_str();
let file = caps.get(2)?.as_str();
return Some(format!("rtk read {} --max-lines {}", file, n));
if is_single_file_operand(file) {
return Some(format!("rtk read {} --head-lines {}", file, n));
}
return None;
}
}
if cmd.starts_with("head -") {
if let Some(caps) = HEAD_BARE.captures(cmd) {
let file = caps.get(1)?.as_str();
if is_single_file_operand(file) {
return Some(format!("rtk read {} --head-lines 10", file));
}
}
if cmd.starts_with("head") {
return None;
}
for re in [
@@ -1261,7 +1327,10 @@ fn rewrite_line_range(cmd: &str) -> Option<String> {
if let Some(caps) = re.captures(cmd) {
let n = caps.get(1)?.as_str();
let file = caps.get(2)?.as_str();
return Some(format!("rtk read {} --tail-lines {}", file, n));
if is_single_file_operand(file) {
return Some(format!("rtk read {} --tail-lines {}", file, n));
}
return None;
}
}
None
@@ -1578,7 +1647,7 @@ fn rewrite_segment_inner(
}
if context == RewriteContext::Normal
&& (cmd_part.starts_with("head -") || cmd_part.starts_with("tail "))
&& (cmd_part.starts_with("head ") || cmd_part.starts_with("tail "))
{
// head/tail rewrite to `rtk read`, so honour exclude_commands here too:
// this branch returns before the checks below. Any env prefix has already
@@ -1586,7 +1655,7 @@ fn rewrite_segment_inner(
if is_excluded(cmd_part, excluded) {
return None;
}
return rewrite_line_range(cmd_part).map(|r| format!("{}{}", r, redirect_suffix));
return rewrite_line_range(cmd_part).map(|r| join_redirect_suffix(&r, redirect_suffix));
}
// Most cat flags (-v, -A, -e, -t, -s, -b, --show-all, etc.) have different
@@ -2417,6 +2486,7 @@ mod tests {
assert_eq!(
safe_rules,
vec![
"rtk ast-grep",
"rtk brew",
"rtk bundle",
"rtk cargo",
@@ -3831,7 +3901,7 @@ mod tests {
// A non-excluded inner command still rewrites through the wrapper.
assert_eq!(
rewrite_command_no_prefixes("uv run head -20 src/main.rs", &["cat".to_string()]),
Some("uv run rtk read src/main.rs --max-lines 20".into())
Some("uv run rtk read src/main.rs --head-lines 20".into())
);
}
@@ -3839,33 +3909,211 @@ mod tests {
fn test_head_tail_rewrite_when_not_excluded() {
assert_eq!(
rewrite_command_no_prefixes("head -20 src/main.rs", &["cat".to_string()]),
Some("rtk read src/main.rs --max-lines 20".into())
Some("rtk read src/main.rs --head-lines 20".into())
);
}
#[test]
fn test_rewrite_head_numeric_flag() {
// head -20 file → rtk read file --max-lines 20 (not rtk read -20 file)
// head -20 file → rtk read file --head-lines 20 (not rtk read -20 file)
assert_eq!(
rewrite_command_no_prefixes("head -20 src/main.rs", &[]),
Some("rtk read src/main.rs --max-lines 20".into())
Some("rtk read src/main.rs --head-lines 20".into())
);
}
/// A single token that the shell expands into several operands must stay
/// native: `rtk read` concatenates files, losing `head`'s `==> name <==`
/// banners. Covers the newly added `-n N` / `--lines N` routes, which had
/// no matcher at all before and so were native by accident.
#[test]
fn test_rewrite_head_expanding_operand_stays_native() {
for cmd in [
"head src/core/*.rs",
"head -1 src/core/*.rs",
"head -n 1 src/core/*.rs",
"head --lines 1 src/core/*.rs",
"head --lines=1 src/core/*.rs",
"head -n 1 src/core/{a,b}.rs",
"head -n 1 $FILES",
"head -n 1 src/core/?.rs",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"expanding operand must stay native: {}",
cmd
);
}
}
/// `head -n 1 --help` must reach `head`, not print `rtk read`'s help. The
/// quoted and escaped spellings matter as much as the bare one: the matcher
/// sees shell source, so `'--'` and `\--help` slip past a leading-`-` test
/// while still reaching the tool as options.
#[test]
fn test_rewrite_head_option_operand_stays_native() {
for cmd in [
"head -n 1 --help",
"head --lines 1 --version",
"head --help",
"head -n 1 '--'",
"head -n 1 \"--\"",
"head -n 1 '--help'",
"head -n 1 \"--help\"",
"head -n 1 \\--help",
"head '--'",
"head -n 1 #comment",
"head #comment",
"head -n 1 a|b",
"head -n 1 (x)",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"option-like operand must stay native: {}",
cmd
);
}
}
/// The same expansion hazard applied to `tail`, which shared the code path.
#[test]
fn test_rewrite_tail_expanding_operand_stays_native() {
for cmd in [
"tail -20 src/core/*.rs",
"tail -n 20 src/core/*.rs",
"tail --lines 20 $FILES",
"tail -n 1 '--'",
"tail -n 1 \\--help",
"tail -n 1 #comment",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"expanding operand must stay native: {}",
cmd
);
}
}
/// `;` and `&` are operators the lexer splits on before the operand is ever
/// examined, so the trailing text is a separate command and the real operand
/// is just `f`. These rewrite, and should: the allowlist only has to judge
/// characters that survive segmentation.
#[test]
fn test_rewrite_head_operand_after_operator_split() {
assert_eq!(
rewrite_command_no_prefixes("head -n 1 f;rm", &[]),
Some("rtk read f --head-lines 1; rm".into())
);
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a&b", &[]),
Some("rtk read a --head-lines 1 & b".into())
);
}
/// A trailing redirect is stripped before the operand is judged, so `a>b`
/// rewrites with operand `a` — but the suffix must not fuse onto the numeric
/// flag value, or the shell reads `1>b` as an fd-1 redirect and
/// `--head-lines` loses its argument.
#[test]
fn test_rewrite_head_redirect_suffix_keeps_flag_value() {
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a>b", &[]),
Some("rtk read a --head-lines 1 >b".into())
);
assert_eq!(
rewrite_command_no_prefixes("tail -n 1 a>b", &[]),
Some("rtk read a --tail-lines 1 >b".into())
);
// An already-spaced suffix must not gain a second space.
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a > b", &[]),
Some("rtk read a --head-lines 1 > b".into())
);
}
/// Shapes the allowlist must keep accepting, including a non-ASCII name.
#[test]
fn test_rewrite_head_accepts_ordinary_paths() {
for (cmd, want) in [
(
"head -10 /tmp/seq.txt",
"rtk read /tmp/seq.txt --head-lines 10",
),
("head ./a-b_c.txt", "rtk read ./a-b_c.txt --head-lines 10"),
("head ~/x.txt", "rtk read ~/x.txt --head-lines 10"),
(
"head /tmp/a.b.c-d_e.txt",
"rtk read /tmp/a.b.c-d_e.txt --head-lines 10",
),
(
"head src/日本語.rs",
"rtk read src/日本語.rs --head-lines 10",
),
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
Some(want.into()),
"must still rewrite: {}",
cmd
);
}
}
#[test]
fn test_rewrite_tail_plain_operand_still_rewrites() {
assert_eq!(
rewrite_command_no_prefixes("tail -20 src/main.rs", &[]),
Some("rtk read src/main.rs --tail-lines 20".into())
);
}
#[test]
fn test_rewrite_head_n_space_flag() {
assert_eq!(
rewrite_command_no_prefixes("head -n 50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
#[test]
fn test_rewrite_head_lines_space_flag() {
assert_eq!(
rewrite_command_no_prefixes("head --lines 50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
/// Multi-file and optioned bare forms stay native: the rewrite emits one
/// path (see `is_single_file_operand`), and `head` prints `==> name <==`
/// banners for several files, which a concatenated read cannot reproduce.
#[test]
fn test_rewrite_head_bare_multifile_stays_native() {
assert_eq!(rewrite_command_no_prefixes("head a.txt b.txt", &[]), None);
}
#[test]
fn test_rewrite_head_unsupported_option_stays_native() {
assert_eq!(rewrite_command_no_prefixes("head -c 10 f.bin", &[]), None);
}
#[test]
fn test_rewrite_head_lines_long_flag() {
assert_eq!(
rewrite_command_no_prefixes("head --lines=50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --max-lines 50".into())
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
#[test]
fn test_rewrite_head_no_flag_still_rewrites() {
// plain `head file` → `rtk read file` (no numeric flag)
// plain `head file` means ten lines, so the rewrite must bound the read
// rather than dumping the whole file.
assert_eq!(
rewrite_command_no_prefixes("head src/main.rs", &[]),
Some("rtk read src/main.rs".into())
Some("rtk read src/main.rs --head-lines 10".into())
);
}
@@ -3925,7 +4173,8 @@ mod tests {
// --- Issue #1362: head/tail with multiple files falls back to native command ---
//
// `rtk read <file> --max-lines N` only accepts a single positional file path in
// The head/tail rewrite emits a single positional path (see
// `is_single_file_operand`), even though `rtk read` itself accepts several, in
// a shape that maps cleanly to `head -N`. Rewriting `head -N a b c` to
// `rtk read a b c --max-lines N` previously produced a command where `rtk read`
// would concatenate the files without the `==> name <==` banners that native
+12
View File
@@ -147,6 +147,18 @@ pub const RULES: &[RtkRule] = &[
savings_pct: 75.0,
..RtkRule::DEFAULT
},
RtkRule {
pattern: r"^ast-grep\s+",
rtk_cmd: "rtk ast-grep",
// Unlike grep/rg, `rtk ast-grep`'s run() execs with stdin null (no
// piped-stdin support yet), so it must not be rewritten as a
// pipeline's final stage — that would silently drop the pipe input.
pipeline_safety: PipelineSafety::ProducerOnly,
rewrite_prefixes: &["ast-grep"],
category: "Files",
savings_pct: 85.0,
..RtkRule::DEFAULT
},
RtkRule {
pattern: r"^ls(\s|$)",
rtk_cmd: "rtk ls",
+3 -3
View File
@@ -29,7 +29,7 @@ LLM agent integration layer that installs, validates, and executes command-rewri
| Claude-MD (legacy) | `rtk init --claude-md` | 134-line RTK block | CLAUDE.md |
| Windsurf | `rtk init -g --agent windsurf` | `.windsurfrules` | -- |
| Cline | `rtk init --agent cline` | `.clinerules` | -- |
| Codex | `rtk init --codex` | RTK.md in `$CODEX_HOME` or `~/.codex` | AGENTS.md |
| Codex | `rtk init --codex` | RTK.md + `.codex/hooks.json` (local) or `$CODEX_HOME/hooks.json` (global) | AGENTS.md + `PreToolUse` hook |
| Cursor | `rtk init -g --agent cursor` | Cursor hook | hooks.json |
| Pi | `rtk init --agent pi` | `.pi/extensions/rtk.ts` | -- |
| Oh My Pi (OMP) | `rtk init --agent omp` | `.omp/extensions/rtk.ts` (shared Pi extension) | -- |
@@ -91,14 +91,14 @@ Rules are loaded from all Claude Code `settings.json` files (project + global, i
| Cursor (rtk hook cursor) | Ready | `permission: "ask",` — users will be prompted when Cursor enforces the permission; in the meantime, allow |
| Gemini CLI (rtk hook gemini) | No (allow/deny only) | allow (limitation — no ask mode in Gemini) |
| Copilot CLI (rtk hook copilot) | No updatedInput | deny-with-suggestion (unchanged) |
| Codex | ask parsed but no-op | allow (limitation — fails open) |
| Codex (`rtk hook codex`) | Native approval runs after rewrite | Emit required protocol `allow` with `updatedInput`; Codex then evaluates the rewritten command normally |
| Mistral Vibe (rtk hook vibe) | No native ask surface | passthrough — Vibe's own approval prompt fires on the rewritten command |
### Implementation
- `permissions.rs` — loads deny/ask/allow rules, evaluates precedence, returns `PermissionVerdict`
- `rewrite_cmd.rs` — maps verdict to exit code (consumed by shell hook)
- `hook_cmd.rs` — maps verdict to JSON `permissionDecision` field (Copilot/Gemini)
- `hook_cmd.rs` — maps decisions to each agent's JSON protocol, including Codex `updatedInput`
## Exit Code Contract
+2
View File
@@ -10,6 +10,8 @@ pub const BEFORE_TOOL_KEY: &str = "BeforeTool";
/// Native Rust hook command for Claude Code (replaces rtk-rewrite.sh).
pub const CLAUDE_HOOK_COMMAND: &str = "rtk hook claude";
/// Native Rust hook command for Codex CLI.
pub const CODEX_HOOK_COMMAND: &str = "rtk hook codex";
/// Native Rust hook command for Cursor (replaces rtk-rewrite.sh).
pub const CURSOR_HOOK_COMMAND: &str = "rtk hook cursor";
/// Native Rust hook command for Factory Droid.
+16 -3
View File
@@ -193,10 +193,9 @@ impl AgentPath {
match agent {
// `copilot` reads Claude Code's settings rather than a Copilot file
// (see `hook_cmd`'s `vscode_response` and `copilot_cli_response`).
"antigravity" | "cline" | "codex" | "kilocode" | "kimi" | "windsurf" => {
Some(Self::RulesOnly)
}
"antigravity" | "cline" | "kilocode" | "kimi" | "windsurf" => Some(Self::RulesOnly),
"claude" | "copilot" => Some(Self::InProcess(Host::Claude)),
"codex" => Some(Self::InProcess(Host::Codex)),
"cursor" => Some(Self::InProcess(Host::Cursor)),
"droid" => Some(Self::InProcess(Host::Droid)),
"gemini" => Some(Self::InProcess(Host::Gemini)),
@@ -408,6 +407,20 @@ mod tests {
assert!(AgentPath::lookup("Claude").is_none());
}
#[test]
fn codex_uses_shared_decision_without_claiming_permission() {
assert!(matches!(
AgentPath::lookup("codex"),
Some(AgentPath::InProcess(Host::Codex))
));
assert_eq!(
check_command_for("git status", Host::Codex),
PermissionVerdict::Default
);
let (deny, ask, allow) = super::super::permissions::load_rules_for(Host::Codex);
assert!(deny.is_empty() && ask.is_empty() && allow.is_empty());
}
/// A rules-file agent has no hook and no permission rules, so its answer
/// must not depend on any host's settings.
#[test]
+409 -47
View File
@@ -564,11 +564,34 @@ enum PayloadAction {
},
Skip {
decision: HookOutcome,
reason: &'static str,
cmd: String,
},
Ignore,
}
fn pre_tool_use_rewrite_output(
v: &Value,
rewritten: &str,
permission_decision: Option<&str>,
) -> Value {
let mut updated_input = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
if let Some(obj) = updated_input.as_object_mut() {
obj.insert("command".into(), Value::String(rewritten.to_string()));
}
let mut hook_output = json!({
"hookEventName": PRE_TOOL_USE_KEY,
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": updated_input
});
if let Some(decision) = permission_decision {
hook_output["permissionDecision"] = Value::String(decision.to_string());
}
json!({ "hookSpecificOutput": hook_output })
}
fn process_claude_payload(v: &Value) -> PayloadAction {
let cmd = match v
.pointer("/tool_input/command")
@@ -595,12 +618,14 @@ fn process_claude_payload_from_decision(
HookDecision::Deny => {
return PayloadAction::Skip {
decision: HookOutcome::Deny,
reason: "skip:deny_rule",
cmd: cmd.to_string(),
}
}
HookDecision::Defer => {
return PayloadAction::Skip {
decision: HookOutcome::Defer,
reason: "skip:defer",
cmd: cmd.to_string(),
}
}
@@ -608,36 +633,15 @@ fn process_claude_payload_from_decision(
HookDecision::AskRewrite(r) => (r, false),
};
let updated_input = {
let mut ti = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
if let Some(obj) = ti.as_object_mut() {
obj.insert("command".into(), Value::String(rewritten.clone()));
}
ti
};
let mut hook_output = json!({
"hookEventName": PRE_TOOL_USE_KEY,
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": updated_input
});
if allow {
hook_output
.as_object_mut()
.unwrap()
.insert("permissionDecision".into(), json!("allow"));
}
PayloadAction::Rewrite {
cmd: cmd.to_string(),
output: pre_tool_use_rewrite_output(v, &rewritten, allow.then_some("allow")),
rewritten,
decision: if allow {
HookOutcome::Allow
} else {
HookOutcome::Ask
},
output: json!({ "hookSpecificOutput": hook_output }),
}
}
@@ -721,22 +725,20 @@ pub fn run_claude() -> Result<()> {
audit_log("rewrite", &cmd, &rewritten);
log_hook_decision(&v, &cmd, decision, Some(&rewritten));
}
PayloadAction::Skip { decision, cmd } => {
PayloadAction::Skip {
decision,
cmd,
reason,
} => {
// `rtk hook audit`'s skip-breakdown groups by a "skip:<reason>" prefix
// (see hook_audit_cmd.rs) — Skip is only ever reached via Deny/Defer,
// so map those to the reasons it expects rather than the bare
// HookOutcome::Display used for the Rewrite/tracking-DB paths.
// (see hook_audit_cmd.rs). Carry the reason separately from the
// decision so distinct defer causes remain diagnosable.
//
// Skip has no stdout response to write (Claude Code falls through to
// its own native handling), but log_hook_decision is still deferred to
// last for the same reason as the Rewrite arm above: it must never be
// what a Bash tool call is waiting on.
let audit_action = match decision {
HookOutcome::Deny => "skip:deny_rule",
HookOutcome::Defer => "skip:defer",
HookOutcome::Allow | HookOutcome::Ask => "skip",
};
audit_log(audit_action, &cmd, "");
audit_log(reason, &cmd, "");
log_hook_decision(&v, &cmd, decision, None);
}
PayloadAction::Ignore => {}
@@ -755,6 +757,146 @@ fn run_claude_inner(input: &str) -> Option<String> {
}
}
// ── Codex CLI native hook ─────────────────────────────────────
fn is_supported_codex_permission_mode(v: &Value) -> bool {
matches!(
v.get("permission_mode").and_then(Value::as_str),
Some("default" | "acceptEdits" | "plan" | "dontAsk" | "bypassPermissions")
)
}
fn process_codex_payload(v: &Value) -> PayloadAction {
if v.get("hook_event_name").and_then(Value::as_str) != Some(PRE_TOOL_USE_KEY)
|| !matches!(
v.get("tool_name").and_then(Value::as_str),
Some("Bash" | "bash")
)
{
return PayloadAction::Ignore;
}
let cmd = match v
.pointer("/tool_input/command")
.and_then(Value::as_str)
.filter(|cmd| !cmd.is_empty())
{
Some(cmd) => cmd,
None => return PayloadAction::Ignore,
};
// Codex deliberately includes this field in every hook event. Fail open
// for missing or future modes instead of assuming their approval semantics.
if !is_supported_codex_permission_mode(v) {
return PayloadAction::Skip {
decision: HookOutcome::Defer,
reason: "skip:unsupported_permission_mode",
cmd: cmd.to_string(),
};
}
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return PayloadAction::Skip {
decision: HookOutcome::Defer,
reason: "skip:defer",
cmd: cmd.to_string(),
};
}
process_codex_payload_from_decision(v, cmd, decide_hook_action(cmd, permissions::Host::Codex))
}
fn process_codex_payload_from_decision(
v: &Value,
cmd: &str,
decision: HookDecision,
) -> PayloadAction {
let (rewritten, outcome) = match decision {
HookDecision::AllowRewrite(rewritten) => (rewritten, HookOutcome::Allow),
HookDecision::AskRewrite(rewritten) => (rewritten, HookOutcome::Ask),
HookDecision::Deny => {
return PayloadAction::Skip {
decision: HookOutcome::Deny,
reason: "skip:deny_rule",
cmd: cmd.to_string(),
}
}
HookDecision::Defer => {
return PayloadAction::Skip {
decision: HookOutcome::Defer,
reason: "skip:no_rewrite",
cmd: cmd.to_string(),
}
}
};
// Both AllowRewrite and AskRewrite require protocol-level allow: Codex
// cannot accept updatedInput with ask or an omitted permissionDecision.
// The internal outcome remains Ask for Default, not an RTK auto-approval.
// Its runtime applies the replacement before native approval and sandbox
// checks, so this is a protocol-level allow rather than RTK approving the
// command. Those checks inspect the rewritten argv, however, and Codex's
// safe/dangerous-command classifiers do not currently unwrap `rtk`. This
// can add prompts for known-safe commands and obscure classifier signals
// for wrapped mutating commands such as git push. Keep the passthrough gates
// above conservative and revisit this boundary whenever coverage expands.
PayloadAction::Rewrite {
cmd: cmd.to_string(),
output: pre_tool_use_rewrite_output(v, &rewritten, Some("allow")),
decision: outcome,
rewritten,
}
}
/// Run the Codex CLI PreToolUse hook natively.
pub fn run_codex() -> Result<()> {
let input = match read_stdin_limited() {
Ok(input) => input,
Err(e) => {
let _ = writeln!(io::stderr(), "[rtk hook] Failed to read JSON input: {e}");
return Ok(());
}
};
let input = strip_leading_bom(&input).trim();
if input.is_empty() {
return Ok(());
}
let v: Value = match serde_json::from_str(input) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(io::stderr(), "[rtk hook] Failed to parse JSON input: {e}");
return Ok(());
}
};
match process_codex_payload(&v) {
PayloadAction::Rewrite {
cmd,
rewritten,
output,
..
} => {
audit_log("rewrite", &cmd, &rewritten);
let _ = writeln!(io::stdout(), "{output}");
}
PayloadAction::Skip { cmd, reason, .. } => audit_log(reason, &cmd, ""),
PayloadAction::Ignore => {}
}
Ok(())
}
#[cfg(test)]
fn run_codex_inner(input: &str) -> Option<String> {
let input = strip_leading_bom(input).trim();
let v: Value = serde_json::from_str(input).ok()?;
match process_codex_payload(&v) {
PayloadAction::Rewrite { output, .. } => Some(output.to_string()),
_ => None,
}
}
// ── Cursor native hook ─────────────────────────────────────────
/// Run the Cursor Agent hook natively.
@@ -906,21 +1048,7 @@ fn droid_response_from_decision(v: &Value, cmd: &str, decision: HookDecision) ->
audit_log("rewrite", cmd, &rewritten);
let updated_input = {
let mut ti = v.get("tool_input").cloned().unwrap_or_else(|| json!({}));
if let Some(obj) = ti.as_object_mut() {
obj.insert("command".into(), Value::String(rewritten));
}
ti
};
Some(json!({
"hookSpecificOutput": {
"hookEventName": PRE_TOOL_USE_KEY,
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": updated_input
}
}))
Some(pre_tool_use_rewrite_output(v, &rewritten, None))
}
/// Run the Factory Droid PreToolUse hook natively.
@@ -1444,6 +1572,32 @@ mod tests {
);
}
#[test]
fn test_pre_tool_use_rewrite_output_merges_input_and_optional_decision() {
let input = json!({
"tool_input": {
"command": "git status",
"timeout": 30_000,
"description": "Inspect the working tree"
}
});
let ask = pre_tool_use_rewrite_output(&input, "rtk git status", None);
let ask_hook = &ask["hookSpecificOutput"];
assert_eq!(ask_hook["hookEventName"], PRE_TOOL_USE_KEY);
assert_eq!(ask_hook["permissionDecisionReason"], "RTK auto-rewrite");
assert!(ask_hook.get("permissionDecision").is_none());
assert_eq!(ask_hook["updatedInput"]["command"], "rtk git status");
assert_eq!(ask_hook["updatedInput"]["timeout"], 30_000);
assert_eq!(
ask_hook["updatedInput"]["description"],
"Inspect the working tree"
);
let allow = pre_tool_use_rewrite_output(&input, "rtk git status", Some("allow"));
assert_eq!(allow["hookSpecificOutput"]["permissionDecision"], "allow");
}
// --- Claude handler ---
fn claude_input(cmd: &str) -> String {
@@ -1751,6 +1905,214 @@ mod tests {
);
}
// --- Codex handler ---
fn codex_input_with_permission_mode(cmd: &str, permission_mode: Option<&str>) -> String {
let mut input = json!({
"session_id": "session-1",
"turn_id": "turn-1",
"hook_event_name": PRE_TOOL_USE_KEY,
"tool_name": "Bash",
"tool_use_id": "tool-1",
"tool_input": { "command": cmd }
});
if let Some(permission_mode) = permission_mode {
input["permission_mode"] = json!(permission_mode);
}
input.to_string()
}
// Normal Codex payloads include `default`; missing permission_mode is
// covered deliberately by the dedicated fail-open test below.
fn codex_input(cmd: &str) -> String {
codex_input_with_permission_mode(cmd, Some("default"))
}
#[test]
fn test_codex_rewrite_uses_required_allow_shape() {
let result = run_codex_inner(&codex_input("git status")).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
let hook = &v["hookSpecificOutput"];
assert_eq!(hook["hookEventName"], PRE_TOOL_USE_KEY);
assert_eq!(hook["permissionDecision"], "allow");
assert_eq!(hook["permissionDecisionReason"], "RTK auto-rewrite");
assert_eq!(hook["updatedInput"]["command"], "rtk git status");
}
#[test]
fn test_codex_shared_decision_preserves_host_approval_and_deny() {
let input = json!({"tool_input": {"command": "git status", "timeout": 30000}});
for (verdict, expected) in [
(PermissionVerdict::Default, HookOutcome::Ask),
(PermissionVerdict::Ask, HookOutcome::Ask),
(PermissionVerdict::Allow, HookOutcome::Allow),
] {
let decision =
super::super::decision::decide_with_params("git status", verdict, &[], &[]);
let PayloadAction::Rewrite {
output, decision, ..
} = process_codex_payload_from_decision(&input, "git status", decision)
else {
panic!("expected rewrite")
};
assert_eq!(decision, expected);
assert_eq!(output["hookSpecificOutput"]["permissionDecision"], "allow");
assert_eq!(
output["hookSpecificOutput"]["updatedInput"]["timeout"],
30000
);
assert_eq!(
output["hookSpecificOutput"]["updatedInput"]["command"],
"rtk git status"
);
}
let denied = super::super::decision::decide_with_params(
"git status",
PermissionVerdict::Deny,
&[],
&[],
);
assert!(matches!(
process_codex_payload_from_decision(&input, "git status", denied),
PayloadAction::Skip {
decision: HookOutcome::Deny,
reason: "skip:deny_rule",
..
}
));
}
#[test]
fn test_codex_skip_reasons_remain_distinct() {
for (command, mode, expected) in [
("git status", None, "skip:unsupported_permission_mode"),
(
"git status",
Some("futureMode"),
"skip:unsupported_permission_mode",
),
("git status $(whoami)", Some("default"), "skip:defer"),
("htop", Some("default"), "skip:no_rewrite"),
] {
let input: Value =
serde_json::from_str(&codex_input_with_permission_mode(command, mode)).unwrap();
let PayloadAction::Skip { reason, .. } = process_codex_payload(&input) else {
panic!("expected skip for {command}")
};
assert_eq!(reason, expected);
}
}
#[test]
fn test_codex_rewrites_all_documented_permission_modes() {
for permission_mode in [
"default",
"acceptEdits",
"plan",
"dontAsk",
"bypassPermissions",
] {
assert!(
run_codex_inner(&codex_input_with_permission_mode(
"git status",
Some(permission_mode)
))
.is_some(),
"documented permission mode should rewrite: {permission_mode}"
);
}
}
#[test]
fn test_codex_unknown_or_missing_permission_mode_passes_through() {
assert!(run_codex_inner(&codex_input_with_permission_mode("git status", None)).is_none());
assert!(run_codex_inner(&codex_input_with_permission_mode(
"git status",
Some("futureMode")
))
.is_none());
}
#[test]
fn test_codex_rewrites_commands_that_still_need_native_approval() {
let result = run_codex_inner(&codex_input("cargo test")).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(
v.pointer("/hookSpecificOutput/updatedInput/command"),
Some(&json!("rtk cargo test"))
);
}
#[test]
fn test_codex_rewrite_preserves_tool_input_fields() {
let input = json!({
"hook_event_name": PRE_TOOL_USE_KEY,
"tool_name": "Bash",
"permission_mode": "default",
"tool_input": {
"command": "git status --short",
"timeout": 30_000,
"description": "Inspect the working tree"
}
})
.to_string();
let result = run_codex_inner(&input).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
let updated = &v["hookSpecificOutput"]["updatedInput"];
assert_eq!(updated["command"], "rtk git status --short");
assert_eq!(updated["timeout"], 30_000);
assert_eq!(updated["description"], "Inspect the working tree");
}
#[test]
fn test_codex_ignores_other_events_and_tools() {
let other_event = json!({
"hook_event_name": "PostToolUse",
"tool_name": "Bash",
"tool_input": { "command": "git status" }
})
.to_string();
let other_tool = json!({
"hook_event_name": PRE_TOOL_USE_KEY,
"tool_name": "apply_patch",
"tool_input": { "command": "git status" }
})
.to_string();
assert!(run_codex_inner(&other_event).is_none());
assert!(run_codex_inner(&other_tool).is_none());
}
#[test]
fn test_codex_passthrough_for_unsupported_or_unattestable_commands() {
assert!(run_codex_inner(&codex_input("rtk git status")).is_none());
assert!(run_codex_inner(&codex_input("htop")).is_none());
assert!(run_codex_inner(&codex_input("rm -rf /tmp/rtk-safety-test")).is_none());
assert!(run_codex_inner(&codex_input("sudo rm -rf /tmp/rtk-safety-test")).is_none());
assert!(run_codex_inner(&codex_input("git status > /tmp/status")).is_none());
assert!(run_codex_inner(&codex_input("git status $(touch /tmp/x)")).is_none());
}
#[test]
fn test_codex_rewrites_compound_command_directly() {
let result = run_codex_inner(&codex_input("git add . && cargo test")).unwrap();
let v: Value = serde_json::from_str(&result).unwrap();
assert_eq!(
v.pointer("/hookSpecificOutput/updatedInput/command"),
Some(&json!("rtk git add . && rtk cargo test"))
);
}
#[test]
fn test_codex_malformed_json_and_empty_command_pass_through() {
assert!(run_codex_inner("not valid json {{{").is_none());
assert!(run_codex_inner(&codex_input("")).is_none());
}
// --- Cursor handler ---
fn cursor_input(cmd: &str) -> String {
+711 -137
View File
File diff suppressed because it is too large. Load diff
+34 -4
View File
@@ -17,15 +17,26 @@ pub mod rewrite_cmd;
pub mod trust;
pub mod verify_cmd;
pub fn is_claude_hook_command(command: &str) -> bool {
fn is_rtk_binary(binary: &str) -> bool {
let binary_name = binary.rsplit(['/', '\\']).next().unwrap_or(binary);
matches!(binary_name, "rtk" | "rtk.exe")
}
fn is_rtk_hook_command(command: &str, agent: &str) -> bool {
let parts = crate::discover::lexer::shell_split(command);
let [binary, hook, claude] = parts.as_slice() else {
let [parsed_binary, hook, target] = parts.as_slice() else {
return false;
};
let binary_name = binary.rsplit(['/', '\\']).next().unwrap_or(binary);
is_rtk_binary(parsed_binary) && hook == "hook" && target == agent
}
binary_name == "rtk" && hook == "hook" && claude == "claude"
pub fn is_claude_hook_command(command: &str) -> bool {
is_rtk_hook_command(command, "claude")
}
pub fn is_codex_hook_command(command: &str) -> bool {
is_rtk_hook_command(command, "codex")
}
#[cfg(test)]
@@ -39,6 +50,9 @@ mod tests {
assert!(is_claude_hook_command(
"\"/opt/homebrew/bin/rtk\" hook claude"
));
assert!(is_claude_hook_command(
"/Users/jane/My\\ Apps/rtk hook claude"
));
}
#[test]
@@ -47,4 +61,20 @@ mod tests {
assert!(!is_claude_hook_command("/opt/homebrew/bin/rtk hook cursor"));
assert!(!is_claude_hook_command("echo rtk hook claude"));
}
#[test]
fn codex_hook_command_matches_bare_absolute_and_windows_rtk() {
assert!(is_codex_hook_command("rtk hook codex"));
assert!(is_codex_hook_command("/opt/homebrew/bin/rtk hook codex"));
assert!(is_codex_hook_command(
"\"C:\\Program Files\\rtk.exe\" hook codex"
));
}
#[test]
fn codex_hook_command_rejects_other_commands() {
assert!(!is_codex_hook_command("rtk hook claude"));
assert!(!is_codex_hook_command("echo rtk hook codex"));
assert!(!is_codex_hook_command("\"rtk\"evil hook codex"));
}
}
+6 -1
View File
@@ -34,6 +34,7 @@ pub fn check_command(cmd: &str) -> PermissionVerdict {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Host {
Claude,
Codex,
Cursor,
Gemini,
Droid,
@@ -57,7 +58,11 @@ pub(crate) fn load_rules_for(host: Host) -> (Vec<String>, Vec<String>, Vec<Strin
Host::Cursor => load_cursor_rules(),
Host::Gemini => load_gemini_rules(),
Host::Droid => load_droid_rules(),
Host::Vibe => (Vec::new(), Vec::new(), Vec::new()),
// Hosts with no RTK-side rule source. Codex enforces its native
// execution rules after updatedInput. Do not interpret either host's
// rules as Claude Bash patterns or borrow another host's settings.
// No RTK-side match means Default, not an explicit Allow.
Host::Codex | Host::Vibe => (Vec::new(), Vec::new(), Vec::new()),
}
}
+53 -9
View File
@@ -24,8 +24,8 @@ use cmds::ruby::{rake_cmd, rspec_cmd, rubocop_cmd};
use cmds::rust::{cargo_cmd, runner};
use cmds::scala::sbt_cmd;
use cmds::system::{
ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls, pipe_cmd,
read, search, summary, tree, wc_cmd,
ast_grep_cmd, ctest_cmd, deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls,
pipe_cmd, read, search, summary, tree, wc_cmd,
};
use anyhow::{Context, Result};
@@ -111,11 +111,16 @@ enum Commands {
/// Filter: none (default, full content), minimal, aggressive
#[arg(short, long, default_value = "none")]
level: core::filter::FilterLevel,
/// Max lines
#[arg(short, long, conflicts_with = "tail_lines")]
/// Structural preview capped at N lines (keeps signatures and imports;
/// not the first N lines — use --head-lines for that)
#[arg(short, long, conflicts_with_all = ["head_lines", "tail_lines"])]
max_lines: Option<usize>,
/// Keep only the first N lines (byte-exact at the default --level none
/// with -n off; --level and -n still transform the window)
#[arg(long, conflicts_with_all = ["max_lines", "tail_lines"])]
head_lines: Option<usize>,
/// Keep only last N lines
#[arg(long, conflicts_with = "max_lines")]
#[arg(long, conflicts_with_all = ["max_lines", "head_lines"])]
tail_lines: Option<usize>,
/// Show line numbers
#[arg(short = 'n', long)]
@@ -355,6 +360,13 @@ enum Commands {
extra_args: Vec<String>,
},
/// Compact ast-grep - runs ast-grep natively, groups matches by file
AstGrep {
/// ast-grep subcommand, pattern, path, and any flags (e.g. run -p '$$$', --json)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
extra_args: Vec<String>,
},
/// Initialize rtk instructions for assistant CLI usage
Init {
/// Add to global assistant config directory instead of local project file
@@ -405,7 +417,7 @@ enum Commands {
#[arg(long)]
uninstall: bool,
/// Target Codex CLI (uses AGENTS.md + RTK.md, no Claude hook patching)
/// Target Codex CLI (uses PreToolUse hook + AGENTS.md + RTK.md)
#[arg(long)]
codex: bool,
@@ -953,6 +965,8 @@ enum Commands {
enum HookCommands {
/// Process Claude Code PreToolUse hook (reads JSON from stdin)
Claude,
/// Process Codex CLI PreToolUse hook (reads JSON from stdin)
Codex,
/// Process Cursor Agent hook (reads JSON from stdin)
Cursor,
/// Process Gemini CLI BeforeTool hook (reads JSON from stdin)
@@ -1848,8 +1862,11 @@ fn run_cli() -> Result<i32> {
};
// Warn if installed hook is outdated/missing (1/day, non-blocking).
// Skip for Gain — it shows its own inline hook warning.
if !matches!(cli.command, Commands::Gain { .. }) {
// Skip for Gain (shows its own inline warning), Init/Verify (manage the hook themselves).
if !matches!(
cli.command,
Commands::Gain { .. } | Commands::Init { .. } | Commands::Verify { .. }
) {
hooks::hook_check::maybe_warn();
}
@@ -1870,6 +1887,7 @@ fn run_cli() -> Result<i32> {
files,
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
} => {
@@ -1882,12 +1900,20 @@ fn run_cli() -> Result<i32> {
continue;
}
stdin_seen = true;
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)
read::run_stdin(
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
cli.verbose,
)
} else {
read::run(
file,
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
cli.verbose,
@@ -2248,6 +2274,7 @@ fn run_cli() -> Result<i32> {
&extra_args,
cli.verbose,
)?,
Commands::AstGrep { extra_args } => ast_grep_cmd::run(&extra_args)?,
Commands::Rg { extra_args } => {
search::run(search::Engine::Rg, 80, 200, false, &extra_args, cli.verbose)?
}
@@ -2768,6 +2795,10 @@ fn run_cli() -> Result<i32> {
hooks::hook_cmd::run_claude()?;
0
}
HookCommands::Codex => {
hooks::hook_cmd::run_codex()?;
0
}
HookCommands::Cursor => {
hooks::hook_cmd::run_cursor()?;
0
@@ -3117,6 +3148,7 @@ fn is_operational_command(cmd: &Commands) -> bool {
| Commands::Summary { .. }
| Commands::Grep { .. }
| Commands::Rg { .. }
| Commands::AstGrep { .. }
| Commands::Wget { .. }
| Commands::Vitest { .. }
| Commands::Ctest { .. }
@@ -3590,6 +3622,7 @@ mod tests {
"tree",
"read",
"rg",
"ast-grep",
"git",
"gh",
"glab",
@@ -3716,6 +3749,17 @@ mod tests {
));
}
#[test]
fn test_hook_codex_parses() {
let cli = Cli::try_parse_from(["rtk", "hook", "codex"]).unwrap();
assert!(matches!(
cli.command,
Commands::Hook {
command: HookCommands::Codex
}
));
}
#[test]
fn test_hook_check_parses() {
let cli = Cli::try_parse_from(["rtk", "hook", "check", "git", "status"]).unwrap();
+99
View File
@@ -0,0 +1,99 @@
//! Regression test for the missing `restore_double_dash` call in dotnet_cmd.rs
//! (see run_dotnet_with_binlog/run_format): without it, `inject_report_trx_into_args`
//! can't tell "the user passed no `--`" from "the user passed `--` but clap's
//! trailing_var_arg stripped it". Since args then look like `["FullyQualifiedName=MyFilter"]`
//! (no `--` at all), it appends a *fresh* `-- --report-trx` at the end instead of reusing the
//! user's own `--` — landing the user's MTP-runtime filter expression BEFORE the separator
//! (misread as a `dotnet test` CLI arg) instead of after it, and stranding `--report-trx` with
//! nothing following it.
//!
//! Stubs `dotnet` on PATH with a script that records its argv, since the real
//! dotnet SDK isn't available in this environment.
#[cfg(unix)]
#[test]
fn dotnet_test_reuses_users_double_dash_for_report_trx_injection() {
use std::process::Command;
fn shell_quote(path: &std::path::Path) -> String {
format!("'{}'", path.display().to_string().replace('\'', "'\\''"))
}
let dir = tempfile::tempdir().expect("tempdir");
let argv_file = dir.path().join("argv.txt");
let stub_path = dir.path().join("dotnet");
// --report-trx is only injected after `--` in VsTestBridge mode (detect_test_runner_mode),
// which requires a project file with UseMicrosoftTestingPlatformRunner/UseTestingPlatformRunner.
std::fs::write(
dir.path().join("MyProject.csproj"),
r#"<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
</PropertyGroup>
</Project>"#,
)
.expect("write csproj");
std::fs::write(
&stub_path,
format!(
"#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\nexit 0\n",
shell_quote(&argv_file)
),
)
.expect("write stub");
let mut perms = std::fs::metadata(&stub_path)
.expect("stat stub")
.permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
std::fs::set_permissions(&stub_path, perms).expect("chmod stub");
let path_with_stub = format!(
"{}:{}",
dir.path().display(),
std::env::var("PATH").unwrap_or_default()
);
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
.env("PATH", path_with_stub)
.current_dir(dir.path())
.args(["dotnet", "test", "--", "FullyQualifiedName=MyFilter"])
.output()
.expect("spawn rtk");
assert!(
out.status.success(),
"rtk dotnet test failed: stdout={} stderr={}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
let argv: Vec<String> = std::fs::read_to_string(&argv_file)
.expect("read captured argv")
.lines()
.map(str::to_string)
.collect();
let dashdash_count = argv.iter().filter(|a| a.as_str() == "--").count();
assert_eq!(
dashdash_count, 1,
"the user's -- must be reused, not duplicated: {argv:?}"
);
let sep = argv.iter().position(|a| a == "--").expect("has --");
assert_eq!(
argv.get(sep + 1).map(String::as_str),
Some("--report-trx"),
"--report-trx should be injected right after the user's --: {argv:?}"
);
let filter_pos = argv
.iter()
.position(|a| a == "FullyQualifiedName=MyFilter")
.expect("filter expression present");
assert!(
filter_pos > sep,
"the user's filter expression must stay AFTER --, not be pulled before it \
when clap's stripped -- gets a fresh one appended at the end: {argv:?}"
);
}
File diff suppressed because it is too large. Load diff
+387
View File
@@ -0,0 +1,387 @@
src/learn/detector.rs:51:static UNKNOWN_FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
src/learn/detector.rs:52: Regex::new(
src/learn/detector.rs:53: r"(?i)(unexpected argument|unknown (option|flag)|unrecognized (option|flag)|invalid (option|flag))"
src/learn/detector.rs:54: ).unwrap()
src/learn/detector.rs:55:});
src/learn/detector.rs:57:static CMD_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {
src/learn/detector.rs:58: Regex::new(
src/learn/detector.rs:59: r"(?i)(command not found|not recognized as an internal|no such file or directory.*command)",
src/learn/detector.rs:60: )
src/learn/detector.rs:61: .unwrap()
src/learn/detector.rs:62:});
src/learn/detector.rs:64:static WRONG_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
src/learn/detector.rs:65: Regex::new(r"(?i)(no such file or directory|cannot find the path|file not found)").unwrap()
src/learn/detector.rs:66:});
src/learn/detector.rs:68:static MISSING_ARG_RE: LazyLock<Regex> = LazyLock::new(|| {
src/learn/detector.rs:69: Regex::new(
src/learn/detector.rs:70: r"(?i)(requires a value|requires an argument|missing (required )?argument|expected.*argument)"
src/learn/detector.rs:71: ).unwrap()
src/learn/detector.rs:72:});
src/learn/detector.rs:75: LazyLock::new(|| Regex::new(r"(?i)(permission denied|access denied|not permitted)").unwrap());
src/learn/detector.rs:78:static USER_REJECTION_RE: LazyLock<Regex> = LazyLock::new(|| {
src/learn/detector.rs:79: Regex::new(
src/learn/detector.rs:80: r"(?i)(user (doesn't want|declined|rejected|cancelled)|operation (cancelled|aborted) by user)"
src/learn/detector.rs:81: ).unwrap()
src/learn/detector.rs:82:});
src/cmds/git/gh_cmd.rs:16:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
src/cmds/git/gh_cmd.rs:18: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
src/cmds/git/gh_cmd.rs:20: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
src/cmds/git/gh_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
src/cmds/git/gh_cmd.rs:23:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
src/cmds/system/ctest_cmd.rs:24:static TEST_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:25: Regex::new(
src/cmds/system/ctest_cmd.rs:26: r"(?s)^\s*(?:\d+/(\d+)\s+)?Test\s+#(\d+):\s+(.+?)\s+\.{2,}\s*(?:\*{3})?\s*(.+?)\s+([\d.]+)\s+sec\s*$",
src/cmds/system/ctest_cmd.rs:27: )
src/cmds/system/ctest_cmd.rs:28: .expect("invalid ctest result regex")
src/cmds/system/ctest_cmd.rs:29:});
src/cmds/system/ctest_cmd.rs:30:static RESULT_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:31: Regex::new(r"^\s*(?:\d+/\d+\s+)?Test\s+#\d+:")
src/cmds/system/ctest_cmd.rs:32: .expect("invalid ctest result prefix regex")
src/cmds/system/ctest_cmd.rs:33:});
src/cmds/system/ctest_cmd.rs:34:static RESULT_TERMINATOR_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:35: Regex::new(r"[\d.]+\s+sec\s*$").expect("invalid ctest result terminator regex")
src/cmds/system/ctest_cmd.rs:36:});
src/cmds/system/ctest_cmd.rs:37:static START_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:38: Regex::new(r"^\s*Start\s+(\d+):\s*(.*?)\s*$").expect("invalid ctest start regex")
src/cmds/system/ctest_cmd.rs:39:});
src/cmds/system/ctest_cmd.rs:40:static SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:41: Regex::new(r"^\s*\d+%\s+tests passed,\s+(\d+)\s+tests failed out of\s+(\d+)")
src/cmds/system/ctest_cmd.rs:42: .expect("invalid ctest summary regex")
src/cmds/system/ctest_cmd.rs:43:});
src/cmds/system/ctest_cmd.rs:44:static TIME_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ctest_cmd.rs:45: Regex::new(r"^\s*Total Test time \(real\)\s+=\s+([\d.]+)\s+sec")
src/cmds/system/ctest_cmd.rs:46: .expect("invalid ctest time regex")
src/cmds/system/ctest_cmd.rs:47:});
src/cmds/git/glab_cmd.rs:23:static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
src/cmds/git/glab_cmd.rs:25: LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
src/cmds/git/glab_cmd.rs:27: LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
src/cmds/git/glab_cmd.rs:29: LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
src/cmds/git/glab_cmd.rs:30:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
src/cmds/git/glab_cmd.rs:32: LazyLock::new(|| Regex::new(r"/-/merge_requests/(\d+)").unwrap());
src/cmds/git/glab_cmd.rs:34:static SECTION_MARKER_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/git/glab_cmd.rs:35: Regex::new(r"section_(?:start|end):\d+:[a-z0-9_]+(?:\x1b\[0K|\[0K)*").unwrap()
src/cmds/git/glab_cmd.rs:36:});
src/cmds/git/glab_cmd.rs:38:static BARE_ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[[\d;]+[A-Za-z]").unwrap());
src/cmds/ruby/rake_cmd.rs:168: LazyLock::new(|| regex::Regex::new(r"^\d+\)\s+(Failure|Error):$").unwrap());
src/cmds/system/ls.rs:14:static LS_DATE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/ls.rs:15: Regex::new(
src/cmds/system/ls.rs:16: r"\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+(?:\d{4}|\d{2}:\d{2})\s+"
src/cmds/system/ls.rs:17: )
src/cmds/system/ls.rs:18: .unwrap()
src/cmds/system/ls.rs:19:});
src/cmds/git/gt_cmd.rs:13: LazyLock::new(|| Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b").unwrap());
src/cmds/git/gt_cmd.rs:14:static BRANCH_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/git/gt_cmd.rs:15: Regex::new(
src/cmds/git/gt_cmd.rs:16: r#"(?:Created|Pushed|pushed|Deleted|deleted)\s+branch\s+[`"']?([a-zA-Z0-9/_.\-+@]+)"#,
src/cmds/git/gt_cmd.rs:17: )
src/cmds/git/gt_cmd.rs:18: .unwrap()
src/cmds/git/gt_cmd.rs:19:});
src/cmds/git/gt_cmd.rs:20:static PR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/git/gt_cmd.rs:21: Regex::new(r"(Created|Updated)\s+pull\s+request\s+#(\d+)\s+for\s+([^\s:]+)(?::\s*(\S+))?")
src/cmds/git/gt_cmd.rs:22: .unwrap()
src/cmds/git/gt_cmd.rs:23:});
src/cmds/system/search.rs:739: LazyLock::new(|| Regex::new(r"^([^\x00]+)\x00(\d+)([:-])(.*)$").unwrap());
src/discover/registry.rs:54:static REGEX_SET: LazyLock<RegexSet> = LazyLock::new(|| {
src/discover/registry.rs:55: RegexSet::new(RULES.iter().map(|r| r.pattern)).expect("invalid regex patterns")
src/discover/registry.rs:56:});
src/discover/registry.rs:57:static COMPILED: LazyLock<Vec<Regex>> = LazyLock::new(|| {
src/discover/registry.rs:58: RULES
src/discover/registry.rs:59: .iter()
src/discover/registry.rs:60: .map(|r| Regex::new(r.pattern).expect("invalid regex"))
src/discover/registry.rs:61: .collect()
src/discover/registry.rs:62:});
src/discover/registry.rs:63:static ENV_PREFIX: LazyLock<Regex> = LazyLock::new(|| {
src/discover/registry.rs:64: let double_quoted = r#""(?:[^"\\]|\\.)*""#;
src/discover/registry.rs:65: let single_quoted = r#"'(?:[^'\\]|\\.)*'"#;
src/discover/registry.rs:66: let unquoted = r#"[^\s]*"#;
src/discover/registry.rs:67: let env_value = format!("(?:{}|{}|{})", double_quoted, single_quoted, unquoted);
src/discover/registry.rs:68: let env_assign = format!(r#"[A-Z_][A-Z0-9_]*={}"#, env_value);
src/discover/registry.rs:69: Regex::new(&format!(r#"^(?:sudo\s+|env\s+|{}\s+)+"#, env_assign)).unwrap()
src/discover/registry.rs:70:});
src/discover/registry.rs:73:static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
src/discover/registry.rs:74: Regex::new(r"^(?:(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=\S+|\s+\S+)|--work-tree(?:=\S+|\s+\S+)|--no-pager|--no-optional-locks|--bare|--literal-pathspecs)\s+)+").unwrap()
src/discover/registry.rs:75:});
src/discover/registry.rs:80:static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:82: LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:83:static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:85: LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:87: LazyLock::new(|| Regex::new(r"^tail\s+--lines=(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:89: LazyLock::new(|| Regex::new(r"^tail\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
src/discover/registry.rs:539: LazyLock::new(|| Regex::new(r"(?m)[ \t\x0B\x0C]*\\\r?\n[ \t\x0B\x0C]*").unwrap());
src/discover/registry.rs:541:static BASH_JOIN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\\r?\n").unwrap());
src/cmds/system/log_cmd.rs:14:static TIMESTAMP_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/log_cmd.rs:15: Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap()
src/cmds/system/log_cmd.rs:16:});
src/cmds/system/log_cmd.rs:17:static UUID_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/system/log_cmd.rs:18: Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
src/cmds/system/log_cmd.rs:19: .unwrap()
src/cmds/system/log_cmd.rs:20:});
src/cmds/system/log_cmd.rs:21:static HEX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"0x[0-9a-fA-F]+").unwrap());
src/cmds/system/log_cmd.rs:22:static NUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b\d{4,}\b").unwrap());
src/cmds/system/log_cmd.rs:23:static PATH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/[\w./\-]+").unwrap());
src/cmds/ruby/rspec_cmd.rs:22: LazyLock::new(|| Regex::new(r"(?i)running via spring preloader").unwrap());
src/cmds/ruby/rspec_cmd.rs:23:static RE_SIMPLECOV: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/ruby/rspec_cmd.rs:24: Regex::new(r"(?i)(coverage report|simplecov|coverage/|\.simplecov|All Files.*Lines)").unwrap()
src/cmds/ruby/rspec_cmd.rs:25:});
src/cmds/ruby/rspec_cmd.rs:27: LazyLock::new(|| Regex::new(r"^DEPRECATION WARNING:").unwrap());
src/cmds/ruby/rspec_cmd.rs:28:static RE_FINISHED_IN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Finished in \d").unwrap());
src/cmds/ruby/rspec_cmd.rs:30: LazyLock::new(|| Regex::new(r"saved screenshot to (.+)").unwrap());
src/cmds/ruby/rspec_cmd.rs:32: LazyLock::new(|| Regex::new(r"(\d+) examples?, (\d+) failures?").unwrap());
src/cmds/js/playwright_cmd.rs:168: LazyLock::new(|| Regex::new(r"(\d+)\s+(passed|failed|flaky|skipped)").unwrap());
src/cmds/js/playwright_cmd.rs:170: LazyLock::new(|| Regex::new(r"\((\d+(?:\.\d+)?)(ms|s|m)\)").unwrap());
src/cmds/js/playwright_cmd.rs:220: LazyLock::new(|| Regex::new(r"[×✗]\s+.*?›\s+([^›]+\.spec\.[tj]sx?)").unwrap());
src/cmds/js/next_cmd.rs:45: static BUNDLE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/js/next_cmd.rs:46: Regex::new(r"^[○●◐λ✓]\s+([\w/\-\.]+)\s+(\d+(?:\.\d+)?)\s*(kB|B)\s+(\d+(?:\.\d+)?)\s*(kB|B)")
src/cmds/js/next_cmd.rs:47: .unwrap()
src/cmds/js/next_cmd.rs:48: });
src/cmds/js/next_cmd.rs:172: LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*(s|ms)").unwrap());
src/cmds/php/artisan_cmd.rs:8:static BOX_CHARS_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/php/artisan_cmd.rs:9: Regex::new(r"[\u{2500}-\u{257F}\u{2580}-\u{259F}\u{25A0}-\u{25FF}\u{27A0}-\u{27BF}]+").unwrap()
src/cmds/php/artisan_cmd.rs:10:});
src/cmds/php/artisan_cmd.rs:11:static DOTS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\.{3,}").unwrap());
src/cmds/php/artisan_cmd.rs:12:static MULTI_SPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[ \t]{2,}").unwrap());
src/cmds/php/artisan_cmd.rs:13:static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
src/cmds/jvm/gradlew_cmd.rs:13:static TASK_LINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^> Task :").unwrap());
src/cmds/jvm/gradlew_cmd.rs:15: LazyLock::new(|| Regex::new(r"^\* Try:|^> Run with --|^> Get more help at").unwrap());
src/cmds/jvm/gradlew_cmd.rs:17: LazyLock::new(|| Regex::new(r"^BUILD (SUCCESSFUL|FAILED)").unwrap());
src/cmds/jvm/gradlew_cmd.rs:19: LazyLock::new(|| Regex::new(r"^\d+ actionable tasks?").unwrap());
src/cmds/jvm/gradlew_cmd.rs:180: static DAEMON_LINE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/gradlew_cmd.rs:181: Regex::new(
src/cmds/jvm/gradlew_cmd.rs:182: r"^(Starting a Gradle Daemon|Daemon will be stopped|Reusing configuration cache|Calculating task graph|> Configure project|Deprecated Gradle features|You can use|For more on this|Configuration cache entry)"
src/cmds/jvm/gradlew_cmd.rs:183: )
src/cmds/jvm/gradlew_cmd.rs:184: .unwrap()
src/cmds/jvm/gradlew_cmd.rs:185: });
src/cmds/jvm/gradlew_cmd.rs:186: static PROGRESS: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/gradlew_cmd.rs:187: Regex::new(r"^\s*\d+%|^Downloading|^Configuring|^Resolving|^\[Incubating\]|^Wrote HTML report|^class \S+ could not|^\[android-")
src/cmds/jvm/gradlew_cmd.rs:188: .unwrap()
src/cmds/jvm/gradlew_cmd.rs:189: });
src/cmds/jvm/gradlew_cmd.rs:190: static ERROR_LINE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/gradlew_cmd.rs:191: Regex::new(
src/cmds/jvm/gradlew_cmd.rs:192: r"(?i)(^FAILURE:|^\* What went wrong:|^\* Where:|> Could not|e: |error:|^Execution failed|Lint found \d+ error)"
src/cmds/jvm/gradlew_cmd.rs:193: )
src/cmds/jvm/gradlew_cmd.rs:194: .unwrap()
src/cmds/jvm/gradlew_cmd.rs:195: });
src/cmds/jvm/gradlew_cmd.rs:198: LazyLock::new(|| Regex::new(r"^(w: |warning:|Warning:|WARNING:)").unwrap());
src/cmds/jvm/gradlew_cmd.rs:200: LazyLock::new(|| Regex::new(r"gradle\.com/s/|Publishing build scan").unwrap());
src/cmds/jvm/gradlew_cmd.rs:234: LazyLock::new(|| Regex::new(r"FAILED$| FAILED ").unwrap());
src/cmds/jvm/gradlew_cmd.rs:236: LazyLock::new(|| Regex::new(r" PASSED$| SKIPPED$").unwrap());
src/cmds/jvm/gradlew_cmd.rs:237: static SUMMARY_LINE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/gradlew_cmd.rs:238: Regex::new(
src/cmds/jvm/gradlew_cmd.rs:239: r"\d+ tests? completed|\d+ tests? failed|There were failing tests|See the report at",
src/cmds/jvm/gradlew_cmd.rs:240: )
src/cmds/jvm/gradlew_cmd.rs:241: .unwrap()
src/cmds/jvm/gradlew_cmd.rs:242: });
src/cmds/jvm/gradlew_cmd.rs:312: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_STATUS[_CODE]*:").unwrap());
src/cmds/jvm/gradlew_cmd.rs:314: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_RESULT:").unwrap());
src/cmds/jvm/gradlew_cmd.rs:316: LazyLock::new(|| Regex::new(r"^INSTRUMENTATION_CODE:").unwrap());
src/cmds/jvm/gradlew_cmd.rs:318: LazyLock::new(|| Regex::new(r"^Starting \d+ tests? on ").unwrap());
src/cmds/jvm/gradlew_cmd.rs:320: LazyLock::new(|| Regex::new(r"^Installing APK").unwrap());
src/cmds/jvm/gradlew_cmd.rs:363: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ee]rror:.*\[").unwrap());
src/cmds/jvm/gradlew_cmd.rs:366: LazyLock::new(|| Regex::new(r"[^:]+:\d+:.*[Ww]arning:.*\[").unwrap());
src/cmds/jvm/gradlew_cmd.rs:369: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*[Ll]int").unwrap());
src/cmds/jvm/gradlew_cmd.rs:372: LazyLock::new(|| Regex::new(r"[^:]+:\d+:\d+:.*error").unwrap());
src/cmds/jvm/gradlew_cmd.rs:375: LazyLock::new(|| Regex::new(r"\d+ (issues?|errors?|warnings?)").unwrap());
src/cmds/jvm/gradlew_cmd.rs:377: static REPORT_LINE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/gradlew_cmd.rs:378: Regex::new(r"Wrote (HTML|XML|text) report|file://|/build/reports/lint").unwrap()
src/cmds/jvm/gradlew_cmd.rs:379: });
src/cmds/php/utils.rs:7:static ANSI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[A-Za-z]").unwrap());
src/cmds/php/utils.rs:9: LazyLock::new(|| Regex::new(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]").unwrap());
src/cmds/cloud/psql_cmd.rs:17: LazyLock::new(|| Regex::new(r"-\[ RECORD \d+ \]-").unwrap());
src/cmds/cloud/psql_cmd.rs:18:static SEPARATOR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[-+]+$").unwrap());
src/cmds/cloud/psql_cmd.rs:19:static ROW_COUNT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\(\d+ rows?\)$").unwrap());
src/cmds/cloud/psql_cmd.rs:21: LazyLock::new(|| Regex::new(r"^-\[ RECORD (\d+) \]-").unwrap());
src/cmds/php/phpunit_cmd.rs:20:static FAILURE_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+\) \S").unwrap());
src/cmds/rust/runner.rs:13:static ERROR_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
src/cmds/rust/runner.rs:14: vec![
src/cmds/rust/runner.rs:15: // Generic errors
src/cmds/rust/runner.rs:16: Regex::new(r"(?i)^.*error[\s:\[].*$").unwrap(),
src/cmds/rust/runner.rs:17: Regex::new(r"(?i)^.*\berr\b.*$").unwrap(),
src/cmds/rust/runner.rs:18: Regex::new(r"(?i)^.*warning[\s:\[].*$").unwrap(),
src/cmds/rust/runner.rs:19: Regex::new(r"(?i)^.*\bwarn\b.*$").unwrap(),
src/cmds/rust/runner.rs:20: Regex::new(r"(?i)^.*failed.*$").unwrap(),
src/cmds/rust/runner.rs:21: Regex::new(r"(?i)^.*failure.*$").unwrap(),
src/cmds/rust/runner.rs:22: Regex::new(r"(?i)^.*exception.*$").unwrap(),
src/cmds/rust/runner.rs:23: Regex::new(r"(?i)^.*panic.*$").unwrap(),
src/cmds/rust/runner.rs:24: // Rust specific
src/cmds/rust/runner.rs:25: Regex::new(r"^error\[E\d+\]:.*$").unwrap(),
src/cmds/rust/runner.rs:26: Regex::new(r"^\s*--> .*:\d+:\d+$").unwrap(),
src/cmds/rust/runner.rs:27: // Python
src/cmds/rust/runner.rs:28: Regex::new(r"^Traceback.*$").unwrap(),
src/cmds/rust/runner.rs:29: Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap(),
src/cmds/rust/runner.rs:30: // JavaScript/TypeScript
src/cmds/rust/runner.rs:31: Regex::new(r"^\s*at .*:\d+:\d+.*$").unwrap(),
src/cmds/rust/runner.rs:32: // Go
src/cmds/rust/runner.rs:33: Regex::new(r"^.*\.go:\d+:.*$").unwrap(),
src/cmds/rust/runner.rs:34: ]
src/cmds/rust/runner.rs:35:});
src/cmds/js/vitest_cmd.rs:121: LazyLock::new(|| Regex::new(r"Tests\s+(?:(\d+)\s+failed\s+\|\s+)?(\d+)\s+passed").unwrap());
src/cmds/js/vitest_cmd.rs:123: LazyLock::new(|| Regex::new(r"Duration\s+([\d.]+)(ms|s)").unwrap());
src/cmds/dotnet/binlog.rs:55:static ISSUE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:56: Regex::new(
src/cmds/dotnet/binlog.rs:57: r"(?m)^\s*(?P<file>[^\r\n:(]+)\((?P<line>\d+),(?P<column>\d+)\):\s*(?P<kind>error|warning)\s*(?:(?P<code>[A-Za-z]+\d+)\s*:\s*)?(?P<msg>.*)$"
src/cmds/dotnet/binlog.rs:58: )
src/cmds/dotnet/binlog.rs:59: .expect("valid regex")
src/cmds/dotnet/binlog.rs:60:});
src/cmds/dotnet/binlog.rs:61:static BUILD_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:62: Regex::new(r"(?mi)^\s*(?P<count>\d+)\s+(?P<kind>warning|error)\(s\)").expect("valid regex")
src/cmds/dotnet/binlog.rs:63:});
src/cmds/dotnet/binlog.rs:65: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+error\(s\)").expect("valid regex"));
src/cmds/dotnet/binlog.rs:67: LazyLock::new(|| Regex::new(r"(?i)\b(?P<count>\d+)\s+warning\(s\)").expect("valid regex"));
src/cmds/dotnet/binlog.rs:68:static FALLBACK_ERROR_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:69: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*error(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
src/cmds/dotnet/binlog.rs:70: .expect("valid regex")
src/cmds/dotnet/binlog.rs:71:});
src/cmds/dotnet/binlog.rs:72:static FALLBACK_WARNING_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:73: Regex::new(r"(?mi)^.+\(\d+,\d+\):\s*warning(?:\s+[A-Za-z]{2,}\d{3,})?(?:\s*:.*)?$")
src/cmds/dotnet/binlog.rs:74: .expect("valid regex")
src/cmds/dotnet/binlog.rs:75:});
src/cmds/dotnet/binlog.rs:76:static DURATION_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:77: Regex::new(r"(?m)^\s*Time Elapsed\s+(?P<duration>[^\r\n]+)$").expect("valid regex")
src/cmds/dotnet/binlog.rs:78:});
src/cmds/dotnet/binlog.rs:79:static TEST_RESULT_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:80: Regex::new(
src/cmds/dotnet/binlog.rs:81: r"(?m)(?:Passed!|Failed!)\s*-\s*Failed:\s*(?P<failed>\d+),\s*Passed:\s*(?P<passed>\d+),\s*Skipped:\s*(?P<skipped>\d+),\s*Total:\s*(?P<total>\d+),\s*Duration:\s*(?P<duration>[^\r\n-]+)"
src/cmds/dotnet/binlog.rs:82: )
src/cmds/dotnet/binlog.rs:83: .expect("valid regex")
src/cmds/dotnet/binlog.rs:84:});
src/cmds/dotnet/binlog.rs:85:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:86: Regex::new(
src/cmds/dotnet/binlog.rs:87: r"(?mi)^\s*Test summary:\s*total:\s*(?P<total>\d+),\s*failed:\s*(?P<failed>\d+),\s*(?:succeeded|passed):\s*(?P<passed>\d+),\s*skipped:\s*(?P<skipped>\d+),\s*duration:\s*(?P<duration>[^\r\n]+)$"
src/cmds/dotnet/binlog.rs:88: )
src/cmds/dotnet/binlog.rs:89: .expect("valid regex")
src/cmds/dotnet/binlog.rs:90:});
src/cmds/dotnet/binlog.rs:91:static FAILED_TEST_HEAD_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:92: Regex::new(r"(?m)^\s*Failed\s+(?P<name>[^\r\n\[]+)\s+\[[^\]\r\n]+\]\s*$").expect("valid regex")
src/cmds/dotnet/binlog.rs:93:});
src/cmds/dotnet/binlog.rs:95: LazyLock::new(|| Regex::new(r"(?m)^\s*Restored\s+.+\.csproj\s*\(").expect("valid regex"));
src/cmds/dotnet/binlog.rs:96:static RESTORE_DIAGNOSTIC_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:97: Regex::new(
src/cmds/dotnet/binlog.rs:98: r"(?mi)^\s*(?:(?P<file>.+?)\s+:\s+)?(?P<kind>warning|error)\s+(?P<code>[A-Za-z]{2,}\d{3,})\s*:\s*(?P<msg>.+)$"
src/cmds/dotnet/binlog.rs:99: )
src/cmds/dotnet/binlog.rs:100: .expect("valid regex")
src/cmds/dotnet/binlog.rs:101:});
src/cmds/dotnet/binlog.rs:102:static PROJECT_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:103: Regex::new(r"(?m)^\s*([A-Za-z]:)?[^\r\n]*\.csproj(?:\s|$)").expect("valid regex")
src/cmds/dotnet/binlog.rs:104:});
src/cmds/dotnet/binlog.rs:106: LazyLock::new(|| Regex::new(r"[\x20-\x7E]{5,}").expect("valid regex"));
src/cmds/dotnet/binlog.rs:108: LazyLock::new(|| Regex::new(r"^[A-Za-z]{2,}\d{3,}$").expect("valid regex"));
src/cmds/dotnet/binlog.rs:110: LazyLock::new(|| Regex::new(r"(?i)([A-Za-z]:)?[/\\][^\s]+\.(cs|vb|fs)").expect("valid regex"));
src/cmds/dotnet/binlog.rs:111:static SENSITIVE_ENV_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/dotnet/binlog.rs:112: let keys = SENSITIVE_ENV_VARS
src/cmds/dotnet/binlog.rs:113: .iter()
src/cmds/dotnet/binlog.rs:114: .map(|key| regex::escape(key))
src/cmds/dotnet/binlog.rs:115: .collect::<Vec<_>>()
src/cmds/dotnet/binlog.rs:116: .join("|");
src/cmds/dotnet/binlog.rs:117: Regex::new(&format!(
src/cmds/dotnet/binlog.rs:118: r"(?P<prefix>\b(?:{})\s*(?:=|:)\s*)(?P<value>[^\s;]+)",
src/cmds/dotnet/binlog.rs:119: keys
src/cmds/dotnet/binlog.rs:120: ))
src/cmds/dotnet/binlog.rs:121: .expect("valid regex")
src/cmds/dotnet/binlog.rs:122:});
src/cmds/jvm/mvn_cmd.rs:34:static RUNNING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Running ").unwrap());
src/cmds/jvm/mvn_cmd.rs:45: LazyLock::new(|| Regex::new(r"^\[INFO\] Running \S+\s*$").unwrap());
src/cmds/jvm/mvn_cmd.rs:55:static CLOSE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/mvn_cmd.rs:56: Regex::new(
src/cmds/jvm/mvn_cmd.rs:57: r"^\[(?:INFO|ERROR|WARNING)\] Tests run: \d+, Failures: (\d+), Errors: (\d+), Skipped: \d+, Time elapsed: [^ ]+ s(?:\s+<<<\s*(?:FAILURE|ERROR)!)?\s+--?\s+in (.+)$"
src/cmds/jvm/mvn_cmd.rs:58: ).unwrap()
src/cmds/jvm/mvn_cmd.rs:59:});
src/cmds/jvm/mvn_cmd.rs:63: LazyLock::new(|| Regex::new(r"^\[(?:INFO|ERROR)\] BUILD (?:SUCCESS|FAILURE)$").unwrap());
src/cmds/jvm/mvn_cmd.rs:66:static RESULTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[INFO\] Results:\s*$").unwrap());
src/cmds/jvm/mvn_cmd.rs:69:static AGG: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/mvn_cmd.rs:70: Regex::new(r"^\[(?:INFO|ERROR)\] Tests run: \d+, Failures: \d+, Errors: \d+, Skipped: \d+\s*$")
src/cmds/jvm/mvn_cmd.rs:71: .unwrap()
src/cmds/jvm/mvn_cmd.rs:72:});
src/cmds/jvm/mvn_cmd.rs:76: LazyLock::new(|| Regex::new(r"^\[INFO\] --- .* @ .* ---$").unwrap());
src/cmds/jvm/mvn_cmd.rs:109:static TEST_PLUGIN_BANNER: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/jvm/mvn_cmd.rs:110: Regex::new(r"^\[INFO\] --- (?:maven-)?(surefire|failsafe)(?:-plugin)?:\S+ \([^)]*\) @ .* ---$")
src/cmds/jvm/mvn_cmd.rs:111: .unwrap()
src/cmds/jvm/mvn_cmd.rs:112:});
src/cmds/jvm/mvn_cmd.rs:125: LazyLock::new(|| Regex::new(r"^\[INFO\] Building .*\[\d+/\d+\]\s*$").unwrap());
src/cmds/jvm/mvn_cmd.rs:129: LazyLock::new(|| Regex::new(r"^\[INFO\] -+< .+ >-+$").unwrap());
src/cmds/jvm/mvn_cmd.rs:134: LazyLock::new(|| Regex::new(r"^\[INFO\] Reactor Summary for ").unwrap());
src/cmds/jvm/mvn_cmd.rs:138: LazyLock::new(|| Regex::new(r"/[^:]+\.java:\[\d+,\d+\]").unwrap());
src/cmds/php/phpt_cmd.rs:163: static STATUS_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/php/phpt_cmd.rs:164: // Matches a status line. Anchor: either start-of-line ("FAIL desc [x.phpt]")
src/cmds/php/phpt_cmd.rs:165: // or immediately after the test bracket ("TEST N/M [x.phpt]PASS desc [x.phpt]").
src/cmds/php/phpt_cmd.rs:166: // We only accept the token after `]` or at line start so that prose like
src/cmds/php/phpt_cmd.rs:167: // "FAILED TEST SUMMARY" does not match.
src/cmds/php/phpt_cmd.rs:168: Regex::new(
src/cmds/php/phpt_cmd.rs:169: r"(?:^|\])(PASS|FAIL|SKIP|BORK|WARN|XLEAK|LEAK|XFAIL)\s+(.*?)\s*\[([^\[\]]+\.phpt)\]",
src/cmds/php/phpt_cmd.rs:170: )
src/cmds/php/phpt_cmd.rs:171: .unwrap()
src/cmds/php/phpt_cmd.rs:172: });
src/cmds/php/phpt_cmd.rs:173: static STAT_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/php/phpt_cmd.rs:174: Regex::new(
src/cmds/php/phpt_cmd.rs:175: r"^\s*(Tests passed|Tests failed|Tests skipped|Tests warned|Expected fail|Expected leak|Tests leaked|Tests borked)\s*:\s*(\d+)",
src/cmds/php/phpt_cmd.rs:176: )
src/cmds/php/phpt_cmd.rs:177: .unwrap()
src/cmds/php/phpt_cmd.rs:178: });
src/cmds/php/phpt_cmd.rs:180: LazyLock::new(|| Regex::new(r"^\s*Number of tests\s*:\s*(\d+)").unwrap());
src/cmds/php/phpt_cmd.rs:182: LazyLock::new(|| Regex::new(r"^\s*Time taken\s*:\s*([0-9.]+)").unwrap());
src/cmds/cloud/aws_cmd.rs:1327: LazyLock::new(|| Regex::new(r"^(upload|download|delete|copy|move):").unwrap());
src/cmds/js/tsc_cmd.rs:22:static TSC_ERROR: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/js/tsc_cmd.rs:23: Regex::new(r"^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
src/cmds/js/tsc_cmd.rs:24:});
src/cmds/js/tsc_cmd.rs:26:static TSC_PRETTY_ERROR: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/js/tsc_cmd.rs:27: Regex::new(r"^(.+?):(\d+):(\d+)\s+-\s+(error|warning)\s+(TS\d+):\s+(.+)$").unwrap()
src/cmds/js/tsc_cmd.rs:28:});
src/cmds/js/tsc_cmd.rs:30: LazyLock::new(|| Regex::new(r"^(error|warning)\s+(TS\d+):\s+(.+)$").unwrap());
src/core/utils.rs:54: LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*[a-zA-Z]").unwrap());
src/cmds/python/uv_cmd.rs:20: LazyLock::new(|| Regex::new(r#"^\s*File ".*", line \d+.*$"#).unwrap());
src/cmds/python/uv_cmd.rs:22: LazyLock::new(|| Regex::new(r"^\s*[A-Za-z_][A-Za-z0-9_.]*(?:Error|Exception):").unwrap());
src/cmds/python/uv_cmd.rs:24: LazyLock::new(|| Regex::new(r"^\s*at .+:\d+:\d+.*$").unwrap());
src/cmds/python/uv_cmd.rs:25:static ERROR_START_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
src/cmds/python/uv_cmd.rs:26: vec![
src/cmds/python/uv_cmd.rs:27: Regex::new(r"(?i)\berror\b").unwrap(),
src/cmds/python/uv_cmd.rs:28: Regex::new(r"(?i)\bfailed\b").unwrap(),
src/cmds/python/uv_cmd.rs:29: Regex::new(r"(?i)\bfailure\b").unwrap(),
src/cmds/python/uv_cmd.rs:30: Regex::new(r"(?i)\bexception\b").unwrap(),
src/cmds/python/uv_cmd.rs:31: Regex::new(r"(?i)\bpanic\b").unwrap(),
src/cmds/python/uv_cmd.rs:32: Regex::new(r"(?i)\bwarn(?:ing)?\b").unwrap(),
src/cmds/python/uv_cmd.rs:33: Regex::new(r"(?i)\bassert(?:ion)?\b").unwrap(),
src/cmds/python/uv_cmd.rs:34: Regex::new(r"^\s*FAILED\b").unwrap(),
src/cmds/python/uv_cmd.rs:35: Regex::new(r"^\s*ERROR\b").unwrap(),
src/cmds/python/uv_cmd.rs:36: Regex::new(r"^\s*E\s+").unwrap(),
src/cmds/python/uv_cmd.rs:37: Regex::new(r"^\s*Caused by:").unwrap(),
src/cmds/python/uv_cmd.rs:38: Regex::new(r"^\s*note:").unwrap(),
src/cmds/python/uv_cmd.rs:39: Regex::new(r"^\s*help:").unwrap(),
src/cmds/python/uv_cmd.rs:40: ]
src/cmds/python/uv_cmd.rs:41:});
src/core/filter.rs:158:static MULTIPLE_BLANK_LINES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
src/core/filter.rs:233: LazyLock::new(|| Regex::new(r"^(use |import |from |require\(|#include)").unwrap());
src/core/filter.rs:234:static FUNC_SIGNATURE: LazyLock<Regex> = LazyLock::new(|| {
src/core/filter.rs:235: Regex::new(
src/core/filter.rs:236: r"^(pub\s+)?(async\s+)?(fn|def|function|func|class|struct|enum|trait|interface|type)\s+\w+",
src/core/filter.rs:237: )
src/core/filter.rs:238: .unwrap()
src/core/filter.rs:239:});
src/cmds/rust/cargo_cmd.rs:1050: static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
src/cmds/rust/cargo_cmd.rs:1051: regex::Regex::new(
src/cmds/rust/cargo_cmd.rs:1052: r"test result: (\w+)\.\s+(\d+) passed;\s+(\d+) failed;\s+(\d+) ignored;\s+(\d+) measured;\s+(\d+) filtered out(?:;\s+finished in ([\d.]+)s)?"
src/cmds/rust/cargo_cmd.rs:1053: ).unwrap()
src/cmds/rust/cargo_cmd.rs:1054: });
src/cmds/python/mypy_cmd.rs:57: static MYPY_DIAG: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/python/mypy_cmd.rs:58: Regex::new(r"^(.+?):(\d+)(?::\d+)?: (error|warning|note): (.+?)(?:\s+\[(.+)\])?$").unwrap()
src/cmds/python/mypy_cmd.rs:59: });
src/cmds/scala/sbt_cmd.rs:10:static TEST_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/scala/sbt_cmd.rs:11: Regex::new(
src/cmds/scala/sbt_cmd.rs:12: r"Tests: succeeded (\d+), failed (\d+), canceled (\d+), ignored (\d+), pending (\d+)",
src/cmds/scala/sbt_cmd.rs:13: )
src/cmds/scala/sbt_cmd.rs:14: .unwrap()
src/cmds/scala/sbt_cmd.rs:15:});
src/cmds/scala/sbt_cmd.rs:20:static MUNIT_SUMMARY_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/scala/sbt_cmd.rs:21: Regex::new(r"^\[info\] (?:Passed|Failed): Total \d+, Failed (\d+), Errors (\d+), Passed (\d+)")
src/cmds/scala/sbt_cmd.rs:22: .unwrap()
src/cmds/scala/sbt_cmd.rs:23:});
src/cmds/scala/sbt_cmd.rs:28: LazyLock::new(|| Regex::new(r"Suites: completed (\d+), aborted (\d+)").unwrap());
src/cmds/scala/sbt_cmd.rs:32: LazyLock::new(|| Regex::new(r"Run completed in (\d+) seconds?").unwrap());
src/cmds/scala/sbt_cmd.rs:36: LazyLock::new(|| Regex::new(r"\[info\] Compiling (\d+) Scala source").unwrap());
src/cmds/scala/sbt_cmd.rs:40: LazyLock::new(|| Regex::new(r"\[success\] Total time: (\d+) s").unwrap());
src/cmds/scala/sbt_cmd.rs:43:static ERROR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[error\]").unwrap());
src/cmds/scala/sbt_cmd.rs:46:static NOISE_RE: LazyLock<Regex> = LazyLock::new(|| {
src/cmds/scala/sbt_cmd.rs:47: Regex::new(
src/cmds/scala/sbt_cmd.rs:48: r"^\[info\] (welcome to sbt|loading |set current project|Updating |Resolved |Fetching |downloading |Done )"
src/cmds/scala/sbt_cmd.rs:49: ).unwrap()
src/cmds/scala/sbt_cmd.rs:50:});
src/core/toml_filter.rs:399:static REGISTRY: LazyLock<TomlFilterRegistry> = LazyLock::new(TomlFilterRegistry::load);
src/core/toml_filter.rs:422:static MATCH_SET: LazyLock<RegexSet> = LazyLock::new(build_match_set);
+139
View File
@@ -0,0 +1,139 @@
//! `gh pr checks` exits non-zero as a normal result: 1 when a check failed, 8 while
//! checks are still pending. Its stdout is complete and valid in both cases, so
//! skipping the filter there dropped the whole table on the user exactly when they
//! were asking why CI was red. These pin that the summary survives a non-zero exit
//! without swallowing the exit code, the diagnostics on stderr, or a check row.
#![cfg(unix)]
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};
/// Writes an executable `name` in `dir` that runs `body`.
fn fake_tool(dir: &Path, name: &str, body: &str) {
let path = dir.join(name);
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
}
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
let path = format!(
"{}:{}",
dir.display(),
std::env::var("PATH").unwrap_or_default()
);
Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.env("PATH", path)
.output()
.expect("run rtk")
}
/// A `gh` whose `pr checks` prints `table` and exits `code`, the way it does when
/// checks failed (1) or are still running (8).
fn fake_gh(dir: &Path, table: &str, code: i32) {
let path = dir.join("checks.txt");
fs::write(&path, table).expect("write table");
fake_tool(dir, "gh", &format!("cat {}\nexit {}", path.display(), code));
}
/// Rows as `gh` 2.46 prints them: tab-separated name, state, elapsed, url, description.
const RED_TABLE: &str = "doc review\tfail\t13s\thttps://example.test/job/1\t\n\
fmt\tfail\t7s\thttps://example.test/job/2\t\n\
Analyze (rust)\tpass\t4m17s\thttps://example.test/job/3\t\n\
check\tpass\t5s\thttps://example.test/job/4\t\n";
#[test]
fn failing_checks_are_summarised_not_dumped_raw() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(dir.path(), RED_TABLE, 1);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("CI Checks Summary:"),
"filter must run on a non-zero exit, got:\n{stdout}"
);
assert!(stdout.contains("Passed: 2"), "got:\n{stdout}");
assert!(stdout.contains("Failed: 2"), "got:\n{stdout}");
assert!(
stdout.contains("doc review") && stdout.contains("fmt"),
"the failed checks are the reason the user ran this, got:\n{stdout}"
);
}
#[test]
fn a_red_run_still_propagates_the_exit_code() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(dir.path(), RED_TABLE, 1);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
assert_eq!(out.status.code(), Some(1), "gh's exit code must survive");
}
#[test]
fn pending_checks_are_counted_and_exit_eight_survives() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(
dir.path(),
"test (ubuntu)\tpending\t0\thttps://example.test/job/5\t\n\
test (macos)\tpending\t0\thttps://example.test/job/6\t\n\
test (windows)\tpending\t0\thttps://example.test/job/7\t\n\
clippy\tpass\t31s\thttps://example.test/job/8\t\n",
8,
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Pending: 3"), "got:\n{stdout}");
assert_eq!(out.status.code(), Some(8), "gh exits 8 while checks pend");
}
#[test]
fn a_cancelled_run_does_not_read_as_nothing_wrong() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(
dir.path(),
"build\tcancelled\t45s\thttps://example.test/job/1\t\n\
test (ubuntu)\tcancelled\t44s\thttps://example.test/job/2\t\n\
Security Scan\tskipping\t0\thttps://example.test/job/3\t\n",
1,
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("Skipped/cancelled: 3"),
"a cancelled run must not summarise to all zeros, got:\n{stdout}"
);
assert_eq!(out.status.code(), Some(1));
}
#[test]
fn an_error_with_empty_stdout_does_not_become_an_all_zero_summary() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(
dir.path(),
"gh",
"echo 'GraphQL: Could not resolve to a Repository' >&2\nexit 1",
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stdout.contains("Passed: 0"),
"a failed lookup must not read as a PR with zero checks, got:\n{stdout}"
);
assert!(
stderr.contains("Could not resolve to a Repository"),
"the real diagnostic must reach the user, got:\n{stderr}"
);
assert_eq!(out.status.code(), Some(1));
}
+281 -3
View File
@@ -212,6 +212,141 @@ fn git_log_dash_p_pathspec_after_double_dash_is_not_patch_flag() {
);
}
#[test]
fn git_show_dash_dash_stat_pathspec_after_double_dash_is_not_stat_flag() {
// Regression: `rtk git show -- --stat` must not be misread as a request for the real
// `--stat` summary flag. Before restore_double_dash + arg_tokenizer, run_show's
// wants_stat_only check was a raw `arg == "--stat"` scan with no `--`-boundary awareness, so
// a file literally named "--stat" after the boundary was wrongly treated as the flag and
// sent down the raw-passthrough path instead of RTK's own compacted-diff path.
let dir = init_git_repo();
std::fs::write(dir.path().join("--stat"), "not a summary flag\n").expect("write --stat file");
git_in_dir(dir.path(), &["add", "--", "--stat"]);
git_in_dir(
dir.path(),
&["commit", "-q", "-m", "add dash-dash-stat file"],
);
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "show", "--", "--stat"]);
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
assert!(
!stdout.contains("diff --git"),
"-- --stat should stay on RTK's compacted-diff path, not raw passthrough: {stdout:?}"
);
assert!(
stdout.contains("--stat") && stdout.contains("+1"),
"expected RTK's compacted diff summary for the --stat file: {stdout:?}"
);
}
#[test]
fn git_diff_dash_dash_stat_pathspec_after_double_dash_is_not_stat_flag() {
// Regression: `rtk git diff -- --stat` must not be misread as a request for the real
// `--stat` diffstat-only flag. Before this fix, run_diff's wants_stat check was a raw
// `arg == "--stat"` scan with no `--`-boundary awareness, so a file literally named "--stat"
// after the boundary was wrongly treated as the flag and sent down the raw-passthrough path
// (plain diffstat output) instead of RTK's own stat+compacted-diff path.
let dir = init_git_repo();
std::fs::write(dir.path().join("--stat"), "line one\n").expect("write --stat file");
git_in_dir(dir.path(), &["add", "--", "--stat"]);
git_in_dir(
dir.path(),
&["commit", "-q", "-m", "add dash-dash-stat file"],
);
std::fs::write(dir.path().join("--stat"), "line one\nline two\n").expect("modify --stat file");
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "--", "--stat"]);
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
assert!(
!stdout.contains("diff --git"),
"-- --stat should stay on RTK's stat+compacted-diff path, not raw passthrough: {stdout:?}"
);
assert!(
stdout.contains("--stat | 1 +") && stdout.contains("Changes:"),
"expected RTK's stat-summary-plus-compacted-diff output for the modified --stat file: {stdout:?}"
);
}
#[test]
fn git_diff_name_only_passes_through_raw() {
// Regression: run_diff's wants_stat check only recognized --stat/--numstat/--shortstat, a
// narrower list than requests_raw_diff_shape (which run_log already used, covering
// --name-only/--name-status/--raw/--dirstat/--summary/-p/-u too). `--name-only` fell through
// to RTK's default stat+compacted-diff path instead of a raw passthrough of git's own
// name-only output.
let dir = init_git_repo();
std::fs::write(dir.path().join("file.txt"), "one\n").expect("write file");
git_in_dir(dir.path(), &["add", "file.txt"]);
git_in_dir(dir.path(), &["commit", "-q", "-m", "add file"]);
std::fs::write(dir.path().join("file.txt"), "one\ntwo\n").expect("modify file");
let (stdout, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "--name-only"]);
assert_eq!(code, Some(0), "rtk stderr: {stderr}");
assert_eq!(
stdout.trim(),
"file.txt",
"--name-only should pass through as git's own bare filename list: {stdout:?}"
);
}
#[test]
fn git_branch_dash_prefixed_name_after_double_dash_attempts_creation_not_a_silent_list() {
// Regression: `rtk git branch -- -weird` must be classified as a branch-creation attempt
// (and let real git's own ref-name validation reject it), not silently fall through to list
// mode as if no branch name were given. Before restore_double_dash + arg_tokenizer,
// run_branch's has_positional_arg check was a raw `!a.starts_with('-')` scan with no
// `--`-boundary awareness, so a branch name starting with '-' after the separator was
// misclassified as a flag: has_positional_arg came back false, and (with no list flag
// either) rtk silently ran `git branch -a --no-color -- -weird-branch` -- a harmless, empty,
// exit-0 *list* filtered on a pattern that matches nothing, giving no indication the
// requested branch was never created. A real branch named "-weird-branch" is impossible
// (git's own check-ref-format forbids a leading '-'), so the observable signal here is that
// rtk actually attempts the creation and surfaces git's real rejection, instead of quietly
// doing nothing and exiting 0.
let dir = init_git_repo();
let (stdout, stderr, code) =
rtk_output_in_dir(dir.path(), &["git", "branch", "--", "-weird-branch"]);
assert_ne!(
code,
Some(0),
"a creation attempt for an invalid ref name must fail, not silently succeed as an empty list: stdout={stdout:?} stderr={stderr:?}"
);
assert!(
stderr.contains("-weird-branch"),
"expected git's own rejection to mention the attempted branch name: {stderr:?}"
);
}
#[test]
fn git_log_malformed_digit_run_propagates_real_git_error() {
// "-5x" isn't a valid git log limit; real git rejects it outright ("fatal: '5x': not an
// integer", verified against git 2.51). run_log's internal limit-parsing for this
// malformed input differs before/after arg_tokenizer (5 vs the old fallback of 10), but
// that's never observable here: run_log bails out on the real git failure before ever
// reaching the formatting code that would use it.
let dir = init_git_repo();
let raw = Command::new("git")
.args(["log", "-5x"])
.current_dir(dir.path())
.output()
.expect("spawn raw git log");
assert!(!raw.status.success(), "expected real git to reject -5x");
let (_, rtk_stderr, rtk_code) = rtk_output_in_dir(dir.path(), &["git", "log", "-5x"]);
assert_eq!(rtk_code, raw.status.code());
assert!(
rtk_stderr.contains("not an integer"),
"rtk should surface git's own error verbatim: {rtk_stderr:?}"
);
}
#[test]
fn git_stash_show_no_stash_emits_empty_and_propagates_failure() {
// Regression: previously printed "Empty stash" and returned Ok(0), masking
@@ -251,13 +386,39 @@ fn git_checkout_new_branch_emits_compact_ok() {
}
#[test]
fn git_checkout_reset_branch_does_not_claim_new_branch() {
fn git_checkout_dash_b_capital_reports_what_git_actually_did() {
let dir = init_git_repo();
// `-B` creates *or* resets, and only git knows which. Reading the branch name out of the
// args and returning early claimed neither, so a created branch lost its `(new)` marker.
//
// rtk_output_in_dir pins LC_ALL=C, which is what makes the English scan land. Under
// another locale this degrades to the args fallback ("ok feature/test") rather than
// claiming a marker it cannot verify -- weaker, never wrong -- so `(new)` is asserted
// here only because the locale is pinned.
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-B", "feature/test"]);
assert_eq!(code, Some(0));
assert_eq!(out.trim(), "ok feature/test");
assert_eq!(
out.trim(),
"ok feature/test (new)",
"git: Switched to a new branch"
);
// Reset of a branch that already exists: not new, and the args fallback names it.
git_in_dir(dir.path(), &["checkout", "-q", "main"]);
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-B", "feature/test"]);
assert_eq!(code, Some(0));
assert_eq!(
out.trim(),
"ok feature/test",
"git: Switched to and reset branch -- matches no scan prefix, so the args name it"
);
// Glued spelling routes identically; the string scans it replaced could not read it.
git_in_dir(dir.path(), &["checkout", "-q", "main"]);
let (out, code) = rtk_in_dir(dir.path(), &["git", "checkout", "-Bfeature/glued"]);
assert_eq!(code, Some(0));
assert_eq!(out.trim(), "ok feature/glued (new)");
}
#[test]
@@ -321,3 +482,120 @@ fn git_checkout_dirty_tree_error_keeps_file_list() {
"dirty checkout failure should keep abort line: {combined:?}"
);
}
/// A repo with one commit and one working-tree change, for the diff/show routing tests below.
fn repo_with_a_change() -> tempfile::TempDir {
let dir = init_git_repo();
std::fs::write(dir.path().join("a.txt"), "l1\nl2\nl3\n").expect("write");
git_in_dir(dir.path(), &["add", "-A"]);
git_in_dir(dir.path(), &["commit", "-qm", "c1"]);
std::fs::write(dir.path().join("a.txt"), "l1\nl2 CHANGED\nl3\n").expect("write");
dir
}
#[test]
fn git_diff_reports_the_error_git_gives_for_what_was_typed() {
// RTK also runs a stat probe with the patch-shape flags stripped, so that probe answers a
// different command: git rejects `-Uabc` (129) while the stripped probe got as far as the
// unknown ref and said `ambiguous argument` (128). A probe must never be what reports.
let dir = repo_with_a_change();
let (_, stderr, code) =
rtk_output_in_dir(dir.path(), &["git", "diff", "-Uabc", "nonexistent-ref"]);
assert_eq!(code, Some(129), "git's own code for the first bad flag");
assert!(
stderr.contains("--unified"),
"expected git's --unified complaint, got: {stderr:?}"
);
// Each alone still reports its own error.
let (_, _, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "-Uabc"]);
assert_eq!(code, Some(129));
let (_, _, code) = rtk_output_in_dir(dir.path(), &["git", "diff", "nonexistent-ref"]);
assert_eq!(code, Some(128));
}
#[test]
fn git_diff_keeps_the_body_when_git_colours_it() {
// Colour puts an escape at column 0, where the compaction looks for `diff --git` and `@@`,
// so the body silently came back empty. RTK renders its own output, so the colour was
// never going to survive compaction and is stripped before parsing.
let dir = repo_with_a_change();
for args in [
&["git", "diff", "--color"][..],
&["git", "diff", "--color", "--unified=0"][..],
&["git", "diff", "--color=always"][..],
] {
let (stdout, _, code) = rtk_output_in_dir(dir.path(), args);
assert_eq!(code, Some(0), "{args:?}");
assert!(
stdout.contains("CHANGED"),
"{args:?} lost the body: {stdout:?}"
);
}
// The same escape arrives from config, where no argument inspection could have seen it.
git_in_dir(dir.path(), &["config", "color.ui", "always"]);
let (stdout, _, _) = rtk_output_in_dir(dir.path(), &["git", "diff"]);
assert!(
stdout.contains("CHANGED"),
"color.ui=always lost the body: {stdout:?}"
);
}
#[test]
fn git_log_announces_its_limit_only_when_the_limit_took_something() {
// The notice exists because that path streams and has no footer to notice missing commits
// from. It must not claim a truncation that did not happen, nor precede a command git
// rejects outright.
let dir = repo_with_a_change();
git_in_dir(dir.path(), &["add", "-A"]);
git_in_dir(dir.path(), &["commit", "-qm", "c2"]);
let (_, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "log", "--stat"]);
assert_eq!(code, Some(0));
assert!(
!stderr.contains("[rtk]"),
"two commits, limit of ten: nothing was truncated, but got: {stderr:?}"
);
let (_, stderr, code) = rtk_output_in_dir(dir.path(), &["git", "log", "-pq"]);
assert_ne!(code, Some(0), "git rejects -q for log");
assert!(
!stderr.contains("[rtk]"),
"no notice ahead of a command git refuses: {stderr:?}"
);
}
#[test]
fn git_show_quiet_loses_to_a_patch_request_from_either_side() {
// git 2.53: `-s`/`--no-patch` fold in order against a patch request, `--quiet` never wins
// over one. Modelling all three the same way dropped a patch that was asked for.
let dir = repo_with_a_change();
git_in_dir(dir.path(), &["add", "-A"]);
git_in_dir(dir.path(), &["commit", "-qm", "c2"]);
for args in [
&["git", "show", "--quiet", "-p"][..],
&["git", "show", "-p", "--quiet"][..],
&["git", "show", "-s", "-p"][..],
] {
let (stdout, _, _) = rtk_output_in_dir(dir.path(), args);
assert!(
stdout.contains("CHANGED"),
"{args:?} should print the body: {stdout:?}"
);
}
for args in [
&["git", "show", "--quiet"][..],
&["git", "show", "-s"][..],
&["git", "show", "-p", "-s"][..],
] {
let (stdout, _, _) = rtk_output_in_dir(dir.path(), args);
assert!(
!stdout.contains("CHANGED"),
"{args:?} should suppress the body: {stdout:?}"
);
}
}
+79
View File
@@ -0,0 +1,79 @@
//! The "hook missing/outdated" reminder is a once-a-day nudge, so where it is
//! spent matters: a command the user ran to inspect or install the hook would
//! both duplicate that command's own reporting and burn the daily marker,
//! leaving the next filtered command silent.
//!
//! Unix only: the check resolves the Claude directory through the home
//! directory, and only Unix takes that from `$HOME`.
#![cfg(unix)]
use std::path::Path;
use std::process::Command;
const REMINDER: &str = "No hook installed";
/// Runs `rtk <args>` against a home directory whose Claude config directory
/// exists but registers no hook, and returns stderr.
fn run(home: &Path, args: &[&str]) -> String {
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.env("HOME", home)
.env("RTK_DB_PATH", home.join("rtk.db"))
.output()
.expect("run rtk");
String::from_utf8_lossy(&out.stderr).into_owned()
}
fn fresh_home() -> tempfile::TempDir {
let home = tempfile::tempdir().expect("tempdir");
// Absent, the status check reports "not applicable"; present-but-empty is
// what makes a missing hook detectable.
std::fs::create_dir_all(home.path().join(".claude")).expect("claude dir");
home
}
#[test]
fn commands_that_report_hook_state_do_not_repeat_the_reminder() {
for args in [
vec!["init", "-g"],
vec!["verify"],
vec!["verify", "--filter", "cargo"],
vec!["gain"],
] {
let home = fresh_home();
let stderr = run(home.path(), &args);
assert!(
!stderr.contains(&format!("[rtk] /!\\ {REMINDER}")),
"rtk {} must not print the daily reminder: {stderr}",
args.join(" ")
);
}
}
#[test]
fn filtered_commands_still_get_the_reminder() {
for args in [vec!["ls"], vec!["git", "status"]] {
let home = fresh_home();
let stderr = run(home.path(), &args);
assert!(
stderr.contains(REMINDER),
"rtk {} must still warn: {stderr}",
args.join(" ")
);
}
}
#[test]
fn a_meta_command_leaves_the_daily_reminder_for_the_next_filtered_command() {
// The regression this guards: `maybe_warn` touches the once-a-day marker,
// so warning on a meta command would spend the reminder there and leave
// the next filtered command — the one that should have been hooked —
// silent for 24 hours.
let home = fresh_home();
run(home.path(), &["verify", "--filter", "cargo"]);
let stderr = run(home.path(), &["ls"]);
assert!(
stderr.contains(REMINDER),
"the reminder must survive a preceding meta command: {stderr}"
);
}
+175
View File
@@ -0,0 +1,175 @@
use std::fs;
use std::io::Write;
use std::process::{Command, Output, Stdio};
fn read_stdin(input: &[u8], args: &[&str]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(["read", "-"])
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("run rtk read from stdin");
child
.stdin
.take()
.expect("piped stdin")
.write_all(input)
.expect("write stdin");
child.wait_with_output().expect("wait for rtk read")
}
#[test]
fn read_windows_preserve_non_utf8_files() {
let dir = tempfile::tempdir().expect("create test directory");
let file = dir.path().join("binary.log");
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
for (flag, expected) in [
("--head-lines", b"\xff\xfe bad\nline2\n".as_slice()),
("--tail-lines", b"line2\nline3\n".as_slice()),
] {
let output = Command::new(env!("CARGO_BIN_EXE_rtk"))
.arg("read")
.arg(&file)
.args([flag, "2"])
.output()
.expect("run rtk read");
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
assert_eq!(output.stdout, expected, "{flag}");
}
}
#[test]
fn read_windows_preserve_binary_boundaries_for_files_and_stdin() {
let dir = tempfile::tempdir().expect("create test directory");
let file = dir.path().join("binary.log");
for input in [
b"\xff\r\nvalid\n\0\xfe".as_slice(),
b"\xff\r\nvalid\n\0\xfe\n".as_slice(),
] {
fs::write(&file, input).expect("write binary file");
let last = if input.ends_with(b"\n") {
b"\0\xfe\n".as_slice()
} else {
b"\0\xfe".as_slice()
};
for (flag, count, expected) in [
("--head-lines", "0", b"".as_slice()),
("--tail-lines", "0", b"".as_slice()),
("--head-lines", "1", b"\xff\r\n".as_slice()),
("--tail-lines", "1", last),
("--head-lines", "99", input),
("--tail-lines", "99", input),
] {
let from_file = Command::new(env!("CARGO_BIN_EXE_rtk"))
.arg("read")
.arg(&file)
.args([flag, count])
.output()
.expect("run rtk read");
let from_stdin = read_stdin(input, &[flag, count]);
for output in [from_file, from_stdin] {
assert!(
output.status.success(),
"{flag} {count}: {:?}",
output.stderr
);
assert_eq!(output.stdout, expected, "{flag} {count}");
}
}
}
}
#[test]
fn read_windows_accept_invalid_bytes_outside_the_selected_window() {
for (input, flag) in [
(b"valid\n\xff\n".as_slice(), "--head-lines"),
(b"\xff\nvalid\n".as_slice(), "--tail-lines"),
] {
let output = read_stdin(input, &[flag, "1"]);
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
assert_eq!(output.stdout, b"valid\n");
}
}
#[test]
fn read_windows_still_apply_text_filtering_and_line_numbers() {
let input = b"// comment\nfn alpha() {}\nfn beta() {}\nfn gamma() {}\n";
for (args, expected) in [
(
["--head-lines", "1", "--level", "minimal"].as_slice(),
"fn alpha() {}\n",
),
(
["--tail-lines", "1", "--level", "minimal"].as_slice(),
"fn gamma() {}",
),
(
["--head-lines", "1", "--line-numbers"].as_slice(),
"1 │ // comment\n",
),
(
["--tail-lines", "1", "--line-numbers"].as_slice(),
"1 │ fn gamma() {}\n",
),
] {
let output = read_stdin(input, args);
assert!(output.status.success(), "{args:?}: {:?}", output.stderr);
assert_eq!(output.stdout, expected.as_bytes(), "{args:?}");
}
}
#[cfg(unix)]
#[test]
fn rewritten_head_spellings_match_native_on_non_utf8_files() {
let dir = tempfile::tempdir().expect("create test directory");
let claude_dir = dir.path().join(".claude");
fs::create_dir(&claude_dir).expect("create isolated Claude config directory");
let config_dir = dir.path().join("config");
fs::create_dir(&config_dir).expect("create isolated rtk config directory");
let file = dir.path().join("binary.log");
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
for flags in ["-2", "-n 2", "--lines 2", "--lines=2", ""] {
let command = format!("head {flags} {}", file.display());
let rewrite = Command::new(env!("CARGO_BIN_EXE_rtk"))
.current_dir(dir.path())
.env("CLAUDE_CONFIG_DIR", &claude_dir)
.env("XDG_CONFIG_HOME", &config_dir)
.args(["rewrite", &command])
.output()
.expect("rewrite head command");
assert_eq!(
rewrite.status.code(),
Some(3),
"{command}: {:?}",
rewrite.stderr
);
let rewritten = String::from_utf8(rewrite.stdout).expect("UTF-8 command");
let count = if flags.is_empty() { "10" } else { "2" };
assert_eq!(
rewritten.trim(),
format!("rtk read {} --head-lines {count}", file.display())
);
let actual = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(
rewritten
.trim()
.strip_prefix("rtk ")
.expect("rtk rewrite prefix")
.split_whitespace(),
)
.output()
.expect("execute rewritten head");
let native = Command::new("head")
.args(flags.split_whitespace())
.arg(&file)
.output()
.expect("run native head");
assert!(native.status.success(), "{command}: {:?}", native.stderr);
assert_eq!(actual.status.code(), native.status.code(), "{command}");
assert_eq!(actual.stdout, native.stdout, "{command}");
}
}
+105
View File
@@ -0,0 +1,105 @@
#![cfg(unix)]
//! Which stdin the engines actually read. These run in CI as integration tests rather than
//! `#[ignore]`d unit tests: `CARGO_BIN_EXE_rtk` guarantees a built binary, so the fix they
//! cover is exercised by `cargo test --all` instead of only by a flag nobody passes.
use std::process::{Command, Stdio};
fn rtk() -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_rtk"));
cmd.env("LC_ALL", "C");
cmd
}
/// Each test guards on the engine it actually drives -- guarding an rg test on grep (or the
/// reverse) turns a missing tool into a silent pass rather than a skip.
fn engine_available(engine: &str) -> bool {
Command::new(engine)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
#[test]
fn rg_shows_filenames_when_stdin_is_not_a_pipe() {
if !engine_available("rg") {
return;
}
// `rtk rg -z foo < /dev/null` in a multi-file dir used to drop filenames: stdin being a
// non-terminal, non-pipe redirect was misread as "the engine reads stdin," routing into the
// streaming path, which can't discover "multiple files" the way the buffered path does.
// Real rg searches the cwd here, not stdin.
let dir = tempfile::tempdir().expect("test setup");
std::fs::write(dir.path().join("a.txt"), "foo one\n").expect("test setup");
std::fs::write(dir.path().join("b.txt"), "foo two\n").expect("test setup");
let output = rtk()
.args(["rg", "-z", "foo"])
.current_dir(dir.path())
.stdin(Stdio::null())
.output()
.expect("failed to run rtk rg");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("a.txt"), "filename missing: {stdout}");
assert!(stdout.contains("b.txt"), "filename missing: {stdout}");
}
#[test]
fn a_single_matching_file_still_gets_its_name() {
if !engine_available("rg") {
return;
}
// The engine walked the cwd itself, so the filename is the only way to place the match --
// real rg prints it even when exactly one file matched.
let dir = tempfile::tempdir().expect("test setup");
std::fs::write(dir.path().join("only.txt"), "foo here\n").expect("test setup");
std::fs::write(dir.path().join("other.txt"), "nothing\n").expect("test setup");
let output = rtk()
.args(["rg", "foo"])
.current_dir(dir.path())
.stdin(Stdio::null())
.output()
.expect("failed to run rtk rg");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("only.txt"), "filename missing: {stdout}");
}
#[test]
fn both_engines_read_a_redirected_file_on_stdin() {
// A regular file on stdin *is* read by both engines (rg's own is_readable_stdin counts
// files and sockets, not just FIFOs), so the search must return that file's match rather
// than the cwd's.
let dir = tempfile::tempdir().expect("test setup");
std::fs::write(dir.path().join("a.txt"), "foo from the cwd\n").expect("test setup");
// The fixture lives outside the searched directory: inside it, an engine that ignored
// stdin and walked the cwd would still print "foo from stdin" and the test would pass.
let elsewhere = tempfile::tempdir().expect("test setup");
let piped = elsewhere.path().join("piped.log");
std::fs::write(&piped, "foo from stdin\n").expect("test setup");
for engine in ["grep", "rg"] {
if !engine_available(engine) {
continue;
}
let output = rtk()
.args([engine, "foo"])
.current_dir(dir.path())
.stdin(std::fs::File::open(&piped).expect("test setup"))
.output()
.expect("failed to run rtk");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains("foo from stdin"),
"{engine} did not read stdin: {stdout}"
);
assert!(
!stdout.contains("foo from the cwd"),
"{engine} walked the cwd instead of reading stdin: {stdout}"
);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! Stdout-only filters parse structured stdout, but a tool's diagnostics often go to
//! stderr. Dropping that stream leaves a failing command looking silent; inventing a
//! stdout message in its place is just as wrong. These pin both halves.
#![cfg(unix)]
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};
/// Writes an executable `name` in `dir` that runs `body`.
fn fake_tool(dir: &Path, name: &str, body: &str) {
let path = dir.join(name);
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
}
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
let path = format!(
"{}:{}",
dir.display(),
std::env::var("PATH").unwrap_or_default()
);
Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.env("PATH", path)
.output()
.expect("run rtk")
}
/// A golangci-lint that answers `--version`, then fails the way a config or build
/// error does: everything on stderr, stdout empty, non-zero exit.
fn fake_golangci(dir: &Path, failure: &str) {
fake_tool(
dir,
"golangci-lint",
&format!(
r#"if [ "$1" = "--version" ]; then
echo "golangci-lint has version 1.64.8"
exit 0
fi
{failure}"#
),
);
}
#[test]
fn golangci_lint_stderr_only_failure_reaches_the_user() {
let dir = tempfile::tempdir().expect("tempdir");
fake_golangci(
dir.path(),
r#"echo 'level=error msg="context loading failed: failed to load packages"' >&2
exit 3"#,
);
let out = rtk_with(dir.path(), &["golangci-lint", "run"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("context loading failed"),
"the tool's own error must reach the user; got stderr: {stderr}"
);
assert_eq!(out.status.code(), Some(3), "exit code must propagate");
}
/// The command said nothing on stdout, so neither does rtk. A filter's "I got nothing"
/// placeholder is not a diagnostic — the real one is on stderr.
#[test]
fn no_invented_stdout_diagnostic_when_the_tool_used_stderr() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(
dir.path(),
"prettier",
r#"echo "Checking formatting..." >&2
echo "[warn] src/a.js" >&2
echo "Code style issues found in the above file(s)." >&2
exit 1"#,
);
let out = rtk_with(dir.path(), &["prettier", "--check", "."]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stdout.trim().is_empty(),
"prettier ran fine and reported on stderr; stdout must not claim otherwise, got: {stdout}"
);
assert!(
stderr.contains("[warn] src/a.js"),
"prettier's report must reach the user; got stderr: {stderr}"
);
}
/// stderr goes out on its own stream, so it must not also be replayed on stdout.
#[test]
fn stderr_is_not_duplicated_onto_stdout() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(
dir.path(),
"ruff",
r#"echo "stdout line"
echo "stderr diagnostic" >&2
exit 1"#,
);
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stdout.contains("stderr diagnostic"),
"stderr must not be replayed on stdout; got stdout: {stdout}"
);
assert!(
stderr.contains("stderr diagnostic"),
"stderr must still reach the user; got stderr: {stderr}"
);
}
/// A command that genuinely says nothing must stay silent.
#[test]
fn silent_command_stays_silent() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(dir.path(), "ruff", "exit 0");
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
assert!(
String::from_utf8_lossy(&out.stdout).trim().is_empty(),
"a silent command must not gain output"
);
assert!(String::from_utf8_lossy(&out.stderr).trim().is_empty());
assert_eq!(out.status.code(), Some(0));
}
/// Not a golangci-lint quirk: every stdout-only filter forwards stderr.
#[test]
fn stderr_forwarding_is_not_golangci_specific() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(
dir.path(),
"ruff",
r#"echo "ruff failed hard" >&2
exit 2"#,
);
let out = rtk_with(dir.path(), &["ruff", "check", "."]);
assert!(
String::from_utf8_lossy(&out.stderr).contains("ruff failed hard"),
"stderr must reach the user for any stdout-only filter"
);
assert_eq!(out.status.code(), Some(2), "exit code must propagate");
}
/// golangci-lint exits 1 when it merely found lint issues. RTK reports them and
/// returns 0, so the linter running successfully does not fail a build.
#[test]
fn lint_issues_are_summarised_and_exit_zero() {
let dir = tempfile::tempdir().expect("tempdir");
let issues = r#"{"Issues":[{"FromLinter":"errcheck","Text":"unchecked","Pos":{"Filename":"main.go","Line":1,"Column":1},"SourceLines":["x()"],"Severity":""}]}"#;
fake_golangci(dir.path(), &format!("echo '{issues}'\nexit 1"));
let out = rtk_with(dir.path(), &["golangci-lint", "run"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("1 issues in 1 files") && stdout.contains("errcheck"),
"expected an issue summary; got: {stdout}"
);
assert_eq!(
out.status.code(),
Some(0),
"exit 1 means issues found, which RTK reports without failing"
);
}