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
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
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
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
32 changed files with 7010 additions and 297 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 ---
+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. |
+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
+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]
+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"));
}
+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;
}
}
+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();
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));
}
+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}");
}
}