Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak c8e5618e6a docs: fix Linux binary filename in README (gnu → musl)
README still referenced x86_64-unknown-linux-gnu.tar.gz which was
replaced by x86_64-unknown-linux-musl in PR #267 (v0.23.0+).

Fixes #323
2026-03-06 11:25:25 +01:00
Alex Tsanis 884e37edbf stream proxy output while command is running (#268) 2026-03-06 11:02:59 +01:00
patrick szymkowiak 27b35d84a3 fix: strip npx/bunx/pnpm prefixes in lint linter detection (#186) (#366)
When running `rtk lint npx eslint ...`, args[0] was "npx" instead of
"eslint", causing no JSON format flag injection and duplicated output.

Extract strip_pm_prefix() and detect_linter() helpers, skip package
manager prefixes before identifying the actual linter name.
2026-03-06 10:51:11 +01:00
Radu Ursache 0a1bcb05e5 fix: pass through -R/--repo flag in gh view commands (#328)
gh view/checks commands (pr view, issue view, pr checks, run view)
were ignoring extra flags like -R/--repo, causing failures outside
git repositories where gh needs -R to know which repo to query.

The root cause: these functions took args[0] as the identifier and
discarded everything else, while constructing hardcoded gh commands.

Changes:
- Add extract_identifier_and_extra_args() to separate the positional
  identifier from flags, handling both `view 123 -R owner/repo` and
  `view -R owner/repo 123` argument orders
- Pass extra args through to gh in view_pr, view_issue, pr_checks,
  and view_run
- Add has_json_flag() check at top of run() to passthrough when user
  explicitly requests --json output (related fix from #313)

Fixes #223
2026-03-06 10:31:10 +01:00
Sam Kvale 799f0856e4 fix: gh pr edit/comment pass correct subcommand to gh (#332)
* fix: gh pr edit/comment pass correct subcommand to gh

pr_action was receiving the past-tense display label ("edited",
"commented") and using it as both the gh subcommand and the
ok_confirmation message. This caused `gh pr edited` to be invoked
instead of `gh pr edit`, which fails with "unknown flag" errors.

Split the parameter into subcmd (for the gh invocation) and
display_label (for ok_confirmation output).

* smaller diff
2026-03-06 09:59:00 +01:00
github-actions[bot] 093e431193 chore(master): release 0.27.1 (#362)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-06 09:46:33 +01:00
patrick szymkowiak 409aed6dbc fix: support git commit -am, --amend and other flags (#327) (#360)
Clap was rejecting -a, --amend, --allow-empty etc. because Commit only
declared -m/--message. Switch to trailing_var_arg like other git
subcommands so all flags pass through to git directly.

Fixes #327
2026-03-06 09:41:23 +01:00
patrick szymkowiak 85b0b3eb0b fix: prettier false positive when not installed (#221) (#359)
* fix: prettier reports "All OK" when not installed (#221)

Empty or failed prettier output was incorrectly treated as "all files
formatted". Now detects empty output and non-zero exit code, shows the
actual error message instead of a false positive.

* test: add smoke tests for rewrite, verify, proxy, discover, diff, wc, smart, docker, json edge cases

Covers bug fixes #196, #344, #345, #346, #347 and previously untested
commands. Adds assert_fails helper. 118 assertions total (was 69).

* chore: update benchmark.sh with missing commands and fix paths

- Add cargo (build/test/clippy/check), diff, smart, wc, curl, wget sections
- Fix Python commands: use dedicated rtk ruff/pytest instead of rtk test
- Fix Go commands: use dedicated rtk go/golangci-lint, add go build/vet
- Make BENCH_DIR absolute so debug files work from temp fixture dirs
- Fallback to installed rtk if target/release/rtk not found
2026-03-06 09:40:24 +01:00
patrick szymkowiak dbc950395e fix: only rewrite docker compose ps/logs/build, skip unsupported subcommands (#336) (#363)
The rewrite pattern matched all `docker` commands but the regex didn't
cover `docker compose`, so compose subcommands were never rewritten.
Meanwhile unsupported compose commands (up, down, config) would fail
if manually prefixed with rtk.

- Extend regex to match `docker compose (ps|logs|build)`
- Unsupported compose subcommands (up, down, config, exec, etc.) are
  correctly skipped by the regex and not rewritten
- 6 new tests covering supported and unsupported compose subcommands

Fixes #336
2026-03-06 09:24:28 +01:00
Radu Ursache 45f9344f03 fix: preserve -- separator for cargo commands and silence fallback (#326)
Two fixes for command passthrough issues:

1. Restore `--` separator stripped by clap (#287): When running
   `rtk cargo test -- --nocapture`, clap consumes `--` and passes only
   `["--nocapture"]` to cargo, which rejects it. Now detect `--` from
   the original command line and re-insert it in the correct position.

2. Remove noisy `[rtk: parse failed, running raw]` stderr message (#286):
   Unrecognized commands like `rtk make` or `rtk ruby` pass through
   silently via the fallback, matching the documented behavior.

Fixes #286
Fixes #287
2026-03-06 09:00:13 +01:00
github-actions[bot] f693e060c6 chore(master): release 0.27.0 (#353)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-05 23:17:41 +01:00
Patrick szymkowiak 8953af0fc0 fix: bugs #196 #344 #345 #346 #347 — gh --json, hook check, RTK_DISABLED, 2>&1, json TOML 2026-03-05 23:08:41 +01:00
Patrick szymkowiak 079ee9a4ea fix: skip rewrite for gh --json/--jq/--template (#196)
gh commands with --json, --jq, or --template produce structured output
that rtk gh filtering would corrupt. Skip rewrite so callers get raw JSON.
2026-03-05 23:08:08 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 7ad291bab5 docs: bump version refs to 0.26.0, fix module count to 57
Version mentions (README.md, CLAUDE.md, ARCHITECTURE.md) were still
on 0.25.0. Module count was 56 (missed hook_check module added in #350).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 22:52:15 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 6c13d23436 fix: RTK_DISABLED ignored, 2>&1 broken, json TOML error (#345, #346, #347)
- #345: rewrite_segment() now returns None when env_prefix contains
  RTK_DISABLED= — prevents rewriting commands the user explicitly
  opted out of
- #346: rewrite_compound() detects redirect operators (2>&1, >&2,
  &>/dev/null, &>>) before treating bare & as background operator —
  fixes corrupted compound commands containing stderr redirects
- #347: validate_json_extension() helper added to json_cmd.rs — early
  rejection with clear error message for TOML/YAML/XML/CSV/etc. files,
  with a dedicated tip for Cargo.toml (suggests rtk deps)

Tests: 16 new unit tests (4 + 6 + 6), 7 new hook integration tests.
All 672 tests pass. Quality gate clean.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 22:50:17 +01:00
patrick szymkowiak 3141fecf95 feat: warn when installed hook is outdated (#344) (#350)
- Add `# rtk-hook-version: 2` header to hook file
- New `hook_check` module: detect outdated hook on startup, warn 1/day
- Homebrew caveats: remind users to run `rtk init -g` after upgrade
2026-03-05 22:33:17 +01:00
github-actions[bot] 32ade38e0a chore(master): release 0.26.0 (#337)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-05 21:02:37 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 6ad6ffecce feat: add Claude Code skills for PR and issue triage (#343)
* feat: add Claude Code skills for PR and issue triage

Two skills that power structured audits directly in Claude Code sessions.
They replace ad-hoc manual reviews with a repeatable, documented workflow.

**`/pr-triage`** — Pull request audit
Scans open PRs, runs deep review on selected ones, and posts formatted
review comments to GitHub. Covers code quality, test coverage, security
surface, and alignment with CLAUDE.md conventions. Useful before every
merge and for contributor onboarding.

**`/issue-triage`** — Issue audit
Audits open issues, auto-categorizes (bug/feature/doc/question), detects
duplicates, cross-references related PRs, and estimates risk/priority.
Posts structured comments so maintainers have a clear action queue.

Both skills integrate with the `gh` CLI and can be invoked with args:
  /pr-triage 42 57        — deep review of specific PRs
  /pr-triage all          — full audit of all open PRs
  /issue-triage           — audit-only mode (no comments posted)
  /issue-triage all en    — deep analysis, English output

These reduce the overhead of code review and issue management to a single
slash command, keeping context inside the Claude Code session.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix version references 0.24.0 → 0.25.0 and module count (pre-existing)

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 20:51:15 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 a8d6106f73 fix: curl JSON size guard (#297) + exclude_commands config (#243) (#342)
* fix: curl size guard (#297) + exclude_commands config (#243)

**#297 — curl JSON inflation guard**
- `rtk curl` no longer replaces small JSON responses with a type schema
  that is larger than the original payload
- Size guard in `filter_curl_output()`: only return schema when
  `schema.len() <= original.len()`
- Inspired by PR #324 (@rursache)

**#243 — exclude_commands config**
- Add `[hooks] exclude_commands = ["curl"]` in config.toml to prevent
  the auto-rewrite hook from rewriting specific commands
- Survives `rtk init -g` re-runs (config.toml is user-owned)
- Implemented in `rewrite_cmd::run()` via `HooksConfig` struct
- Threaded through `rewrite_command()` → `rewrite_compound()` → `rewrite_segment()`

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add #297 and #243 to CHANGELOG + exclude_commands in README

* docs: fix version references 0.24.0 → 0.25.0 across all docs

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 20:46:40 +01:00
patrick szymkowiak baff6a2334 feat: anonymous telemetry ping (1/day, opt-out) (#334)
* feat: add anonymous telemetry ping (1/day, opt-out)

Fire-and-forget daily ping to track active installs for BPI metrics.
- SHA-256 device hash (hostname:user), no PII
- Opt-out: RTK_TELEMETRY_DISABLED=1 or config.toml [telemetry] enabled=false
- Token injected at compile time via option_env!, not in source
- 23h throttle via marker file, 2s timeout, non-blocking thread

* ci: inject RTK_TELEMETRY_TOKEN at build time in release workflow

All 3 build jobs (binary, DEB, RPM) now receive the token from
GitHub secrets so option_env!() compiles it into release binaries.

* refactor: externalize telemetry URL via option_env!(RTK_TELEMETRY_URL)

URL and token are both injected at compile time — no hardcoded
server address in source code. Builds without the env var simply
skip telemetry silently.
2026-03-05 15:34:49 +01:00
github-actions[bot] 99b9f9f926 chore(master): release 0.25.0 (#321)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-05 14:32:19 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 f447a3d5b1 feat: rtk rewrite — single source of truth for LLM hook rewrites (#241)
* feat: add `rtk rewrite` command — single source of truth for hook rewrites

Implements `rtk rewrite <cmd>` as the canonical rewrite engine for all
LLM hook integrations (Claude Code, Gemini CLI, future tools).

- Add `rewrite_prefixes` field to `RtkRule` in discover/registry.rs
- Add public `rewrite_command()` with compound command support (&&, ||, ;, |)
- Add `rewrite_segment()`, `rewrite_compound()`, `strip_word_prefix()` helpers
- Handle already-rtk commands (exit 0, identical output)
- Handle unsupported/ignored commands (exit 1, no output)
- Add 20 unit tests covering all branches and edge cases
- Create `src/rewrite_cmd.rs` thin CLI wrapper
- Register `Commands::Rewrite` in main.rs
- Simplify `.claude/hooks/rtk-rewrite.sh` from 357 → 60 lines

Hooks no longer need duplicate mapping logic — a single
`REWRITTEN=$(rtk rewrite "$CMD") || exit 0` handles everything.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix version references and module count for 0.22.2

- README.md, CLAUDE.md, ARCHITECTURE.md: 0.20.1 → 0.22.2
- ARCHITECTURE.md: module count 48 → 51 (added rewrite_cmd + 2 from master)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ci: update hook coverage check to verify registry (not hook script)

Since PR #241, the hook delegates to `rtk rewrite` — command mappings
live in src/discover/registry.rs, not the bash hook script.

Update the "Verify hook coverage" CI step to:
- Check that the hook calls `rtk rewrite` (new architecture)
- Check that registry.rs has rewrite_prefixes for all Python/Go commands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: support single `&` background operator in compound rewrites

Per feedback from @xDelph: AI agents increasingly use `cmd1 & cmd2`
for parallel execution. This commit adds support alongside existing
`&&`, `||`, `;`, and `|` operators.

Changes:
- rewrite_compound: add match arm for single `&` (after `&&` check)
- rewrite_command: add `" & "` to has_compound detection
- init: show "installed/updated" vs "already up to date" so users
  know whether rtk init changed the hook on re-run

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add Python/Go commands to rewrite registry

Add `ruff`, `pytest`, `pip`, `go`, and `golangci-lint` to both
PATTERNS and RULES in registry.rs so the CI coverage check passes
and `rtk rewrite` correctly identifies these commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.23.0 in README

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.23.0 in CLAUDE.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version and module count to 0.23.0/52 in ARCHITECTURE.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address P0 review feedback on rtk-rewrite PR

P0.1 - Replace 218-line bash hook with 58-line thin delegating hook.
  All rewrite logic now lives exclusively in `rtk rewrite` (Rust registry).
  `rtk init` installs the thin hook via include_str!.

P0.2 - Fix `head -20 file` crash at runtime.
  Generic prefix replacement produced `rtk read -20 file` (invalid clap args).
  Now translates `head -N file` → `rtk read file --max-lines N` and skips
  unsupported head flags (e.g. -c) by returning exit 1.

P0.3 - Add version guard in hook for rtk < 0.23.0.
  Prints a warning to stderr instead of silently doing nothing.

Also adds missing registry entries vs old hook:
  - gh release, cargo install
  - docker run/exec/build, kubectl describe/apply
  - tree, diff

474 tests pass, 0 clippy warnings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: cargo fmt

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(discover): extract rules/patterns into rules.rs

Per aeppling review: registry.rs was too large (~1500 lines).
Extract all static data into src/discover/rules.rs:
- RtkRule struct (with pub fields)
- PATTERNS const array
- RULES const array
- IGNORED_PREFIXES and IGNORED_EXACT const arrays

registry.rs now contains only logic + tests.
rules.rs is the single place to add a new command mapping.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.24.0 in README

* docs: update version references to 0.24.0 in CLAUDE.md and ARCHITECTURE.md

* fix(discover): add aws and psql to rewrite registry

rtk aws and rtk psql modules exist since PR #216 but were missing
from the registry rules — rewrite was silently skipping them.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(discover): exhaustive regression tests for rewrite registry

Cover all command categories added in PR #241 and missing from
the previous test suite:
- aws / psql (PR #216 modules, gap detected during non-reg run)
- Python: ruff, pytest, python -m pytest, pip, uv pip
- Go: go test/build/vet, golangci-lint
- JS/TS: vitest, pnpm vitest, prisma, prettier, pnpm list
- Compound operators: || and ; rewrites, 4-segment chains,
  mixed supported/unsupported segments, all-unsupported → None
- sudo prefix rewrite, env var prefix rewrite
- find with native flags
- Registry invariants: PATTERNS/RULES aligned, all rules valid,
  all patterns are valid regex

Before: 559 tests. After: 607 tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(migration): document breaking change + detect outdated hook in rtk config

CHANGELOG [Unreleased]:
- Migration required: rtk init --global needed after upgrade
- Documents upgrade path and explains no immediate breakage

rtk init --show / rtk config now detects old hook (inline if-else)
vs new thin delegator (rtk rewrite) and prints actionable warning:

  ⚠️  Hook: ~/.claude/hooks/rtk-rewrite.sh (outdated — inline logic, not thin delegator)
     → Run `rtk init --global` to upgrade to the single source of truth hook

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update hook references for thin delegator (0.24.0)

- ARCHITECTURE.md: fix hook description (shell script → thin delegator)
- INSTALL.md: add upgrade path for old hook users (pre-0.24 breaking change)
- SECURITY.md: add registry.rs + hook files to Tier 1 critical files

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(arch): fix module count 52→55, add aws/psql/rewrite to module map

Adds aws_cmd, psql_cmd (PR #216) and rewrite_cmd (this PR) to the
Complete Module Map table. Updates total from 52 to 55 to match main.rs.

Fixes CI validate-docs.sh module count mismatch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ci: fix hook coverage check to search rules.rs instead of registry.rs

After the PR #241 refactor, rewrite_prefixes constants moved from
registry.rs to rules.rs. Update grep to search the whole discover/
directory so it finds them in the right file.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 14:20:01 +01:00
Sahil Gandhi 7ac5bc4bd3 fix(find): accept native find flags (-name, -type, etc.) (#211)
* fix(find): accept native find flags (-name, -type, etc.)

* fix: apply cargo fmt after merge

* Merge master into fix/find-positional-args

Update git -C test for new global options support, apply fmt.
2026-03-05 09:10:01 +01:00
39 changed files with 4874 additions and 837 deletions

No files matched your search

+18 -182
View File
@@ -1,7 +1,9 @@
#!/bin/bash
# RTK auto-rewrite hook for Claude Code PreToolUse:Bash
# Transparently rewrites raw commands to their rtk equivalents.
# Outputs JSON with updatedInput to modify the command before execution.
# Transparently rewrites raw commands to their RTK equivalents.
# Uses `rtk rewrite` as single source of truth — no duplicate mapping logic here.
#
# To add support for new commands, update src/discover/registry.rs (PATTERNS + RULES).
# --- Audit logging (opt-in via RTK_HOOK_AUDIT=1) ---
_rtk_audit_log() {
@@ -30,198 +32,32 @@ if [ -z "$CMD" ]; then
exit 0
fi
# Extract the first meaningful command (before pipes, &&, etc.)
# We only rewrite if the FIRST command in a chain matches.
FIRST_CMD="$CMD"
# Skip if already using rtk
case "$FIRST_CMD" in
rtk\ *|*/rtk\ *) _rtk_audit_log "skip:already_rtk" "$CMD"; exit 0 ;;
esac
# Skip commands with heredocs, variable assignments as the whole command, etc.
case "$FIRST_CMD" in
# Skip heredocs (rtk rewrite also skips them, but bail early)
case "$CMD" in
*'<<'*) _rtk_audit_log "skip:heredoc" "$CMD"; exit 0 ;;
esac
# Strip leading env var assignments for pattern matching
# e.g., "TEST_SESSION_ID=2 npx playwright test" → match against "npx playwright test"
# but preserve them in the rewritten command for execution.
ENV_PREFIX=$(echo "$FIRST_CMD" | grep -oE '^([A-Za-z_][A-Za-z0-9_]*=[^ ]* +)+' || echo "")
if [ -n "$ENV_PREFIX" ]; then
MATCH_CMD="${FIRST_CMD:${#ENV_PREFIX}}"
CMD_BODY="${CMD:${#ENV_PREFIX}}"
else
MATCH_CMD="$FIRST_CMD"
CMD_BODY="$CMD"
fi
REWRITTEN=""
# --- Git commands ---
if echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+status([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git status/rtk git status/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+diff([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git diff/rtk git diff/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+log([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git log/rtk git log/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+add([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git add/rtk git add/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+commit([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git commit/rtk git commit/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+push([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git push/rtk git push/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+pull([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git pull/rtk git pull/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+branch([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git branch/rtk git branch/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+fetch([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git fetch/rtk git fetch/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+stash([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git stash/rtk git stash/')"
elif echo "$MATCH_CMD" | grep -qE '^git[[:space:]]+show([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^git show/rtk git show/')"
# --- GitHub CLI (added: api, release) ---
elif echo "$MATCH_CMD" | grep -qE '^gh[[:space:]]+(pr|issue|run|api|release)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^gh /rtk gh /')"
# --- Cargo ---
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo test/rtk cargo test/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+build([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo build/rtk cargo build/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+clippy([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo clippy/rtk cargo clippy/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+check([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo check/rtk cargo check/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+install([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo install/rtk cargo install/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+nextest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo nextest/rtk cargo nextest/')"
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]+fmt([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cargo fmt/rtk cargo fmt/')"
# --- File operations ---
elif echo "$MATCH_CMD" | grep -qE '^cat[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cat /rtk read /')"
elif echo "$MATCH_CMD" | grep -qE '^(rg|grep)[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(rg|grep) /rtk grep /')"
elif echo "$MATCH_CMD" | grep -qE '^ls([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^ls/rtk ls/')"
elif echo "$MATCH_CMD" | grep -qE '^tree([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^tree/rtk tree/')"
elif echo "$MATCH_CMD" | grep -qE '^find[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^find /rtk find /')"
elif echo "$MATCH_CMD" | grep -qE '^diff[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^diff /rtk diff /')"
elif echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+'; then
# Transform: head -N file → rtk read file --max-lines N
# Also handle: head --lines=N file
if echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+-[0-9]+[[:space:]]+'; then
LINES=$(echo "$MATCH_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
FILE=$(echo "$MATCH_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
REWRITTEN="${ENV_PREFIX}rtk read $FILE --max-lines $LINES"
elif echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+--lines=[0-9]+[[:space:]]+'; then
LINES=$(echo "$MATCH_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
FILE=$(echo "$MATCH_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
REWRITTEN="${ENV_PREFIX}rtk read $FILE --max-lines $LINES"
fi
# --- JS/TS tooling (added: npm run, npm test, vue-tsc) ---
elif echo "$MATCH_CMD" | grep -qE '^(pnpm[[:space:]]+)?(npx[[:space:]]+)?vitest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(pnpm )?(npx )?vitest( run)?/rtk vitest run/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm test/rtk vitest run/')"
elif echo "$MATCH_CMD" | grep -qE '^npm[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^npm test/rtk npm test/')"
elif echo "$MATCH_CMD" | grep -qE '^npm[[:space:]]+run[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^npm run /rtk npm /')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?vue-tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?vue-tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+lint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm lint/rtk lint/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?eslint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?eslint/rtk lint/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?prettier([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?prettier/rtk prettier/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?playwright([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?playwright/rtk playwright/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+playwright([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm playwright/rtk playwright/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?prisma([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?prisma/rtk prisma/')"
# --- Containers (added: docker compose, docker run/build/exec, kubectl describe/apply) ---
elif echo "$MATCH_CMD" | grep -qE '^docker[[:space:]]+compose([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^docker /rtk docker /')"
elif echo "$MATCH_CMD" | grep -qE '^docker[[:space:]]+(ps|images|logs|run|build|exec)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^docker /rtk docker /')"
elif echo "$MATCH_CMD" | grep -qE '^kubectl[[:space:]]+(get|logs|describe|apply)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^kubectl /rtk kubectl /')"
# --- Network ---
elif echo "$MATCH_CMD" | grep -qE '^curl[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^curl /rtk curl /')"
elif echo "$MATCH_CMD" | grep -qE '^wget[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^wget /rtk wget /')"
# --- pnpm package management ---
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+(list|ls|outdated)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm /rtk pnpm /')"
# --- Python tooling ---
elif echo "$MATCH_CMD" | grep -qE '^pytest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pytest/rtk pytest/')"
elif echo "$MATCH_CMD" | grep -qE '^python[[:space:]]+-m[[:space:]]+pytest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^python -m pytest/rtk pytest/')"
elif echo "$MATCH_CMD" | grep -qE '^ruff[[:space:]]+(check|format)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^ruff /rtk ruff /')"
elif echo "$MATCH_CMD" | grep -qE '^pip[[:space:]]+(list|outdated|install|show)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pip /rtk pip /')"
elif echo "$MATCH_CMD" | grep -qE '^uv[[:space:]]+pip[[:space:]]+(list|outdated|install|show)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^uv pip /rtk pip /')"
elif echo "$MATCH_CMD" | grep -qE '^mypy([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^mypy/rtk mypy/')"
elif echo "$MATCH_CMD" | grep -qE '^python[[:space:]]+-m[[:space:]]+mypy([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^python -m mypy/rtk mypy/')"
# --- Go tooling ---
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go test/rtk go test/')"
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+build([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go build/rtk go build/')"
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+vet([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go vet/rtk go vet/')"
elif echo "$MATCH_CMD" | grep -qE '^golangci-lint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^golangci-lint/rtk golangci-lint/')"
# --- AWS CLI ---
elif echo "$MATCH_CMD" | grep -qE '^aws[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^aws /rtk aws /')"
# --- PostgreSQL ---
elif echo "$MATCH_CMD" | grep -qE '^psql([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^psql/rtk psql/')"
fi
# If no rewrite needed, approve as-is
if [ -z "$REWRITTEN" ]; then
# Rewrite via rtk — single source of truth for all command mappings.
# Exit 1 = no RTK equivalent, pass through unchanged.
# Exit 0 = rewritten command (or already RTK, identical output).
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || {
_rtk_audit_log "skip:no_match" "$CMD"
exit 0
}
# If output is identical, command was already using RTK — nothing to do.
if [ "$CMD" = "$REWRITTEN" ]; then
_rtk_audit_log "skip:already_rtk" "$CMD"
exit 0
fi
_rtk_audit_log "rewrite" "$CMD" "$REWRITTEN"
# Build the updated tool_input with all original fields preserved, only command changed
# Build the updated tool_input with all original fields preserved, only command changed.
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
# Output the rewrite instruction
# Output the rewrite instruction in Claude Code hook format.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
+348
View File
@@ -0,0 +1,348 @@
---
description: >
Issue triage: audit open issues, categorize, detect duplicates, cross-ref PRs, risk assessment, post comments.
Args: "all" for deep analysis of all, issue numbers to focus (e.g. "42 57"), "en"/"fr" for language, no arg = audit only in French.
---
# Issue Triage
## Quand utiliser
| Skill | Usage | Output |
|-------|-------|--------|
| `/issue-triage` | Trier, analyser, commenter les issues | Tableaux d'action + deep analysis + commentaires postés |
| `/repo-recap` | Récap général pour partager avec l'équipe | Résumé Markdown (PRs + issues + releases) |
**Déclencheurs** :
- Manuellement : `/issue-triage` ou `/issue-triage all` ou `/issue-triage 42 57`
- Proactivement : quand >10 issues ouvertes sans triage, ou issue stale >30j détectée
---
## Langue
- Vérifier l'argument passé au skill
- Si `en` ou `english` → tableaux et résumé en anglais
- Si `fr`, `french`, ou pas d'argument → français (défaut)
- Note : les commentaires GitHub (Phase 3) restent TOUJOURS en anglais (audience internationale)
---
Workflow en 3 phases : audit automatique → deep analysis opt-in → commentaires avec validation obligatoire.
## Préconditions
```bash
git rev-parse --is-inside-work-tree
gh auth status
```
Si l'un échoue, stop et expliquer ce qui manque.
---
## Phase 1 — Audit (toujours exécutée)
### Data Gathering (commandes en parallèle)
```bash
# Identité du repo
gh repo view --json nameWithOwner -q .nameWithOwner
# Issues ouvertes avec métadonnées complètes
gh issue list --state open --limit 100 \
--json number,title,author,createdAt,updatedAt,labels,assignees,body,comments
# PRs ouvertes (pour cross-référence)
gh pr list --state open --limit 50 --json number,title,body
# Issues fermées récemment (pour détection doublons)
gh issue list --state closed --limit 20 \
--json number,title,labels,closedAt
# Collaborateurs (pour protéger les issues des mainteneurs)
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
```
**Fallback collaborateurs** : si `gh api .../collaborators` échoue (403/404) :
```bash
gh pr list --state merged --limit 10 --json author --jq '.[].author.login' | sort -u
```
Si toujours ambigu, demander à l'utilisateur via `AskUserQuestion`.
**Note** : `author` est un objet `{login: "..."}` — toujours extraire `.author.login`.
### Analyse — 6 dimensions
**1. Catégorisation** (labels existants > inférence titre/body) :
- **Bug** : mots-clés `crash`, `error`, `fail`, `broken`, `regression`, `wrong`, `unexpected`
- **Feature** : `add`, `implement`, `support`, `new`, `feat:`
- **Enhancement** : `improve`, `optimize`, `better`, `enhance`, `refactor`
- **Question/Support** : `how`, `why`, `help`, `unclear`, `docs`, `documentation`
- **Duplicate Candidate** : voir dimension 3 ci-dessous
**2. Cross-ref PRs** :
- Scanner `body` de chaque PR ouverte pour `fixes #N`, `closes #N`, `resolves #N` (case-insensitive, regex)
- Construire un map : `issue_number -> [PR numbers]`
- Une issue liée à une PR mergée → recommander fermeture
**3. Détection doublons** :
- Normaliser les titres : lowercase, strip préfixes (`bug:`, `feat:`, `[bug]`, `[feature]`, etc.)
- **Jaccard sur mots des titres** : si score > 60% entre deux issues → candidat doublon
- **Keywords body overlap** > 50% → renforcement du signal
- Comparer aussi avec issues fermées récentes (20 dernières)
- Un faux positif peut être confirmé/écarté en Phase 2
**4. Classification risque** :
- **Rouge** : mots-clés `CVE`, `vulnerability`, `injection`, `auth bypass`, `security`, `exploit`, `unsafe`, `credentials`, `leak`, `RCE`, `XSS`
- **Jaune** : `breaking change`, `migration`, `deprecation`, `remove API`, `breaking`, `incompatible`
- **Vert** : tout le reste
**5. Staleness** :
- >30j sans activité (updatedAt) → **Stale**
- >90j sans activité → **Very Stale**
- Calculer depuis la date actuelle
**6. Recommandations d'action** :
- `Accept & Prioritize` : issue claire, reproducible, dans scope
- `Label needed` : issue sans label
- `Comment needed` : info manquante, body insuffisant
- `Linked to PR` : une PR ouverte référence cette issue
- `Duplicate candidate` : candidat doublon identifié (préciser avec `#N`)
- `Close candidate` : stale + aucune activité récente, ou hors scope (jamais si auteur est collaborateur)
- `PR merged → close` : PR liée est mergée, issue encore ouverte
### Output — 5 tableaux
```
## Issues ouvertes ({count})
### Critiques (risque rouge)
| # | Titre | Auteur | Âge | Labels | Action |
| - | ----- | ------ | --- | ------ | ------ |
### Liées à une PR
| # | Titre | Auteur | PR(s) liée(s) | Status PR | Action |
| - | ----- | ------ | ------------- | --------- | ------ |
### Actives
| # | Titre | Auteur | Catégorie | Âge | Labels | Action |
| - | ----- | ------ | --------- | --- | ------ | ------ |
### Doublons candidats
| # | Titre | Doublon de | Similarité | Action |
| - | ----- | ---------- | ---------- | ------ |
### Stale
| # | Titre | Auteur | Dernière activité | Action |
| - | ----- | ------ | ----------------- | ------ |
### Résumé
- Total : {N} issues ouvertes
- Critiques : {N} (risque sécurité ou breaking)
- Liées à PR : {N}
- Doublons candidats : {N}
- Stale (>30j) : {N} | Very Stale (>90j) : {N}
- Sans labels : {N}
- Quick wins (à fermer ou labeler rapidement) : {liste}
```
0 issues → afficher `Aucune issue ouverte.` et terminer.
**Note** : `Âge` = jours depuis `createdAt`, format `{N}j`. Si >30j, afficher en **gras**.
### Copie automatique
Après affichage du tableau de triage, copier dans le presse-papier :
```bash
pbcopy <<'EOF'
{tableau de triage complet}
EOF
```
Confirmer : `Tableau copié dans le presse-papier.` (FR) / `Triage table copied to clipboard.` (EN)
---
## Phase 2 — Deep Analysis (opt-in)
### Sélection des issues
**Si argument passé** :
- `"all"` → toutes les issues ouvertes
- Numéros (`"42 57"`) → uniquement ces issues
- Pas d'argument → proposer via `AskUserQuestion`
**Si pas d'argument**, afficher :
```
question: "Quelles issues voulez-vous analyser en profondeur ?"
header: "Deep Analysis"
multiSelect: true
options:
- label: "Toutes ({N} issues)"
description: "Analyse approfondie de toutes les issues avec agents en parallèle"
- label: "Critiques uniquement"
description: "Focus sur les {M} issues à risque rouge/jaune"
- label: "Doublons candidats"
description: "Confirmer ou écarter les {K} doublons détectés"
- label: "Stale uniquement"
description: "Décision close/keep sur les {J} issues stale"
- label: "Passer"
description: "Terminer ici — juste l'audit"
```
Si "Passer" → fin du workflow.
### Exécution de l'analyse
Pour chaque issue sélectionnée, lancer un agent via **Task tool en parallèle** :
```
subagent_type: general-purpose
model: sonnet
prompt: |
Analyze GitHub issue #{num}: "{title}" by @{author}
**Metadata**: Created {createdAt}, last updated {updatedAt}, labels: {labels}
**Body**:
{body}
**Existing comments** ({comments_count} total, showing last 5):
{last_5_comments}
**Context**:
- Linked PRs: {linked_prs or "none"}
- Duplicate candidate of: {duplicate_of or "none"}
- Risk classification: {risk_color}
Analyze this issue and return a structured report:
### Scope Assessment
What is this issue actually asking for? Is it clearly defined?
### Missing Information
What's needed to act on this? (reproduction steps, version, environment, etc.)
### Risk & Impact
Security risk? Breaking change? Who's affected?
### Effort Estimate
XS (<1h) / S (1-4h) / M (1-2d) / L (3-5d) / XL (>1 week)
### Priority
P0 (critical, act now) / P1 (high, this sprint) / P2 (medium, backlog) / P3 (low, someday)
### Recommended Action
One of: Accept & Prioritize, Request More Info, Mark Duplicate (#N), Close (Stale), Close (Out of Scope), Link to Existing PR
### Draft Comment
Draft a GitHub comment in English using the appropriate template from templates/issue-comment.md.
Be specific, helpful, and constructive.
```
Si issue a >50 commentaires, résumer les 5 derniers uniquement.
Agréger tous les rapports. Afficher un résumé après toutes les analyses.
---
## Phase 3 — Actions (validation obligatoire)
### Types d'actions possibles
- **Commenter** : `gh issue comment {num} --body-file -`
- **Labeler** : `gh issue edit {num} --add-label "{label}"` (skip si label déjà présent)
- **Fermer** : `gh issue close {num} --reason "not planned"` (jamais sans validation)
### Génération des drafts
Pour chaque issue analysée, générer les actions (commentaire + labels + fermeture si applicable) en utilisant `templates/issue-comment.md`.
**Règles** :
- Langue des commentaires : **anglais** (audience internationale)
- Ton : professionnel, constructif, factuel
- Ne jamais re-labeler une issue qui a déjà ce label
- Ne jamais proposer "close" pour une issue d'un collaborateur
- Toujours afficher le draft AVANT tout `gh issue comment`
### Affichage et validation
**Afficher TOUS les drafts** au format :
```
---
### Draft — Issue #{num}: {title}
**Actions proposées** : {Commentaire | Label: "bug" | Fermeture}
**Commentaire** :
{commentaire complet}
---
```
Puis demander validation via `AskUserQuestion` :
```
question: "Ces actions sont prêtes. Lesquelles voulez-vous exécuter ?"
header: "Exécuter"
multiSelect: true
options:
- label: "Toutes ({N} actions)"
description: "Commenter + labeler + fermer selon les drafts"
- label: "Issue #{x} — {title_truncated}"
description: "Exécuter uniquement les actions pour cette issue"
- label: "Aucune"
description: "Annuler — ne rien faire"
```
(Générer une option par issue + "Toutes" + "Aucune")
### Exécution
Pour chaque action validée, exécuter dans l'ordre : commenter → labeler → fermer.
```bash
# Commenter
gh issue comment {num} --body-file - <<'COMMENT_EOF'
{commentaire}
COMMENT_EOF
# Labeler (si applicable)
gh issue edit {num} --add-label "{label}"
# Fermer (si applicable)
gh issue close {num} --reason "not planned"
```
Confirmer chaque action : `Commentaire posté sur issue #{num}: {title}`
Si "Aucune" → `Aucune action exécutée. Workflow terminé.`
---
## Gestion des cas limites
| Situation | Comportement |
|-----------|--------------|
| 0 issues ouvertes | `Aucune issue ouverte.` + terminer |
| Issue sans body | Catégoriser par titre, recommander `Comment needed` |
| >50 commentaires | Résumer les 5 derniers uniquement |
| Faux positif doublon | Phase 2 confirme/écarte — ne pas agir sur suspicion seule |
| Labels déjà présents | Ne pas re-labeler, signaler "label déjà appliqué" |
| Issue d'un collaborateur | Jamais `close candidate` automatique |
| Rate limit GitHub API | Réduire `--limit`, notifier l'utilisateur |
| PR mergée liée à issue ouverte | Recommander fermeture de l'issue |
| Issue sans activité >90j | Very Stale — proposer fermeture avec message bienveillant |
| Duplicate confirmed in Phase 2 | Poster commentaire + fermer en faveur de l'issue originale |
---
## Notes
- Toujours dériver owner/repo via `gh repo view`, jamais hardcoder
- Utiliser `gh` CLI (pas `curl` GitHub API) sauf pour la liste des collaborateurs
- `updatedAt` peut être null sur certaines issues → traiter comme `createdAt`
- Ne jamais poster ou fermer sans validation explicite de l'utilisateur dans le chat
- Les commentaires draftés doivent être visibles AVANT tout `gh issue comment`
- Similarité Jaccard = |intersection mots| / |union mots| (exclure stop words : a, the, is, in, of, for, to, with, on, at, by)
@@ -0,0 +1,134 @@
# Issue Comment Templates
Use these templates to generate GitHub issue comments. Select the appropriate template based on the recommended action from Phase 2. Comments are posted in **English** (international audience).
---
## Template 1 — Acknowledgment + Request Info
Use when: issue is valid but missing information to act on it (reproduction steps, version, environment, context).
```markdown
## Issue Triage
**Category**: {Bug | Feature | Enhancement | Question}
**Priority**: {P0 | P1 | P2 | P3}
**Effort estimate**: {XS | S | M | L | XL}
### Assessment
{1-2 sentences: what this issue is about and why it matters. Be direct.}
### Missing Information
To move forward, we need the following:
- {Specific missing info 1 — e.g., "RTK version (`rtk --version` output)"}
- {Specific missing info 2 — e.g., "Full command used and raw output"}
- {Specific missing info 3 — e.g., "OS and shell (macOS/Linux, zsh/bash)"}
### Next Steps
{What happens once the info is provided — e.g., "Once confirmed, we'll prioritize this for the next release."}
---
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
```
---
## Template 2 — Duplicate
Use when: this issue is a duplicate of an existing open (or recently closed) issue.
```markdown
## Duplicate Issue
This issue covers the same problem as #{original_number}: **{original_title}**.
### Overlap
{1-2 sentences explaining the overlap — what's identical or nearly identical between the two issues.}
If your situation differs in an important way (different command, different OS, different error message), please reopen and add that context. Otherwise, follow the original issue for updates.
---
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
```
---
## Template 3 — Close (Stale)
Use when: issue has had no activity for >90 days and there's been no engagement.
```markdown
## Closing: No Activity
This issue has been open for {N} days without activity. To keep the backlog actionable, we're closing it.
If this is still relevant:
- Reopen and add context about your current setup
- Or reference this issue in a new one if the problem has evolved
Thanks for taking the time to report it.
---
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
```
---
## Template 4 — Close (Out of Scope)
Use when: issue requests something that doesn't align with RTK's design goals (e.g., adding async runtime, platform-specific features outside scope, changing core behavior).
```markdown
## Closing: Out of Scope
After review, this request falls outside RTK's current design goals.
### Rationale
{1-2 sentences explaining why — be specific. Reference design constraints if relevant, e.g., "RTK is intentionally single-threaded with zero async dependencies to maintain <10ms startup time."}
### Alternatives
{If applicable: what the user can do instead. E.g., "For this use case, `rtk proxy <cmd>` gives you raw output while still tracking usage metrics."}
If the use case evolves or the scope changes in a future version, feel free to reopen with updated context.
---
*Triaged via [rtk](https://github.com/rtk-ai/rtk) `/issue-triage`*
```
---
## Formatting Rules
**Tone** : Professional, constructive, factual. Help the user move forward. Challenge the issue scope, not the person who filed it.
**Length** : 100-250 words per comment. Long enough to be useful, short enough to respect the reader's time.
**Specificity** : Always name the exact command, file, or behavior in question. Vague comments waste everyone's time.
**No superlatives** : Don't write "great issue", "excellent report", "amazing catch". Just address the substance.
**Priority labels** :
- P0 — Critical: security vulnerability, data loss, broken core functionality
- P1 — High: significant bug affecting common workflows, actionable this sprint
- P2 — Medium: valid issue, queue for backlog
- P3 — Low: nice-to-have, future consideration
**Effort labels** :
- XS : <1 hour
- S : 1-4 hours
- M : 1-2 days
- L : 3-5 days
- XL : >1 week
**RTK-specific context to include when relevant** :
- Mention `rtk --version` as the first diagnostic step for bug reports
- Reference the relevant module (`src/git.rs`, `src/vitest_cmd.rs`, etc.) when known
- Link to the filter development checklist in CLAUDE.md for feature requests that involve new commands
- Note performance constraints (<10ms startup) when rejecting async/heavy dependency requests
+315
View File
@@ -0,0 +1,315 @@
---
description: >
PR triage: audit open PRs, deep review selected ones, draft and post review comments.
Args: "all" to review all, PR numbers to focus (e.g. "42 57"), "en"/"fr" for language, no arg = audit only in French.
---
# PR Triage
## Quand utiliser
| Skill | Usage | Output |
|-------|-------|--------|
| `/pr-triage` | Trier, reviewer, commenter les PRs | Tableau d'action + reviews + commentaires postés |
| `/repo-recap` | Récap général pour partager avec l'équipe | Résumé Markdown (PRs + issues + releases) |
**Déclencheurs** :
- Manuellement : `/pr-triage` ou `/pr-triage all` ou `/pr-triage 42 57`
- Proactivement : quand >5 PRs ouvertes sans review, ou PR stale >14j détectée
---
## Langue
- Vérifier l'argument passé au skill
- Si `en` ou `english` → tableaux et résumé en anglais
- Si `fr`, `french`, ou pas d'argument → français (défaut)
- Note : les commentaires GitHub (Phase 3) restent TOUJOURS en anglais (audience internationale)
---
Workflow en 3 phases : audit automatique → deep review opt-in → commentaires avec validation obligatoire.
## Préconditions
```bash
git rev-parse --is-inside-work-tree
gh auth status
```
Si l'un échoue, stop et expliquer ce qui manque.
---
## Phase 1 — Audit (toujours exécutée)
### Data Gathering (commandes en parallèle)
```bash
# Identité du repo
gh repo view --json nameWithOwner -q .nameWithOwner
# PRs ouvertes avec métadonnées complètes (ajouter body pour cross-référence issues)
gh pr list --state open --limit 50 \
--json number,title,author,createdAt,updatedAt,additions,deletions,changedFiles,isDraft,mergeable,reviewDecision,statusCheckRollup,body
# Collaborateurs (pour distinguer "nos PRs" des externes)
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
```
**Fallback collaborateurs** : si `gh api .../collaborators` échoue (403/404) :
```bash
# Extraire les auteurs des 10 derniers PRs mergés
gh pr list --state merged --limit 10 --json author --jq '.[].author.login' | sort -u
```
Si toujours ambigu, demander à l'utilisateur via `AskUserQuestion`.
Pour chaque PR, récupérer reviews existantes ET fichiers modifiés :
```bash
gh api "repos/{owner}/{repo}/pulls/{num}/reviews" \
--jq '[.[] | .user.login + ":" + .state] | join(", ")'
# Fichiers modifiés (nécessaire pour overlap detection)
gh pr view {num} --json files --jq '[.files[].path] | join(",")'
```
**Note rate-limiting** : la récupération des fichiers est N appels API (1 par PR). Pour repos avec 20+ PRs, prioriser les PRs candidates à l'overlap (même domaine fonctionnel, même auteur).
**Note** : `author` est un objet `{login: "..."}` — toujours extraire `.author.login`.
### Analyse
**Classification taille** :
| Label | Additions |
|-------|-----------|
| XS | < 50 |
| S | 50–200 |
| M | 200–500 |
| L | 500–1000 |
| XL | > 1000 |
Format taille : `+{additions}/-{deletions}, {files} files ({label})`
**Détections** :
- **Overlaps** : comparer les listes de fichiers entre PRs — si >50% de fichiers en commun → cross-reference
- **Clusters** : auteur avec 3+ PRs ouvertes → suggérer ordre de review (plus petite en premier)
- **Staleness** : aucune activité depuis >14j → flag "stale"
- **CI status** : via `statusCheckRollup` → `clean` / `unstable` / `dirty`
- **Reviews** : approved / changes_requested / aucune
**Liens PR ↔ Issues** :
- Scanner le `body` de chaque PR pour `fixes #N`, `closes #N`, `resolves #N` (case-insensitive)
- Si trouvé, afficher dans le tableau : `Fixes #42` dans la colonne Action/Status
**Catégorisation** :
_Nos PRs_ : auteur dans la liste des collaborateurs
_Externes — Prêtes_ : additions ≤ 1000 ET files ≤ 10 ET `mergeable` ≠ `CONFLICTING` ET CI clean/unstable
_Externes — Problématiques_ : un des critères suivants :
- additions > 1000 OU files > 10
- OU `mergeable` == `CONFLICTING` (conflit de merge)
- OU CI dirty (statusCheckRollup contient des échecs)
- OU overlap avec une autre PR ouverte (>50% fichiers communs)
### Output — Tableau de triage
```
## PRs ouvertes ({count})
### Nos PRs
| PR | Titre | Taille | CI | Status |
| -- | ----- | ------ | -- | ------ |
### Externes — Prêtes pour review
| PR | Auteur | Titre | Taille | CI | Reviews | Action |
| -- | ------ | ----- | ------ | -- | ------- | ------ |
### Externes — Problématiques
| PR | Auteur | Titre | Taille | Problème | Action recommandée |
| -- | ------ | ----- | ------ | -------- | ------------------ |
### Résumé
- Quick wins : {PRs XS/S prêtes à merger}
- Risques : {overlaps, tailles XL, CI dirty}
- Clusters : {auteurs avec 3+ PRs}
- Stale : {PRs sans activité >14j}
- Overlaps : {PRs qui touchent les mêmes fichiers}
```
0 PRs → afficher `Aucune PR ouverte.` et terminer.
### Copie automatique
Après affichage du tableau de triage, copier dans le presse-papier :
```bash
pbcopy <<'EOF'
{tableau de triage complet}
EOF
```
Confirmer : `Tableau copié dans le presse-papier.` (FR) / `Triage table copied to clipboard.` (EN)
---
## Phase 2 — Deep Review (opt-in)
### Sélection des PRs
**Si argument passé** :
- `"all"` → toutes les PRs externes
- Numéros (`"42 57"`) → uniquement ces PRs
- Pas d'argument → proposer via `AskUserQuestion`
**Si pas d'argument**, afficher :
```
question: "Quelles PRs voulez-vous reviewer en profondeur ?"
header: "Deep Review"
multiSelect: true
options:
- label: "Toutes les externes"
description: "Review {N} PRs externes avec agents code-reviewer en parallèle"
- label: "Problématiques uniquement"
description: "Focus sur les {M} PRs à risque (CI dirty, trop large, overlaps)"
- label: "Prêtes uniquement"
description: "Review {K} PRs prêtes à merger"
- label: "Passer"
description: "Terminer ici — juste l'audit"
```
**Note sur les drafts** :
- Les PRs en draft sont EXCLUES des options "Toutes les externes" et "Prêtes uniquement"
- Les PRs en draft sont INCLUSES dans "Problématiques uniquement" (car elles nécessitent attention)
- Pour reviewer un draft : taper son numéro explicitement (ex: `42`)
Si "Passer" → fin du workflow.
### Exécution des Reviews
Pour chaque PR sélectionnée, lancer un agent `code-reviewer` via **Task tool en parallèle** :
```
subagent_type: code-reviewer
model: sonnet
prompt: |
Review PR #{num}: "{title}" by @{author}
**Metadata**: +{additions}/-{deletions}, {changedFiles} files ({size_label})
**CI**: {ci_status} | **Reviews**: {existing_reviews} | **Draft**: {isDraft}
**PR Body**:
{body}
**Diff**:
{gh pr diff {num} output}
Apply your security-guardian and backend-architect skills for this review.
Additionally, apply the RTK-specific checklist:
- lazy_static! regex (no inline Regex::new())
- anyhow::Result + .context() (no unwrap())
- Fallback to raw command on filter failure
- Exit code propagation
- Token savings ≥60% in tests with real fixtures
- No async/tokio dependencies
Return structured review:
### Critical Issues 🔴
### Important Issues 🟡
### Suggestions 🟢
### What's Good ✅
Be specific: quote the file:line, explain why it's an issue, suggest the fix.
```
Récupérer le diff via :
```bash
gh pr diff {num}
gh pr view {num} --json body,title,author -q '{body: .body, title: .title, author: .author.login}'
```
Agréger tous les rapports. Afficher un résumé après toutes les reviews.
---
## Phase 3 — Commentaires (validation obligatoire)
### Génération des drafts
Pour chaque PR reviewée, générer un commentaire GitHub en utilisant le template `templates/review-comment.md`.
**Règles** :
- Langue : **anglais** (audience internationale)
- Ton : professionnel, constructif, factuel
- Toujours inclure au moins 1 point positif
- Citer les lignes de code quand pertinent (format `file.rs:42`)
### Affichage et validation
**Afficher TOUS les commentaires draftés** au format :
```
---
### Draft — PR #{num}: {title}
{commentaire complet}
---
```
Puis demander validation via `AskUserQuestion` :
```
question: "Ces commentaires sont prêts. Lesquels voulez-vous poster ?"
header: "Poster"
multiSelect: true
options:
- label: "Tous ({N} commentaires)"
description: "Poster sur toutes les PRs reviewées"
- label: "PR #{x} — {title_truncated}"
description: "Poster uniquement sur cette PR"
- label: "Aucun"
description: "Annuler — ne rien poster"
```
(Générer une option par PR + "Tous" + "Aucun")
### Posting
Pour chaque commentaire validé :
```bash
gh pr comment {num} --body-file - <<'REVIEW_EOF'
{commentaire}
REVIEW_EOF
```
Confirmer chaque post : `✅ Commentaire posté sur PR #{num}: {title}`
Si "Aucun" → `Aucun commentaire posté. Workflow terminé.`
---
## Gestion des cas limites
| Situation | Comportement |
|-----------|--------------|
| 0 PRs ouvertes | `Aucune PR ouverte.` + terminer |
| PR en draft | Indiquer dans tableau, skip pour review sauf si sélectionnée explicitement |
| CI inconnu | Afficher `?` dans colonne CI |
| Review agent timeout | Afficher erreur partielle, continuer avec les autres |
| `gh pr diff` vide | Skip cette PR, notifier l'utilisateur |
| PR très large (>5000 additions) | Avertir : "Review partielle, diff tronqué" |
| Collaborateurs API 403/404 | Fallback sur auteurs des 10 derniers PRs mergés |
---
## Notes
- Toujours dériver owner/repo via `gh repo view`, jamais hardcoder
- Utiliser `gh` CLI (pas `curl` GitHub API) sauf pour la liste des collaborateurs
- `statusCheckRollup` peut être null → traiter comme `?`
- `mergeable` peut être `MERGEABLE`, `CONFLICTING`, ou `UNKNOWN` → traiter `UNKNOWN` comme `?`
- Ne jamais poster sans validation explicite de l'utilisateur dans le chat
- Les commentaires draftés doivent être visibles AVANT tout `gh pr comment`
@@ -0,0 +1,71 @@
# Review Comment Template
Use this template to generate GitHub PR review comments. Fill in each section based on the code-reviewer agent output. Comments are posted in **English** (international audience).
---
## Template
```markdown
## Review
**Scope**: Security, code quality, performance, test coverage, architecture
### Summary
{1–2 sentences: overall assessment. Be direct — what's the main takeaway?}
### Critical Issues 🔴
{List blocking issues that must be fixed before merge. For each:}
{- `file.rs:42` — Description of the problem. Why it matters. Suggested fix.}
{If none: "None found."}
### Important Issues 🟡
{List significant issues that should be fixed. For each:}
{- `file.rs:42` — Description. Why it matters. Suggested fix.}
{If none: "None found."}
### Suggestions 🟢
{List nice-to-haves and minor improvements. For each:}
{- Description. Context. Optional fix.}
{If none: omit this section.}
### What's Good ✅
{Always include at least 1 positive point. Be specific — what works well and why.}
{- Description of what's done right.}
---
*Automated review via [rtk](https://github.com/rtk-ai/rtk) `/pr-triage`*
```
---
## Formatting Rules
**Citation format** : `file.rs:42` or `` `code snippet` `` for inline references
**Issue severity** :
- 🔴 Critical : security vulnerability, data loss risk, broken functionality, test missing for new feature
- 🟡 Important : error handling gap, performance regression, scope creep, missing token savings assertion
- 🟢 Suggestion : naming, DRY opportunity, documentation, style
**RTK-specific checks to mention if relevant** :
- `lazy_static!` for regex (not inline `Regex::new()`)
- `anyhow::Result` + `.context("msg")` (no bare `?`, no `.unwrap()`)
- Fallback to raw command on filter failure
- Exit code propagation (`std::process::exit(code)`)
- Token savings assertion ≥60% in tests
- Real fixtures (not synthetic test data)
- No async/tokio dependencies (startup time)
**Tone** : Professional, constructive, factual. Challenge the code, not the person.
No superlatives ("great", "amazing", "perfect"). No filler ("as mentioned", "it's worth noting").
**Length** : Aim for 200–400 words. Long enough to be useful, short enough to be read.
+9
View File
@@ -72,6 +72,9 @@ jobs:
- name: Build
run: cargo build --release --target ${{ matrix.target }}
env:
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
- name: Package (Unix)
if: matrix.os != 'windows-latest'
@@ -108,6 +111,9 @@ jobs:
- name: Build DEB
run: cargo deb
env:
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
- name: Upload DEB
uses: actions/upload-artifact@v4
@@ -132,6 +138,9 @@ jobs:
- name: Build release
run: cargo build --release
env:
RTK_TELEMETRY_URL: ${{ vars.RTK_TELEMETRY_URL }}
RTK_TELEMETRY_TOKEN: ${{ secrets.RTK_TELEMETRY_TOKEN }}
- name: Generate RPM
run: cargo generate-rpm
+13 -4
View File
@@ -60,10 +60,19 @@ jobs:
exit 1
fi
for cmd in ruff pytest pip "go " golangci; do
if ! grep -q "$cmd" "$HOOK_FILE"; then
echo "❌ Hook missing rewrite for: $cmd"
# Since PR #241, the hook delegates to `rtk rewrite` (single source of truth).
# Command coverage is now in src/discover/registry.rs, not the hook bash script.
if ! grep -q "rtk rewrite" "$HOOK_FILE"; then
echo "❌ Hook does not delegate to 'rtk rewrite'"
exit 1
fi
# Verify all Python/Go commands are covered in the registry
# Since PR #241, constants live in src/discover/rules.rs (extracted from registry.rs)
for cmd in ruff pytest pip golangci; do
if ! grep -qr "\"$cmd\"" src/discover/; then
echo "❌ Registry missing rewrite_prefixes for: $cmd"
exit 1
fi
done
echo "✅ Hook rewrites present for Python/Go commands"
echo "✅ Hook delegates to rtk rewrite, registry covers all Python/Go commands"
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.24.0"
".": "0.27.1"
}
+9 -4
View File
@@ -102,7 +102,7 @@ Claude Code settings.json rtk-rewrite.sh RTK binary
│ Claude never sees the rewrite — it only sees optimized output.
Files:
~/.claude/hooks/rtk-rewrite.sh ← shell script (command detection + rewrite)
~/.claude/hooks/rtk-rewrite.sh ← thin delegator (calls `rtk rewrite`, ~50 lines)
~/.claude/settings.json ← hook registry (PreToolUse registration)
~/.claude/RTK.md ← minimal context hint (10 lines)
```
@@ -273,6 +273,10 @@ GO go_cmd.rs go test/build/vet 75-90% ✓
golangci_cmd.rs golangci-lint 85% ✓
NETWORK wget_cmd.rs wget 85-95% ✓
curl_cmd.rs curl 70% ✓
INFRA aws_cmd.rs aws 80% ✓
psql_cmd.rs psql 75% ✓
DEPENDENCIES deps.rs deps 80-90% ✓
@@ -281,6 +285,7 @@ ENVIRONMENT env_cmd.rs env 60-80% ✓
SYSTEM init.rs init N/A ✓
gain.rs gain N/A ✓
config.rs (internal) N/A ✓
rewrite_cmd.rs rewrite N/A ✓
SHARED utils.rs Helpers N/A ✓
filter.rs Language filters N/A ✓
@@ -288,11 +293,11 @@ SHARED utils.rs Helpers N/A ✓
tee.rs Full output recovery N/A ✓
```
**Total: 51 modules** (33 command modules + 18 infrastructure modules)
**Total: 57 modules** (38 command modules + 19 infrastructure modules)
### Module Count Breakdown
- **Command Modules**: 31 (directly exposed to users)
- **Command Modules**: 34 (directly exposed to users)
- **Infrastructure Modules**: 18 (utils, filter, tracking, tee, config, init, gain, etc.)
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
@@ -1483,4 +1488,4 @@ When implementing a new command, consider:
**Last Updated**: 2026-02-22
**Architecture Version**: 2.2
**rtk Version**: 0.23.0
**rtk Version**: 0.26.0
+95
View File
@@ -5,6 +5,101 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.27.1](https://github.com/rtk-ai/rtk/compare/v0.27.0...v0.27.1) (2026-03-06)
### Bug Fixes
* only rewrite docker compose ps/logs/build, skip unsupported subcommands ([#336](https://github.com/rtk-ai/rtk/issues/336)) ([#363](https://github.com/rtk-ai/rtk/issues/363)) ([dbc9503](https://github.com/rtk-ai/rtk/commit/dbc950395e31b4b0bc48710dc52ad01d4d73f9ba))
* preserve -- separator for cargo commands and silence fallback ([#326](https://github.com/rtk-ai/rtk/issues/326)) ([45f9344](https://github.com/rtk-ai/rtk/commit/45f9344f033d27bc370ff54c4fc0c61e52446076)), closes [#286](https://github.com/rtk-ai/rtk/issues/286) [#287](https://github.com/rtk-ai/rtk/issues/287)
* prettier false positive when not installed ([#221](https://github.com/rtk-ai/rtk/issues/221)) ([#359](https://github.com/rtk-ai/rtk/issues/359)) ([85b0b3e](https://github.com/rtk-ai/rtk/commit/85b0b3eb0bad9cbacdc32d2e9ba525728acd7cbe))
* support git commit -am, --amend and other flags ([#327](https://github.com/rtk-ai/rtk/issues/327)) ([#360](https://github.com/rtk-ai/rtk/issues/360)) ([409aed6](https://github.com/rtk-ai/rtk/commit/409aed6dbcdd7cac2a48ec5655e6f1fd8d5248e3))
## [0.27.0](https://github.com/rtk-ai/rtk/compare/v0.26.0...v0.27.0) (2026-03-05)
### Features
* warn when installed hook is outdated ([#344](https://github.com/rtk-ai/rtk/issues/344)) ([#350](https://github.com/rtk-ai/rtk/issues/350)) ([3141fec](https://github.com/rtk-ai/rtk/commit/3141fecf958af5ae98c232543b913f3ca388254f))
### Bug Fixes
* bugs [#196](https://github.com/rtk-ai/rtk/issues/196) [#344](https://github.com/rtk-ai/rtk/issues/344) [#345](https://github.com/rtk-ai/rtk/issues/345) [#346](https://github.com/rtk-ai/rtk/issues/346) [#347](https://github.com/rtk-ai/rtk/issues/347) — gh --json, hook check, RTK_DISABLED, 2&gt;&1, json TOML ([8953af0](https://github.com/rtk-ai/rtk/commit/8953af0fc06759b37f16743ef383af0a52af2bed))
* RTK_DISABLED ignored, 2&gt;&1 broken, json TOML error ([#345](https://github.com/rtk-ai/rtk/issues/345), [#346](https://github.com/rtk-ai/rtk/issues/346), [#347](https://github.com/rtk-ai/rtk/issues/347)) ([6c13d23](https://github.com/rtk-ai/rtk/commit/6c13d234364d314f53b6698c282a621019635fd6))
* skip rewrite for gh --json/--jq/--template ([#196](https://github.com/rtk-ai/rtk/issues/196)) ([079ee9a](https://github.com/rtk-ai/rtk/commit/079ee9a4ea868ecf4e7beffcbc681ca1ba8b165c))
## [0.26.0](https://github.com/rtk-ai/rtk/compare/v0.25.0...v0.26.0) (2026-03-05)
### Features
* add Claude Code skills for PR and issue triage ([#343](https://github.com/rtk-ai/rtk/issues/343)) ([6ad6ffe](https://github.com/rtk-ai/rtk/commit/6ad6ffeccee9b622013f8e1357b6ca4c94aacb59))
* anonymous telemetry ping (1/day, opt-out) ([#334](https://github.com/rtk-ai/rtk/issues/334)) ([baff6a2](https://github.com/rtk-ai/rtk/commit/baff6a2334b155c0d68f38dba85bd8d6fe9e20af))
### Bug Fixes
* curl JSON size guard ([#297](https://github.com/rtk-ai/rtk/issues/297)) + exclude_commands config ([#243](https://github.com/rtk-ai/rtk/issues/243)) ([#342](https://github.com/rtk-ai/rtk/issues/342)) ([a8d6106](https://github.com/rtk-ai/rtk/commit/a8d6106f736e049013ecb77f0f413167266dd40e))
## [Unreleased]
### Features
* **hooks:** `exclude_commands` config — exclude specific commands from auto-rewrite ([#243](https://github.com/rtk-ai/rtk/issues/243))
### Bug Fixes
* **curl:** skip JSON schema replacement when schema is larger than original payload ([#297](https://github.com/rtk-ai/rtk/issues/297))
## [0.25.0](https://github.com/rtk-ai/rtk/compare/v0.24.0...v0.25.0) (2026-03-05)
### Features
* `rtk rewrite` — single source of truth for LLM hook rewrites ([#241](https://github.com/rtk-ai/rtk/issues/241)) ([f447a3d](https://github.com/rtk-ai/rtk/commit/f447a3d5b136dd5b1df3d5cc4969e29a68ba3f89))
### Bug Fixes
* **find:** accept native find flags (-name, -type, etc.) ([#211](https://github.com/rtk-ai/rtk/issues/211)) ([7ac5bc4](https://github.com/rtk-ai/rtk/commit/7ac5bc4bd3942841cc1abb53399025b4fcae10c9))
## [Unreleased]
### ⚠️ Migration Required
**Hook must be updated after upgrading** (`rtk init --global`).
The Claude Code hook is now a thin delegator: all rewrite logic lives in the
`rtk rewrite` command (single source of truth). The old hook embedded the full
if-else mapping inline — it still works after upgrading, but won't pick up new
commands automatically.
**Upgrade path:**
```bash
cargo install rtk # upgrade binary
rtk init --global # replace old hook with thin delegator
```
Running `rtk init` without `--global` updates the project-level hook only.
Users who skip this step keep the old hook working as before — no immediate
breakage, but future rule additions won't take effect until they migrate.
### Features
* **rewrite**: add `rtk rewrite` command — single source of truth for hook rewrites ([#241](https://github.com/rtk-ai/rtk/pull/241))
- New `src/discover/registry.rs` handles all command → RTK mapping
- Hook reduced to ~50 lines (thin delegator), no duplicate logic
- New commands automatically available in hook without hook file changes
- Supports compound commands (`&&`, `||`, `;`, `|`, `&`) and env prefixes
* **discover**: extract rules/patterns into `src/discover/rules.rs` — adding a command now means editing one file only
* **fix**: add `aws` and `psql` to rewrite registry (were missing despite modules existing since 0.24.0)
### Tests
* +48 regression tests covering all command categories: aws, psql, Python, Go, JS/TS,
compound operators, sudo/env prefixes, registry invariants (607 total, was 559)
## [0.24.0](https://github.com/rtk-ai/rtk/compare/v0.23.0...v0.24.0) (2026-03-04)
+1 -1
View File
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
**Verify correct installation:**
```bash
rtk --version # Should show "rtk 0.23.0" (or newer)
rtk --version # Should show "rtk 0.26.0" (or newer)
rtk gain # Should show token savings stats (NOT "command not found")
```
Generated
+442 -1
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "ahash"
version = "0.8.12"
@@ -94,6 +100,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.10.0"
@@ -225,6 +237,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.6"
@@ -291,6 +312,17 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -331,6 +363,25 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"
[[package]]
name = "flate2"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -407,6 +458,17 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hostname"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link",
]
[[package]]
name = "iana-time-zone"
version = "0.1.64"
@@ -431,6 +493,108 @@ dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"
dependencies = [
"displaydoc",
"potential_utf",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"
[[package]]
name = "icu_properties"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"
dependencies = [
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"
[[package]]
name = "icu_provider"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "ignore"
version = "0.4.25"
@@ -518,6 +682,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
[[package]]
name = "litemap"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
[[package]]
name = "log"
version = "0.4.29"
@@ -530,6 +700,16 @@ version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -557,12 +737,27 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "potential_utf"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"
dependencies = [
"zerovec",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
@@ -627,15 +822,30 @@ version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rtk"
version = "0.24.0"
version = "0.27.1"
dependencies = [
"anyhow",
"chrono",
"clap",
"colored",
"dirs",
"hostname",
"ignore",
"lazy_static",
"regex",
@@ -646,6 +856,7 @@ dependencies = [
"tempfile",
"thiserror",
"toml",
"ureq",
"walkdir",
]
@@ -676,6 +887,41 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.22"
@@ -761,18 +1007,36 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "simd-adler32"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.114"
@@ -784,6 +1048,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tempfile"
version = "3.24.0"
@@ -817,6 +1092,16 @@ dependencies = [
"syn",
]
[[package]]
name = "tinystr"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "toml"
version = "0.8.23"
@@ -870,6 +1155,46 @@ version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
dependencies = [
"base64",
"flate2",
"log",
"once_cell",
"rustls",
"rustls-pki-types",
"url",
"webpki-roots 0.26.11",
]
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -958,6 +1283,24 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.6",
]
[[package]]
name = "webpki-roots"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -1035,6 +1378,15 @@ dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
@@ -1189,6 +1541,35 @@ version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
[[package]]
name = "writeable"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
[[package]]
name = "yoke"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.33"
@@ -1209,6 +1590,66 @@ dependencies = [
"syn",
]
[[package]]
name = "zerofrom"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]]
name = "zerotrie"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.16"
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.24.0"
version = "0.27.1"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
@@ -28,6 +28,8 @@ chrono = "0.4"
thiserror = "1.0"
tempfile = "3"
sha2 = "0.10"
ureq = "2"
hostname = "0.4"
[dev-dependencies]
+16 -1
View File
@@ -150,7 +150,7 @@ rtk init # Creates ./CLAUDE.md with full RTK instructions (137 lines)
### Upgrading from Previous Version
If you previously used `rtk init -g` with the old system (137-line injection):
#### From old 137-line CLAUDE.md injection (pre-0.22)
```bash
rtk init -g # Automatically migrates to hook-first mode
@@ -159,6 +159,21 @@ rtk init -g # Automatically migrates to hook-first mode
# → Adds @RTK.md reference
```
#### From old hook with inline logic (pre-0.24) — ⚠️ Breaking Change
RTK 0.24.0 replaced the inline command-detection hook (~200 lines) with a **thin delegator** that calls `rtk rewrite`. The binary now contains the rewrite logic, so adding new commands no longer requires a hook update.
The old hook still works but won't benefit from new rules added in future releases.
```bash
# Upgrade hook to thin delegator
rtk init --global
# Verify the new hook is active
rtk init --show
# Should show: ✅ Hook: ... (thin delegator, up to date)
```
## Common User Flows
### First-Time User (Recommended)
+14 -2
View File
@@ -22,7 +22,7 @@ rtk filters and compresses command outputs before they reach your LLM context, s
**How to verify you have the correct rtk:**
```bash
rtk --version # Should show "rtk 0.23.0"
rtk --version # Should show "rtk 0.26.0"
rtk gain # Should show token savings stats
```
@@ -103,7 +103,7 @@ cargo install rtk
Download from [rtk-ai/releases](https://github.com/rtk-ai/rtk/releases):
- macOS: `rtk-x86_64-apple-darwin.tar.gz` / `rtk-aarch64-apple-darwin.tar.gz`
- Linux: `rtk-x86_64-unknown-linux-gnu.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
- Linux: `rtk-x86_64-unknown-linux-musl.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz`
- Windows: `rtk-x86_64-pc-windows-msvc.zip`
## Quick Start
@@ -455,6 +455,18 @@ database_path = "/path/to/custom.db"
Priority: `RTK_DB_PATH` env var > `config.toml` > default location.
### Excluding Commands from Auto-Rewrite
By default, the hook rewrites all supported commands automatically. To exclude specific commands (e.g., keep raw `curl` output without schema extraction), add to your config:
**Config file** (`~/.config/rtk/config.toml`, macOS: `~/Library/Application Support/rtk/config.toml`):
```toml
[hooks]
exclude_commands = ["curl", "playwright"]
```
Excluded commands pass through the hook unchanged — no RTK filtering. This survives `rtk init -g` re-runs since the config file is user-owned.
### Tee: Full Output Recovery
When RTK filters command output, LLM agents lose failure details (stack traces, assertion messages) and may re-run the same command 2-3 times. The **tee** feature saves raw output to a file so the agent can read it without re-executing.
+3 -1
View File
@@ -51,6 +51,8 @@ The following files are considered **high-risk** and trigger mandatory 2-reviewe
- **`src/runner.rs`** - Shell command execution engine (primary injection vector)
- **`src/summary.rs`** - Command output aggregation (data exfiltration risk)
- **`src/tracking.rs`** - SQLite database operations (privacy/telemetry concerns)
- **`src/discover/registry.rs`** - Rewrite logic for all commands (command injection risk via rewrite rules)
- **`hooks/rtk-rewrite.sh`** / **`.claude/hooks/rtk-rewrite.sh`** - Thin delegator hook (executes in Claude Code context, intercepts all commands)
### Tier 2: Input Validation
- **`src/pnpm_cmd.rs`** - Package name validation (prevents injection via malicious names)
@@ -212,4 +214,4 @@ Critical vulnerabilities (remote code execution, data exfiltration) may be fast-
---
**Last updated**: 2026-02-02
**Last updated**: 2026-03-05
+30 -197
View File
@@ -1,14 +1,32 @@
#!/bin/bash
# RTK auto-rewrite hook for Claude Code PreToolUse:Bash
# Transparently rewrites raw commands to their rtk equivalents.
# Outputs JSON with updatedInput to modify the command before execution.
#!/usr/bin/env bash
# rtk-hook-version: 2
# RTK Claude Code hook — rewrites commands to use rtk for token savings.
# Requires: rtk >= 0.23.0, jq
#
# This is a thin delegating hook: all rewrite logic lives in `rtk rewrite`,
# which is the single source of truth (src/discover/registry.rs).
# To add or change rewrite rules, edit the Rust registry — not this file.
# Guards: skip silently if dependencies missing
if ! command -v rtk &>/dev/null || ! command -v jq &>/dev/null; then
if ! command -v jq &>/dev/null; then
exit 0
fi
set -euo pipefail
if ! command -v rtk &>/dev/null; then
exit 0
fi
# Version guard: rtk rewrite was added in 0.23.0.
# Older binaries: warn once and exit cleanly (no silent failure).
RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [ -n "$RTK_VERSION" ]; then
MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
# Require >= 0.23.0
if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
exit 0
fi
fi
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
@@ -17,203 +35,18 @@ if [ -z "$CMD" ]; then
exit 0
fi
# Extract the first meaningful command (before pipes, &&, etc.)
# We only rewrite if the FIRST command in a chain matches.
FIRST_CMD="$CMD"
# Delegate all rewrite logic to the Rust binary.
# rtk rewrite exits 1 when there's no rewrite — hook passes through silently.
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || exit 0
# Skip if already using rtk
case "$FIRST_CMD" in
rtk\ *|*/rtk\ *) exit 0 ;;
esac
# Skip commands with heredocs, variable assignments as the whole command, etc.
case "$FIRST_CMD" in
*'<<'*) exit 0 ;;
esac
# Strip leading env var assignments for pattern matching
# e.g., "TEST_SESSION_ID=2 npx playwright test" → match against "npx playwright test"
# but preserve them in the rewritten command for execution.
ENV_PREFIX=$(echo "$FIRST_CMD" | grep -oE '^([A-Za-z_][A-Za-z0-9_]*=[^ ]* +)+' || echo "")
if [ -n "$ENV_PREFIX" ]; then
MATCH_CMD="${FIRST_CMD:${#ENV_PREFIX}}"
CMD_BODY="${CMD:${#ENV_PREFIX}}"
else
MATCH_CMD="$FIRST_CMD"
CMD_BODY="$CMD"
fi
REWRITTEN=""
# --- Git commands ---
if echo "$MATCH_CMD" | grep -qE '^git[[:space:]]'; then
GIT_SUBCMD=$(echo "$MATCH_CMD" | sed -E \
-e 's/^git[[:space:]]+//' \
-e 's/(-C|-c)[[:space:]]+[^[:space:]]+[[:space:]]*//g' \
-e 's/--[a-z-]+=[^[:space:]]+[[:space:]]*//g' \
-e 's/--(no-pager|no-optional-locks|bare|literal-pathspecs)[[:space:]]*//g' \
-e 's/^[[:space:]]+//')
case "$GIT_SUBCMD" in
status|status\ *|diff|diff\ *|log|log\ *|add|add\ *|commit|commit\ *|push|push\ *|pull|pull\ *|branch|branch\ *|fetch|fetch\ *|stash|stash\ *|show|show\ *)
REWRITTEN="${ENV_PREFIX}rtk $CMD_BODY"
;;
esac
# --- GitHub CLI (added: api, release) ---
elif echo "$MATCH_CMD" | grep -qE '^gh[[:space:]]+(pr|issue|run|api|release)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^gh /rtk gh /')"
# --- Cargo ---
elif echo "$MATCH_CMD" | grep -qE '^cargo[[:space:]]'; then
CARGO_SUBCMD=$(echo "$MATCH_CMD" | sed -E 's/^cargo[[:space:]]+(\+[^[:space:]]+[[:space:]]+)?//')
case "$CARGO_SUBCMD" in
test|test\ *|build|build\ *|clippy|clippy\ *|check|check\ *|install|install\ *|fmt|fmt\ *)
REWRITTEN="${ENV_PREFIX}rtk $CMD_BODY"
;;
esac
# --- File operations ---
elif echo "$MATCH_CMD" | grep -qE '^cat[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^cat /rtk read /')"
elif echo "$MATCH_CMD" | grep -qE '^(rg|grep)[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(rg|grep) /rtk grep /')"
elif echo "$MATCH_CMD" | grep -qE '^ls([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^ls/rtk ls/')"
elif echo "$MATCH_CMD" | grep -qE '^tree([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^tree/rtk tree/')"
elif echo "$MATCH_CMD" | grep -qE '^find[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^find /rtk find /')"
elif echo "$MATCH_CMD" | grep -qE '^diff[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^diff /rtk diff /')"
elif echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+'; then
# Transform: head -N file → rtk read file --max-lines N
# Also handle: head --lines=N file
if echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+-[0-9]+[[:space:]]+'; then
LINES=$(echo "$MATCH_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
FILE=$(echo "$MATCH_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
REWRITTEN="${ENV_PREFIX}rtk read $FILE --max-lines $LINES"
elif echo "$MATCH_CMD" | grep -qE '^head[[:space:]]+--lines=[0-9]+[[:space:]]+'; then
LINES=$(echo "$MATCH_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
FILE=$(echo "$MATCH_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
REWRITTEN="${ENV_PREFIX}rtk read $FILE --max-lines $LINES"
fi
# --- JS/TS tooling (added: npm run, npm test, vue-tsc) ---
elif echo "$MATCH_CMD" | grep -qE '^(pnpm[[:space:]]+)?(npx[[:space:]]+)?vitest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(pnpm )?(npx )?vitest( run)?/rtk vitest run/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm test/rtk vitest run/')"
elif echo "$MATCH_CMD" | grep -qE '^npm[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^npm test/rtk npm test/')"
elif echo "$MATCH_CMD" | grep -qE '^npm[[:space:]]+run[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^npm run /rtk npm /')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?vue-tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?vue-tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?tsc([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?tsc/rtk tsc/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+lint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm lint/rtk lint/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?eslint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?eslint/rtk lint/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?prettier([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?prettier/rtk prettier/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?playwright([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?playwright/rtk playwright/')"
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+playwright([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm playwright/rtk playwright/')"
elif echo "$MATCH_CMD" | grep -qE '^(npx[[:space:]]+)?prisma([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed -E 's/^(npx )?prisma/rtk prisma/')"
# --- Containers (added: docker compose, docker run/build/exec, kubectl describe/apply) ---
elif echo "$MATCH_CMD" | grep -qE '^docker[[:space:]]'; then
if echo "$MATCH_CMD" | grep -qE '^docker[[:space:]]+compose([[:space:]]|$)'; then
COMPOSE_SUBCMD=$(echo "$MATCH_CMD" | sed -E 's/^docker[[:space:]]+compose[[:space:]]*//')
case "$COMPOSE_SUBCMD" in
ps|ps\ *|logs|logs\ *|build|build\ *)
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^docker /rtk docker /')"
;;
esac
else
DOCKER_SUBCMD=$(echo "$MATCH_CMD" | sed -E \
-e 's/^docker[[:space:]]+//' \
-e 's/(-H|--context|--config)[[:space:]]+[^[:space:]]+[[:space:]]*//g' \
-e 's/--[a-z-]+=[^[:space:]]+[[:space:]]*//g' \
-e 's/^[[:space:]]+//')
case "$DOCKER_SUBCMD" in
ps|ps\ *|images|images\ *|logs|logs\ *|run|run\ *|build|build\ *|exec|exec\ *)
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^docker /rtk docker /')"
;;
esac
fi
elif echo "$MATCH_CMD" | grep -qE '^kubectl[[:space:]]'; then
KUBE_SUBCMD=$(echo "$MATCH_CMD" | sed -E \
-e 's/^kubectl[[:space:]]+//' \
-e 's/(--context|--kubeconfig|--namespace|-n)[[:space:]]+[^[:space:]]+[[:space:]]*//g' \
-e 's/--[a-z-]+=[^[:space:]]+[[:space:]]*//g' \
-e 's/^[[:space:]]+//')
case "$KUBE_SUBCMD" in
get|get\ *|logs|logs\ *|describe|describe\ *|apply|apply\ *)
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^kubectl /rtk kubectl /')"
;;
esac
# --- Network ---
elif echo "$MATCH_CMD" | grep -qE '^curl[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^curl /rtk curl /')"
elif echo "$MATCH_CMD" | grep -qE '^wget[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^wget /rtk wget /')"
# --- pnpm package management ---
elif echo "$MATCH_CMD" | grep -qE '^pnpm[[:space:]]+(list|ls|outdated)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pnpm /rtk pnpm /')"
# --- Python tooling ---
elif echo "$MATCH_CMD" | grep -qE '^pytest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pytest/rtk pytest/')"
elif echo "$MATCH_CMD" | grep -qE '^python[[:space:]]+-m[[:space:]]+pytest([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^python -m pytest/rtk pytest/')"
elif echo "$MATCH_CMD" | grep -qE '^ruff[[:space:]]+(check|format)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^ruff /rtk ruff /')"
elif echo "$MATCH_CMD" | grep -qE '^pip[[:space:]]+(list|outdated|install|show)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^pip /rtk pip /')"
elif echo "$MATCH_CMD" | grep -qE '^uv[[:space:]]+pip[[:space:]]+(list|outdated|install|show)([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^uv pip /rtk pip /')"
elif echo "$MATCH_CMD" | grep -qE '^mypy([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^mypy/rtk mypy/')"
elif echo "$MATCH_CMD" | grep -qE '^python[[:space:]]+-m[[:space:]]+mypy([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^python -m mypy/rtk mypy/')"
# --- Go tooling ---
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+test([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go test/rtk go test/')"
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+build([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go build/rtk go build/')"
elif echo "$MATCH_CMD" | grep -qE '^go[[:space:]]+vet([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^go vet/rtk go vet/')"
elif echo "$MATCH_CMD" | grep -qE '^golangci-lint([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^golangci-lint/rtk golangci-lint/')"
# --- AWS CLI ---
elif echo "$MATCH_CMD" | grep -qE '^aws[[:space:]]+'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^aws /rtk aws /')"
# --- PostgreSQL ---
elif echo "$MATCH_CMD" | grep -qE '^psql([[:space:]]|$)'; then
REWRITTEN="${ENV_PREFIX}$(echo "$CMD_BODY" | sed 's/^psql/rtk psql/')"
fi
# If no rewrite needed, approve as-is
if [ -z "$REWRITTEN" ]; then
# No change — nothing to do.
if [ "$CMD" = "$REWRITTEN" ]; then
exit 0
fi
# Build the updated tool_input with all original fields preserved, only command changed
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
# Output the rewrite instruction
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
+38
View File
@@ -239,6 +239,44 @@ test_rewrite "kubectl apply -f deploy.yaml" \
echo ""
# ---- SECTION 3b: RTK_DISABLED and redirect fixes (#345, #346) ----
echo "--- RTK_DISABLED (#345) ---"
test_rewrite "RTK_DISABLED=1 git status (no rewrite)" \
"RTK_DISABLED=1 git status" \
""
test_rewrite "RTK_DISABLED=1 cargo test (no rewrite)" \
"RTK_DISABLED=1 cargo test" \
""
test_rewrite "FOO=1 RTK_DISABLED=1 git status (no rewrite)" \
"FOO=1 RTK_DISABLED=1 git status" \
""
echo ""
echo "--- Redirect operators (#346) ---"
test_rewrite "cargo test 2>&1 | head" \
"cargo test 2>&1 | head" \
"rtk cargo test 2>&1 | head"
test_rewrite "cargo test 2>&1" \
"cargo test 2>&1" \
"rtk cargo test 2>&1"
test_rewrite "cargo test &>/dev/null" \
"cargo test &>/dev/null" \
"rtk cargo test &>/dev/null"
# Note: the bash hook rewrites only the first command segment (sed-based);
# full compound rewriting (both sides of &) is handled by `rtk rewrite` (Rust).
# The critical behavior tested here: `&` after `cargo test` is NOT mistaken for
# a redirect — the hook still rewrites cargo test, no crash.
test_rewrite "cargo test & git status (bash hook rewrites first segment only)" \
"cargo test & git status" \
"rtk cargo test & git status"
echo ""
# ---- SECTION 4: Vitest edge case (fixed double "run" bug) ----
echo "--- Vitest run dedup ---"
test_rewrite "vitest (no args)" \
+60 -6
View File
@@ -1,8 +1,16 @@
#!/bin/bash
set -e
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
BENCH_DIR="./scripts/benchmark"
# Use local release build if available, otherwise fall back to installed rtk
if [ -f "./target/release/rtk" ]; then
RTK="$(cd "$(dirname ./target/release/rtk)" && pwd)/$(basename ./target/release/rtk)"
elif command -v rtk &> /dev/null; then
RTK="$(command -v rtk)"
else
echo "Error: rtk not found. Run 'cargo build --release' or install rtk."
exit 1
fi
BENCH_DIR="$(pwd)/scripts/benchmark"
# Mode local : générer les fichiers debug
if [ -z "$CI" ]; then
@@ -258,6 +266,50 @@ section "summary"
bench "summary cargo --help" "cargo --help" "$RTK summary cargo --help"
bench "summary rustc --help" "rustc --help 2>/dev/null || echo 'rustc not found'" "$RTK summary rustc --help"
# ===================
# cargo
# ===================
section "cargo"
bench "cargo build" "cargo build 2>&1 || true" "$RTK cargo build"
bench "cargo test" "cargo test 2>&1 || true" "$RTK cargo test"
bench "cargo clippy" "cargo clippy 2>&1 || true" "$RTK cargo clippy"
bench "cargo check" "cargo check 2>&1 || true" "$RTK cargo check"
# ===================
# diff
# ===================
section "diff"
bench "diff" "diff Cargo.toml LICENSE 2>&1 || true" "$RTK diff Cargo.toml LICENSE"
# ===================
# smart
# ===================
section "smart"
bench "smart main.rs" "cat src/main.rs" "$RTK smart src/main.rs"
# ===================
# wc
# ===================
section "wc"
bench "wc" "wc Cargo.toml src/main.rs" "$RTK wc Cargo.toml src/main.rs"
# ===================
# curl
# ===================
section "curl"
if command -v curl &> /dev/null; then
bench "curl json" "curl -s https://httpbin.org/json" "$RTK curl https://httpbin.org/json"
bench "curl text" "curl -s https://httpbin.org/robots.txt" "$RTK curl https://httpbin.org/robots.txt"
fi
# ===================
# wget
# ===================
if command -v wget &> /dev/null; then
section "wget"
bench "wget" "wget -qO- https://httpbin.org/robots.txt" "$RTK wget https://httpbin.org/robots.txt -O"
fi
# ===================
# Modern JavaScript Stack (skip si pas de package.json)
# ===================
@@ -381,8 +433,8 @@ def test_process_data_none():
assert process_data(None) == []
PYEOF
bench "ruff check" "ruff check . 2>&1 || true" "$RTK test ruff check ."
bench "pytest" "pytest -v 2>&1 || true" "$RTK test pytest -v"
bench "ruff check" "ruff check . 2>&1 || true" "$RTK ruff check ."
bench "pytest" "pytest -v 2>&1 || true" "$RTK pytest -v"
cd - > /dev/null
rm -rf "$PYTHON_FIXTURE"
@@ -445,8 +497,10 @@ func TestMultiply(t *testing.T) {
}
GOEOF
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK test golangci-lint run"
bench "go test" "go test -v 2>&1 || true" "$RTK test go test -v"
bench "golangci-lint" "golangci-lint run 2>&1 || true" "$RTK golangci-lint run"
bench "go test" "go test -v 2>&1 || true" "$RTK go test -v"
bench "go build" "go build ./... 2>&1 || true" "$RTK go build ./..."
bench "go vet" "go vet ./... 2>&1 || true" "$RTK go vet ./..."
cd - > /dev/null
rm -rf "$GO_FIXTURE"
+98
View File
@@ -68,6 +68,19 @@ assert_exit_ok() {
fi
}
assert_fails() {
local name="$1"
shift
if "$@" >/dev/null 2>&1; then
FAIL=$((FAIL + 1))
FAILURES+=("$name (expected failure, got success)")
printf " ${RED}FAIL${NC} %s (expected failure)\n" "$name"
else
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s\n" "$name"
fi
}
assert_help() {
local name="$1"
shift
@@ -433,6 +446,91 @@ section "Learn"
assert_ok "rtk learn --help" rtk learn --help
assert_ok "rtk learn (no sessions)" rtk learn --since 0 2>&1 || true
# ── 32. Rewrite ───────────────────────────────────────
section "Rewrite"
assert_contains "rewrite git status" "rtk git status" rtk rewrite "git status"
assert_contains "rewrite cargo test" "rtk cargo test" rtk rewrite "cargo test"
assert_contains "rewrite compound &&" "rtk git status" rtk rewrite "git status && cargo test"
assert_contains "rewrite pipe preserves" "| head" rtk rewrite "git log | head"
section "Rewrite (#345: RTK_DISABLED skip)"
assert_fails "rewrite RTK_DISABLED=1 skip" rtk rewrite "RTK_DISABLED=1 git status"
assert_fails "rewrite env RTK_DISABLED skip" rtk rewrite "FOO=1 RTK_DISABLED=1 cargo test"
section "Rewrite (#346: 2>&1 preserved)"
assert_contains "rewrite 2>&1 preserved" "2>&1" rtk rewrite "cargo test 2>&1 | head"
section "Rewrite (#196: gh --json skip)"
assert_fails "rewrite gh --json skip" rtk rewrite "gh pr list --json number"
assert_fails "rewrite gh --jq skip" rtk rewrite "gh api /repos --jq .name"
assert_fails "rewrite gh --template skip" rtk rewrite "gh pr view 1 --template '{{.title}}'"
assert_contains "rewrite gh normal works" "rtk gh pr list" rtk rewrite "gh pr list"
# ── 33. Verify ────────────────────────────────────────
section "Verify"
assert_ok "rtk verify" rtk verify
# ── 34. Proxy ─────────────────────────────────────────
section "Proxy"
assert_ok "rtk proxy echo hello" rtk proxy echo hello
assert_contains "rtk proxy passthrough" "hello" rtk proxy echo hello
# ── 35. Discover ──────────────────────────────────────
section "Discover"
assert_ok "rtk discover" rtk discover
# ── 36. Diff ──────────────────────────────────────────
section "Diff"
assert_ok "rtk diff two files" rtk diff Cargo.toml LICENSE
# ── 37. Wc ────────────────────────────────────────────
section "Wc"
assert_ok "rtk wc Cargo.toml" rtk wc Cargo.toml
# ── 38. Smart ─────────────────────────────────────────
section "Smart"
assert_ok "rtk smart src/main.rs" rtk smart src/main.rs
# ── 39. Json edge cases ──────────────────────────────
section "Json (edge cases)"
assert_fails "rtk json on TOML (#347)" rtk json Cargo.toml
# ── 40. Docker (conditional) ─────────────────────────
section "Docker (conditional)"
if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
assert_ok "rtk docker ps" rtk docker ps
assert_ok "rtk docker images" rtk docker images
else
skip_test "rtk docker" "docker not running"
fi
# ── 41. Hook check ───────────────────────────────────
section "Hook check (#344)"
assert_contains "rtk init --show hook version" "version" rtk init --show
# ══════════════════════════════════════════════════════
# Report
# ══════════════════════════════════════════════════════
+109 -4
View File
@@ -27,6 +27,40 @@ pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<()> {
}
}
/// Reconstruct args with `--` separator preserved from the original command line.
/// Clap strips `--` from parsed args, but cargo subcommands need it to separate
/// their own flags from test runner flags (e.g. `cargo test -- --nocapture`).
fn restore_double_dash(args: &[String]) -> Vec<String> {
let raw_args: Vec<String> = std::env::args().collect();
restore_double_dash_with_raw(args, &raw_args)
}
/// Testable version that takes raw_args explicitly.
fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<String> {
if args.is_empty() {
return args.to_vec();
}
// Find `--` in the original command line
let sep_pos = match raw_args.iter().position(|a| a == "--") {
Some(pos) => pos,
None => return args.to_vec(),
};
// Count how many of our parsed args appeared before `--` in the original.
// Args before `--` are positional (e.g. test name), args after are flags.
let args_before_sep = raw_args[..sep_pos]
.iter()
.filter(|a| args.contains(a))
.count();
let mut result = Vec::with_capacity(args.len() + 1);
result.extend_from_slice(&args[..args_before_sep]);
result.push("--".to_string());
result.extend_from_slice(&args[args_before_sep..]);
result
}
/// Generic cargo command runner with filtering
fn run_cargo_filtered<F>(subcommand: &str, args: &[String], verbose: u8, filter_fn: F) -> Result<()>
where
@@ -36,12 +70,14 @@ where
let mut cmd = Command::new("cargo");
cmd.arg(subcommand);
for arg in args {
let restored_args = restore_double_dash(args);
for arg in &restored_args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: cargo {} {}", subcommand, args.join(" "));
eprintln!("Running: cargo {} {}", subcommand, restored_args.join(" "));
}
let output = cmd
@@ -65,8 +101,8 @@ where
}
timer.track(
&format!("cargo {} {}", subcommand, args.join(" ")),
&format!("rtk cargo {} {}", subcommand, args.join(" ")),
&format!("cargo {} {}", subcommand, restored_args.join(" ")),
&format!("rtk cargo {} {}", subcommand, restored_args.join(" ")),
&raw,
&filtered,
);
@@ -950,6 +986,75 @@ pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
mod tests {
use super::*;
#[test]
fn test_restore_double_dash_with_separator() {
// rtk cargo test -- --nocapture → clap gives ["--nocapture"]
let args: Vec<String> = vec!["--nocapture".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"--".into(),
"--nocapture".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["--", "--nocapture"]);
}
#[test]
fn test_restore_double_dash_with_test_name() {
// rtk cargo test my_test -- --nocapture → clap gives ["my_test", "--nocapture"]
let args: Vec<String> = vec!["my_test".into(), "--nocapture".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"my_test".into(),
"--".into(),
"--nocapture".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["my_test", "--", "--nocapture"]);
}
#[test]
fn test_restore_double_dash_without_separator() {
// rtk cargo test my_test → no --, args unchanged
let args: Vec<String> = vec!["my_test".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"test".into(),
"my_test".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["my_test"]);
}
#[test]
fn test_restore_double_dash_empty_args() {
let args: Vec<String> = vec![];
let raw = vec!["rtk".into(), "cargo".into(), "test".into()];
let result = restore_double_dash_with_raw(&args, &raw);
assert!(result.is_empty());
}
#[test]
fn test_restore_double_dash_clippy() {
// rtk cargo clippy -- -D warnings → clap gives ["-D", "warnings"]
let args: Vec<String> = vec!["-D".into(), "warnings".into()];
let raw = vec![
"rtk".into(),
"cargo".into(),
"clippy".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
assert_eq!(result, vec!["--", "-D", "warnings"]);
}
#[test]
fn test_filter_cargo_build_success() {
let output = r#" Compiling libc v0.2.153
+60
View File
@@ -12,6 +12,18 @@ pub struct Config {
pub filters: FilterConfig,
#[serde(default)]
pub tee: crate::tee::TeeConfig,
#[serde(default)]
pub telemetry: TelemetryConfig,
#[serde(default)]
pub hooks: HooksConfig,
}
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct HooksConfig {
/// Commands to exclude from auto-rewrite (e.g. ["curl", "playwright"]).
/// Survives `rtk init -g` re-runs since config.toml is user-owned.
#[serde(default)]
pub exclude_commands: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -71,6 +83,22 @@ impl Default for FilterConfig {
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TelemetryConfig {
pub enabled: bool,
}
impl Default for TelemetryConfig {
fn default() -> Self {
Self { enabled: true }
}
}
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
pub fn telemetry_enabled() -> Option<bool> {
Config::load().ok().map(|c| c.telemetry.enabled)
}
impl Config {
pub fn load() -> Result<Self> {
let path = get_config_path()?;
@@ -125,3 +153,35 @@ pub fn show_config() -> Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hooks_config_deserialize() {
let toml = r#"
[hooks]
exclude_commands = ["curl", "gh"]
"#;
let config: Config = toml::from_str(toml).expect("valid toml");
assert_eq!(config.hooks.exclude_commands, vec!["curl", "gh"]);
}
#[test]
fn test_hooks_config_default_empty() {
let config = Config::default();
assert!(config.hooks.exclude_commands.is_empty());
}
#[test]
fn test_config_without_hooks_section_is_valid() {
let toml = r#"
[tracking]
enabled = true
history_days = 90
"#;
let config: Config = toml::from_str(toml).expect("valid toml");
assert!(config.hooks.exclude_commands.is_empty());
}
}
+16 -2
View File
@@ -55,7 +55,10 @@ fn filter_curl_output(output: &str) -> String {
&& (trimmed.ends_with('}') || trimmed.ends_with(']'))
{
if let Ok(schema) = json_cmd::filter_json_string(trimmed, 5) {
return schema;
// Only use schema if it's actually shorter than the original (#297)
if schema.len() <= trimmed.len() {
return schema;
}
}
}
@@ -86,7 +89,8 @@ mod tests {
#[test]
fn test_filter_curl_json() {
let output = r#"{"name": "test", "count": 42, "items": [1, 2, 3]}"#;
// Large JSON where schema is shorter than original — schema should be returned
let output = r#"{"name": "a very long user name here", "count": 42, "items": [1, 2, 3], "description": "a very long description that takes up many characters in the original JSON payload", "status": "active", "url": "https://example.com/api/v1/users/123"}"#;
let result = filter_curl_output(output);
assert!(result.contains("name"));
assert!(result.contains("string"));
@@ -108,6 +112,16 @@ mod tests {
assert!(result.contains("plain text"));
}
#[test]
fn test_filter_curl_json_small_returns_original() {
// Small JSON where schema would be larger than original (issue #297)
let output = r#"{"r2Ready":true,"status":"ok"}"#;
let result = filter_curl_output(output);
// Schema would be "{\n r2Ready: bool,\n status: string\n}" which is longer
// Should return the original JSON unchanged
assert_eq!(result.trim(), output.trim());
}
#[test]
fn test_filter_curl_long_output() {
let lines: Vec<String> = (0..50).map(|i| format!("Line {}", i)).collect();
+1
View File
@@ -1,6 +1,7 @@
pub mod provider;
pub mod registry;
mod report;
pub mod rules;
use anyhow::Result;
use std::collections::HashMap;
+1317 -253
View File
File diff suppressed because it is too large. Load diff
+377
View File
@@ -0,0 +1,377 @@
use super::report::RtkStatus;
/// A rule mapping a shell command pattern to its RTK equivalent.
pub struct RtkRule {
pub rtk_cmd: &'static str,
/// Original command prefixes to replace with rtk_cmd (longest first for correct matching).
pub rewrite_prefixes: &'static [&'static str],
pub category: &'static str,
pub savings_pct: f64,
pub subcmd_savings: &'static [(&'static str, f64)],
pub subcmd_status: &'static [(&'static str, RtkStatus)],
}
// Patterns ordered to match RULES indices exactly.
pub const PATTERNS: &[&str] = &[
r"^git\s+(status|log|diff|show|add|commit|push|pull|branch|fetch|stash|worktree)",
r"^gh\s+(pr|issue|run|repo|api|release)",
r"^cargo\s+(build|test|clippy|check|fmt|install)",
r"^pnpm\s+(list|ls|outdated|install)",
r"^npm\s+(run|exec)",
r"^npx\s+",
r"^(cat|head|tail)\s+",
r"^(rg|grep)\s+",
r"^ls(\s|$)",
r"^find\s+",
r"^(npx\s+|pnpm\s+)?tsc(\s|$)",
r"^(npx\s+|pnpm\s+)?(eslint|biome|lint)(\s|$)",
r"^(npx\s+|pnpm\s+)?prettier",
r"^(npx\s+|pnpm\s+)?next\s+build",
r"^(pnpm\s+|npx\s+)?(vitest|jest|test)(\s|$)",
r"^(npx\s+|pnpm\s+)?playwright",
r"^(npx\s+|pnpm\s+)?prisma",
r"^docker\s+(ps|images|logs|run|exec|build|compose\s+(ps|logs|build))",
r"^kubectl\s+(get|logs|describe|apply)",
r"^tree(\s|$)",
r"^diff\s+",
r"^curl\s+",
r"^wget\s+",
r"^(python3?\s+-m\s+)?mypy(\s|$)",
// Python tooling
r"^ruff\s+(check|format)",
r"^(python\s+-m\s+)?pytest(\s|$)",
r"^(pip3?|uv\s+pip)\s+(list|outdated|install)",
// Go tooling
r"^go\s+(test|build|vet)",
r"^golangci-lint(\s|$)",
// AWS CLI
r"^aws\s+",
// PostgreSQL
r"^psql(\s|$)",
];
pub const RULES: &[RtkRule] = &[
RtkRule {
rtk_cmd: "rtk git",
rewrite_prefixes: &["git"],
category: "Git",
savings_pct: 70.0,
subcmd_savings: &[
("diff", 80.0),
("show", 80.0),
("add", 59.0),
("commit", 59.0),
],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk gh",
rewrite_prefixes: &["gh"],
category: "GitHub",
savings_pct: 82.0,
subcmd_savings: &[("pr", 87.0), ("run", 82.0), ("issue", 80.0)],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk cargo",
rewrite_prefixes: &["cargo"],
category: "Cargo",
savings_pct: 80.0,
subcmd_savings: &[("test", 90.0), ("check", 80.0)],
subcmd_status: &[("fmt", RtkStatus::Passthrough)],
},
RtkRule {
rtk_cmd: "rtk pnpm",
rewrite_prefixes: &["pnpm"],
category: "PackageManager",
savings_pct: 80.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk npm",
rewrite_prefixes: &["npm"],
category: "PackageManager",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk npx",
rewrite_prefixes: &["npx"],
category: "PackageManager",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk read",
rewrite_prefixes: &["cat", "head", "tail"],
category: "Files",
savings_pct: 60.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk grep",
rewrite_prefixes: &["rg", "grep"],
category: "Files",
savings_pct: 75.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk ls",
rewrite_prefixes: &["ls"],
category: "Files",
savings_pct: 65.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk find",
rewrite_prefixes: &["find"],
category: "Files",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
// Longest prefixes first for correct matching
rtk_cmd: "rtk tsc",
rewrite_prefixes: &["pnpm tsc", "npx tsc", "tsc"],
category: "Build",
savings_pct: 83.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk lint",
rewrite_prefixes: &[
"npx eslint",
"pnpm lint",
"npx biome",
"eslint",
"biome",
"lint",
],
category: "Build",
savings_pct: 84.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk prettier",
rewrite_prefixes: &["npx prettier", "pnpm prettier", "prettier"],
category: "Build",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
// "next build" is stripped to "rtk next" — the build subcommand is internal
rtk_cmd: "rtk next",
rewrite_prefixes: &["npx next build", "pnpm next build", "next build"],
category: "Build",
savings_pct: 87.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk vitest",
rewrite_prefixes: &["pnpm vitest", "npx vitest", "vitest", "jest"],
category: "Tests",
savings_pct: 99.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk playwright",
rewrite_prefixes: &["npx playwright", "pnpm playwright", "playwright"],
category: "Tests",
savings_pct: 94.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk prisma",
rewrite_prefixes: &["npx prisma", "pnpm prisma", "prisma"],
category: "Build",
savings_pct: 88.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk docker",
rewrite_prefixes: &["docker"],
category: "Infra",
savings_pct: 85.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk kubectl",
rewrite_prefixes: &["kubectl"],
category: "Infra",
savings_pct: 85.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk tree",
rewrite_prefixes: &["tree"],
category: "Files",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk diff",
rewrite_prefixes: &["diff"],
category: "Files",
savings_pct: 60.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk curl",
rewrite_prefixes: &["curl"],
category: "Network",
savings_pct: 70.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk wget",
rewrite_prefixes: &["wget"],
category: "Network",
savings_pct: 65.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk mypy",
rewrite_prefixes: &["python3 -m mypy", "python -m mypy", "mypy"],
category: "Build",
savings_pct: 80.0,
subcmd_savings: &[],
subcmd_status: &[],
},
// Python tooling
RtkRule {
rtk_cmd: "rtk ruff",
rewrite_prefixes: &["ruff"],
category: "Python",
savings_pct: 80.0,
subcmd_savings: &[("check", 80.0), ("format", 75.0)],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk pytest",
rewrite_prefixes: &["python -m pytest", "pytest"],
category: "Python",
savings_pct: 90.0,
subcmd_savings: &[],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk pip",
rewrite_prefixes: &["pip3", "pip", "uv pip"],
category: "Python",
savings_pct: 75.0,
subcmd_savings: &[("list", 75.0), ("outdated", 80.0)],
subcmd_status: &[],
},
// Go tooling
RtkRule {
rtk_cmd: "rtk go",
rewrite_prefixes: &["go"],
category: "Go",
savings_pct: 85.0,
subcmd_savings: &[("test", 90.0), ("build", 80.0), ("vet", 75.0)],
subcmd_status: &[],
},
RtkRule {
rtk_cmd: "rtk golangci-lint",
rewrite_prefixes: &["golangci-lint", "golangci"],
category: "Go",
savings_pct: 85.0,
subcmd_savings: &[],
subcmd_status: &[],
},
// AWS CLI
RtkRule {
rtk_cmd: "rtk aws",
rewrite_prefixes: &["aws"],
category: "Infra",
savings_pct: 80.0,
subcmd_savings: &[],
subcmd_status: &[],
},
// PostgreSQL
RtkRule {
rtk_cmd: "rtk psql",
rewrite_prefixes: &["psql"],
category: "Infra",
savings_pct: 75.0,
subcmd_savings: &[],
subcmd_status: &[],
},
];
/// Commands to ignore (shell builtins, trivial, already rtk).
pub const IGNORED_PREFIXES: &[&str] = &[
"cd ",
"cd\t",
"echo ",
"printf ",
"export ",
"source ",
"mkdir ",
"rm ",
"mv ",
"cp ",
"chmod ",
"chown ",
"touch ",
"which ",
"type ",
"command ",
"test ",
"true",
"false",
"sleep ",
"wait",
"kill ",
"set ",
"unset ",
"wc ",
"sort ",
"uniq ",
"tr ",
"cut ",
"awk ",
"sed ",
"python3 -c",
"python -c",
"node -e",
"ruby -e",
"rtk ",
"pwd",
"bash ",
"sh ",
"then\n",
"then ",
"else\n",
"else ",
"do\n",
"do ",
"for ",
"while ",
"if ",
"case ",
];
pub const IGNORED_EXACT: &[&str] = &[
"cd", "echo", "true", "false", "wait", "pwd", "bash", "sh", "fi", "done",
];
+318 -11
View File
@@ -1,5 +1,5 @@
use crate::tracking;
use anyhow::Result;
use anyhow::{Context, Result};
use ignore::WalkBuilder;
use std::collections::HashMap;
use std::path::Path;
@@ -23,11 +23,178 @@ fn glob_match_inner(pat: &[u8], name: &[u8]) -> bool {
}
}
/// Parsed arguments from either native find or RTK find syntax.
#[derive(Debug)]
struct FindArgs {
pattern: String,
path: String,
max_results: usize,
max_depth: Option<usize>,
file_type: String,
case_insensitive: bool,
}
impl Default for FindArgs {
fn default() -> Self {
Self {
pattern: "*".to_string(),
path: ".".to_string(),
max_results: 50,
max_depth: None,
file_type: "f".to_string(),
case_insensitive: false,
}
}
}
/// Consume the next argument from `args` at position `i`, advancing the index.
/// Returns `None` if `i` is past the end of `args`.
fn next_arg(args: &[String], i: &mut usize) -> Option<String> {
*i += 1;
args.get(*i).cloned()
}
/// Check if args contain native find flags (-name, -type, -maxdepth, etc.)
fn has_native_find_flags(args: &[String]) -> bool {
args.iter()
.any(|a| a == "-name" || a == "-type" || a == "-maxdepth" || a == "-iname")
}
/// Native find flags that RTK cannot handle correctly.
/// These involve compound predicates, actions, or semantics we don't support.
const UNSUPPORTED_FIND_FLAGS: &[&str] = &[
"-not", "!", "-or", "-o", "-and", "-a", "-exec", "-execdir", "-delete", "-print0", "-newer",
"-perm", "-size", "-mtime", "-mmin", "-atime", "-amin", "-ctime", "-cmin", "-empty", "-link",
"-regex", "-iregex",
];
fn has_unsupported_find_flags(args: &[String]) -> bool {
args.iter()
.any(|a| UNSUPPORTED_FIND_FLAGS.contains(&a.as_str()))
}
/// Parse arguments from raw args vec, supporting both native find and RTK syntax.
///
/// Native find syntax: `find . -name "*.rs" -type f -maxdepth 3`
/// RTK syntax: `find *.rs [path] [-m max] [-t type]`
fn parse_find_args(args: &[String]) -> Result<FindArgs> {
if args.is_empty() {
return Ok(FindArgs::default());
}
if has_unsupported_find_flags(args) {
anyhow::bail!(
"rtk find does not support compound predicates or actions (e.g. -not, -exec). Use `find` directly."
);
}
if has_native_find_flags(args) {
parse_native_find_args(args)
} else {
parse_rtk_find_args(args)
}
}
/// Parse native find syntax: `find [path] -name "*.rs" -type f -maxdepth 3`
fn parse_native_find_args(args: &[String]) -> Result<FindArgs> {
let mut parsed = FindArgs::default();
let mut i = 0;
// First non-flag argument is the path (standard find behavior)
if !args[0].starts_with('-') {
parsed.path = args[0].clone();
i = 1;
}
while i < args.len() {
match args[i].as_str() {
"-name" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.pattern = val;
}
}
"-iname" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.pattern = val;
parsed.case_insensitive = true;
}
}
"-type" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.file_type = val;
}
}
"-maxdepth" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.max_depth = Some(val.parse().context("invalid -maxdepth value")?);
}
}
flag if flag.starts_with('-') => {
eprintln!("rtk find: unknown flag '{}', ignored", flag);
}
_ => {}
}
i += 1;
}
Ok(parsed)
}
/// Parse RTK syntax: `find <pattern> [path] [-m max] [-t type]`
fn parse_rtk_find_args(args: &[String]) -> Result<FindArgs> {
let mut parsed = FindArgs {
pattern: args[0].clone(),
..FindArgs::default()
};
let mut i = 1;
// Second positional arg (if not a flag) is the path
if i < args.len() && !args[i].starts_with('-') {
parsed.path = args[i].clone();
i += 1;
}
while i < args.len() {
match args[i].as_str() {
"-m" | "--max" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.max_results = val.parse().context("invalid --max value")?;
}
}
"-t" | "--file-type" => {
if let Some(val) = next_arg(args, &mut i) {
parsed.file_type = val;
}
}
_ => {}
}
i += 1;
}
Ok(parsed)
}
/// Entry point from main.rs — parses raw args then delegates to run().
pub fn run_from_args(args: &[String], verbose: u8) -> Result<()> {
let parsed = parse_find_args(args)?;
run(
&parsed.pattern,
&parsed.path,
parsed.max_results,
parsed.max_depth,
&parsed.file_type,
parsed.case_insensitive,
verbose,
)
}
pub fn run(
pattern: &str,
path: &str,
max_results: usize,
max_depth: Option<usize>,
file_type: &str,
case_insensitive: bool,
verbose: u8,
) -> Result<()> {
let timer = tracking::TimedExecution::start();
@@ -41,12 +208,16 @@ pub fn run(
let want_dirs = file_type == "d";
let walker = WalkBuilder::new(path)
let mut builder = WalkBuilder::new(path);
builder
.hidden(true) // skip hidden files/dirs
.git_ignore(true) // respect .gitignore
.git_global(true)
.git_exclude(true)
.build();
.git_exclude(true);
if let Some(depth) = max_depth {
builder.max_depth(Some(depth));
}
let walker = builder.build();
let mut files: Vec<String> = Vec::new();
@@ -57,7 +228,7 @@ pub fn run(
};
let ft = entry.file_type();
let is_dir = ft.as_ref().map_or(false, |t| t.is_dir());
let is_dir = ft.as_ref().is_some_and(|t| t.is_dir());
// Filter by type
if want_dirs && !is_dir {
@@ -75,7 +246,12 @@ pub fn run(
None => continue,
};
if !glob_match(effective_pattern, &name) {
let matches = if case_insensitive {
glob_match(&effective_pattern.to_lowercase(), &name.to_lowercase())
} else {
glob_match(effective_pattern, &name)
};
if !matches {
continue;
}
@@ -206,6 +382,11 @@ pub fn run(
mod tests {
use super::*;
/// Convert string slices to Vec<String> for test convenience.
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|s| s.to_string()).collect()
}
// --- glob_match unit tests ---
#[test]
@@ -251,39 +432,165 @@ mod tests {
assert_eq!(effective, "*");
}
// --- parse_find_args: native find syntax ---
#[test]
fn parse_native_find_name() {
let parsed = parse_find_args(&args(&[".", "-name", "*.rs"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, ".");
assert_eq!(parsed.file_type, "f");
assert_eq!(parsed.max_results, 50);
}
#[test]
fn parse_native_find_name_and_type() {
let parsed = parse_find_args(&args(&["src", "-name", "*.rs", "-type", "f"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, "src");
assert_eq!(parsed.file_type, "f");
}
#[test]
fn parse_native_find_type_d() {
let parsed = parse_find_args(&args(&[".", "-type", "d"])).unwrap();
assert_eq!(parsed.pattern, "*");
assert_eq!(parsed.file_type, "d");
}
#[test]
fn parse_native_find_maxdepth() {
let parsed = parse_find_args(&args(&[".", "-name", "*.toml", "-maxdepth", "2"])).unwrap();
assert_eq!(parsed.pattern, "*.toml");
assert_eq!(parsed.max_depth, Some(2));
assert_eq!(parsed.max_results, 50); // max_results unchanged by -maxdepth
}
#[test]
fn parse_native_find_iname() {
let parsed = parse_find_args(&args(&[".", "-iname", "Makefile"])).unwrap();
assert_eq!(parsed.pattern, "Makefile");
assert!(parsed.case_insensitive);
}
#[test]
fn parse_native_find_name_is_case_sensitive() {
let parsed = parse_find_args(&args(&[".", "-name", "*.rs"])).unwrap();
assert!(!parsed.case_insensitive);
}
#[test]
fn parse_native_find_no_path() {
// `find -name "*.rs"` without explicit path defaults to "."
let parsed = parse_find_args(&args(&["-name", "*.rs"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, ".");
}
// --- parse_find_args: unsupported flags ---
#[test]
fn parse_native_find_rejects_not() {
let result = parse_find_args(&args(&[".", "-name", "*.rs", "-not", "-name", "*_test.rs"]));
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(msg.contains("compound predicates"));
}
#[test]
fn parse_native_find_rejects_exec() {
let result = parse_find_args(&args(&[".", "-name", "*.tmp", "-exec", "rm", "{}", ";"]));
assert!(result.is_err());
}
// --- parse_find_args: RTK syntax ---
#[test]
fn parse_rtk_syntax_pattern_only() {
let parsed = parse_find_args(&args(&["*.rs"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, ".");
}
#[test]
fn parse_rtk_syntax_pattern_and_path() {
let parsed = parse_find_args(&args(&["*.rs", "src"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, "src");
}
#[test]
fn parse_rtk_syntax_with_flags() {
let parsed = parse_find_args(&args(&["*.rs", "src", "-m", "10", "-t", "d"])).unwrap();
assert_eq!(parsed.pattern, "*.rs");
assert_eq!(parsed.path, "src");
assert_eq!(parsed.max_results, 10);
assert_eq!(parsed.file_type, "d");
}
#[test]
fn parse_empty_args() {
let parsed = parse_find_args(&args(&[])).unwrap();
assert_eq!(parsed.pattern, "*");
assert_eq!(parsed.path, ".");
}
// --- run_from_args integration tests ---
#[test]
fn run_from_args_native_find_syntax() {
// Simulates: find . -name "*.rs" -type f
let result = run_from_args(&args(&[".", "-name", "*.rs", "-type", "f"]), 0);
assert!(result.is_ok());
}
#[test]
fn run_from_args_rtk_syntax() {
// Simulates: rtk find *.rs src
let result = run_from_args(&args(&["*.rs", "src"]), 0);
assert!(result.is_ok());
}
#[test]
fn run_from_args_iname_case_insensitive() {
// -iname should match case-insensitively
let result = run_from_args(&args(&[".", "-iname", "cargo.toml"]), 0);
assert!(result.is_ok());
}
// --- integration: run on this repo ---
#[test]
fn find_rs_files_in_src() {
// Should find .rs files without error
let result = run("*.rs", "src", 100, "f", 0);
let result = run("*.rs", "src", 100, None, "f", false, 0);
assert!(result.is_ok());
}
#[test]
fn find_dot_pattern_works() {
// "." pattern should not error (was broken before)
let result = run(".", "src", 10, "f", 0);
let result = run(".", "src", 10, None, "f", false, 0);
assert!(result.is_ok());
}
#[test]
fn find_no_matches() {
let result = run("*.xyz_nonexistent", "src", 50, "f", 0);
let result = run("*.xyz_nonexistent", "src", 50, None, "f", false, 0);
assert!(result.is_ok());
}
#[test]
fn find_respects_max() {
// With max=2, should not error
let result = run("*.rs", "src", 2, "f", 0);
let result = run("*.rs", "src", 2, None, "f", false, 0);
assert!(result.is_ok());
}
#[test]
fn find_gitignored_excluded() {
// target/ is in .gitignore — files inside should not appear
let result = run("*", ".", 1000, "f", 0);
let result = run("*", ".", 1000, None, "f", false, 0);
assert!(result.is_ok());
// We can't easily capture stdout in unit tests, but at least
// verify it runs without error. The smoke tests verify content.
+164 -37
View File
@@ -108,8 +108,58 @@ fn filter_markdown_segment(text: &str) -> String {
s
}
/// Check if args contain --json flag (user wants specific JSON fields, not RTK filtering)
fn has_json_flag(args: &[String]) -> bool {
args.iter().any(|a| a == "--json")
}
/// Extract a positional identifier (PR/issue number) from args, returning it
/// separately from the remaining extra flags (like -R, --repo, etc.).
/// Handles both `view 123 -R owner/repo` and `view -R owner/repo 123`.
fn extract_identifier_and_extra_args(args: &[String]) -> Option<(String, Vec<String>)> {
if args.is_empty() {
return None;
}
// Known gh flags that take a value — skip these and their values
let flags_with_value = ["-R", "--repo", "-q", "--jq", "-t", "--template"];
let mut identifier = None;
let mut extra = Vec::new();
let mut skip_next = false;
for arg in args {
if skip_next {
extra.push(arg.clone());
skip_next = false;
continue;
}
if flags_with_value.contains(&arg.as_str()) {
extra.push(arg.clone());
skip_next = true;
continue;
}
if arg.starts_with('-') {
extra.push(arg.clone());
continue;
}
// First non-flag arg is the identifier (number/URL)
if identifier.is_none() {
identifier = Some(arg.clone());
} else {
extra.push(arg.clone());
}
}
identifier.map(|id| (id, extra))
}
/// Run a gh command with token-optimized output
pub fn run(subcommand: &str, args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
// When user explicitly passes --json, they want raw gh JSON output, not RTK filtering
if has_json_flag(args) {
return run_passthrough("gh", subcommand, args);
}
match subcommand {
"pr" => run_pr(args, verbose, ultra_compact),
"issue" => run_issue(args, verbose, ultra_compact),
@@ -136,8 +186,8 @@ fn run_pr(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
"create" => pr_create(&args[1..], verbose),
"merge" => pr_merge(&args[1..], verbose),
"diff" => pr_diff(&args[1..], verbose),
"comment" => pr_action("commented", &args[1..], verbose),
"edit" => pr_action("edited", &args[1..], verbose),
"comment" => pr_action("commented", &args, verbose),
"edit" => pr_action("edited", &args, verbose),
_ => run_passthrough("gh", "pr", args),
}
}
@@ -229,20 +279,22 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("PR number required")),
};
let mut cmd = Command::new("gh");
cmd.args([
"pr",
"view",
pr_number,
&pr_number,
"--json",
"number,title,state,author,body,url,mergeable,reviews,statusCheckRollup",
]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -398,14 +450,16 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let (pr_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("PR number required")),
};
let mut cmd = Command::new("gh");
cmd.args(["pr", "checks", pr_number]);
cmd.args(["pr", "checks", &pr_number]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr checks")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -607,20 +661,22 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("Issue number required"));
}
let issue_number = &args[0];
let (issue_number, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("Issue number required")),
};
let mut cmd = Command::new("gh");
cmd.args([
"issue",
"view",
issue_number,
&issue_number,
"--json",
"number,title,state,author,body,url",
]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh issue view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -796,22 +852,23 @@ fn should_passthrough_run_view(extra_args: &[String]) -> bool {
}
fn view_run(args: &[String], _verbose: u8) -> Result<()> {
if args.is_empty() {
return Err(anyhow::anyhow!("Run ID required"));
}
let run_id = &args[0];
let extra_args = &args[1..];
let (run_id, extra_args) = match extract_identifier_and_extra_args(args) {
Some(result) => result,
None => return Err(anyhow::anyhow!("Run ID required")),
};
// Pass through when user requests logs or JSON — the filter would strip them
if should_passthrough_run_view(extra_args) {
return run_passthrough_with_extra("gh", &["run", "view", run_id], extra_args);
if should_passthrough_run_view(&extra_args) {
return run_passthrough_with_extra("gh", &["run", "view", &run_id], &extra_args);
}
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["run", "view", run_id]);
cmd.args(["run", "view", &run_id]);
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh run view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
@@ -1070,23 +1127,24 @@ fn pr_diff(args: &[String], _verbose: u8) -> Result<()> {
/// Generic PR action handler for comment/edit
fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let subcmd = &args[0];
let mut cmd = Command::new("gh");
cmd.args(["pr", action]);
cmd.arg("pr");
for arg in args {
cmd.arg(arg);
}
let output = cmd
.output()
.context(format!("Failed to run gh pr {}", action))?;
.context(format!("Failed to run gh pr {}", subcmd))?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh pr {}", action),
&format!("rtk gh pr {}", action),
&format!("gh pr {}", subcmd),
&format!("rtk gh pr {}", subcmd),
&stderr,
&stderr,
);
@@ -1094,8 +1152,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
std::process::exit(output.status.code().unwrap_or(1));
}
// Extract PR number from args
let pr_num = args
// Extract PR number from args (skip args[0] which is the subcommand)
let pr_num = args[1..]
.iter()
.find(|a| !a.starts_with('-'))
.map(|s| format!("#{}", s))
@@ -1112,8 +1170,8 @@ fn pr_action(action: &str, args: &[String], _verbose: u8) -> Result<()> {
};
timer.track(
&format!("gh pr {}", action),
&format!("rtk gh pr {}", action),
&format!("gh pr {}", subcmd),
&format!("rtk gh pr {}", subcmd),
&raw,
&filtered,
);
@@ -1277,6 +1335,75 @@ mod tests {
assert_eq!(result, "ok edited #42");
}
#[test]
fn test_has_json_flag_present() {
assert!(has_json_flag(&[
"view".into(),
"--json".into(),
"number,url".into()
]));
}
#[test]
fn test_has_json_flag_absent() {
assert!(!has_json_flag(&["view".into(), "42".into()]));
}
#[test]
fn test_extract_identifier_simple() {
let args: Vec<String> = vec!["123".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "123");
assert!(extra.is_empty());
}
#[test]
fn test_extract_identifier_with_repo_flag_after() {
// gh issue view 185 -R rtk-ai/rtk
let args: Vec<String> = vec!["185".into(), "-R".into(), "rtk-ai/rtk".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "185");
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
}
#[test]
fn test_extract_identifier_with_repo_flag_before() {
// gh issue view -R rtk-ai/rtk 185
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into(), "185".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "185");
assert_eq!(extra, vec!["-R", "rtk-ai/rtk"]);
}
#[test]
fn test_extract_identifier_with_long_repo_flag() {
let args: Vec<String> = vec!["42".into(), "--repo".into(), "owner/repo".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "42");
assert_eq!(extra, vec!["--repo", "owner/repo"]);
}
#[test]
fn test_extract_identifier_empty() {
let args: Vec<String> = vec![];
assert!(extract_identifier_and_extra_args(&args).is_none());
}
#[test]
fn test_extract_identifier_only_flags() {
// No positional identifier, only flags
let args: Vec<String> = vec!["-R".into(), "rtk-ai/rtk".into()];
assert!(extract_identifier_and_extra_args(&args).is_none());
}
#[test]
fn test_extract_identifier_with_web_flag() {
let args: Vec<String> = vec!["123".into(), "--web".into()];
let (id, extra) = extract_identifier_and_extra_args(&args).unwrap();
assert_eq!(id, "123");
assert_eq!(extra, vec!["--web"]);
}
#[test]
fn test_run_view_passthrough_log_failed() {
assert!(should_passthrough_run_view(&["--log-failed".into()]));
+39 -41
View File
@@ -10,7 +10,7 @@ pub enum GitCommand {
Status,
Show,
Add,
Commit { messages: Vec<String> },
Commit,
Push,
Pull,
Branch,
@@ -42,7 +42,7 @@ pub fn run(
GitCommand::Status => run_status(args, verbose, global_args),
GitCommand::Show => run_show(args, max_lines, verbose, global_args),
GitCommand::Add => run_add(args, verbose, global_args),
GitCommand::Commit { messages } => run_commit(&messages, verbose, global_args),
GitCommand::Commit => run_commit(args, verbose, global_args),
GitCommand::Push => run_push(args, verbose, global_args),
GitCommand::Pull => run_pull(args, verbose, global_args),
GitCommand::Branch => run_branch(args, verbose, global_args),
@@ -703,30 +703,25 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
Ok(())
}
fn build_commit_command(messages: &[String], global_args: &[String]) -> Command {
fn build_commit_command(args: &[String], global_args: &[String]) -> Command {
let mut cmd = git_cmd(global_args);
cmd.arg("commit");
for msg in messages {
cmd.args(["-m", msg]);
for arg in args {
cmd.arg(arg);
}
cmd
}
fn run_commit(messages: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
let timer = tracking::TimedExecution::start();
let original_cmd = messages
.iter()
.map(|m| format!("-m \"{}\"", m))
.collect::<Vec<_>>()
.join(" ");
let original_cmd = format!("git commit {}", original_cmd);
let original_cmd = format!("git commit {}", args.join(" "));
if verbose > 0 {
eprintln!("{}", original_cmd);
}
let output = build_commit_command(messages, global_args)
let output = build_commit_command(args, global_args)
.output()
.context("Failed to run git commit")?;
@@ -1721,28 +1716,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
#[test]
fn test_commit_single_message() {
let messages = vec!["fix: typo".to_string()];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
let args = vec!["-m".to_string(), "fix: typo".to_string()];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(args, vec!["commit", "-m", "fix: typo"]);
assert_eq!(cmd_args, vec!["commit", "-m", "fix: typo"]);
}
#[test]
fn test_commit_multiple_messages() {
let messages = vec![
let args = vec![
"-m".to_string(),
"feat: add multi-paragraph support".to_string(),
"-m".to_string(),
"This allows git commit -m \"title\" -m \"body\".".to_string(),
];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(
args,
cmd_args,
vec![
"commit",
"-m",
@@ -1753,29 +1750,30 @@ no changes added to commit (use "git add" and/or "git commit -a")
);
}
// #327: git commit -am "msg" must pass -am through to git
#[test]
fn test_commit_three_messages() {
let messages = vec![
"title".to_string(),
"body".to_string(),
"footer: refs #202".to_string(),
];
let cmd = build_commit_command(&messages, &[]);
let args: Vec<_> = cmd
fn test_commit_am_flag() {
let args = vec!["-am".to_string(), "quick fix".to_string()];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(
args,
vec![
"commit",
"-m",
"title",
"-m",
"body",
"-m",
"footer: refs #202"
]
);
assert_eq!(cmd_args, vec!["commit", "-am", "quick fix"]);
}
#[test]
fn test_commit_amend() {
let args = vec![
"--amend".to_string(),
"-m".to_string(),
"new msg".to_string(),
];
let cmd = build_commit_command(&args, &[]);
let cmd_args: Vec<_> = cmd
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
assert_eq!(cmd_args, vec!["commit", "--amend", "-m", "new msg"]);
}
}
+88
View File
@@ -0,0 +1,88 @@
use std::path::PathBuf;
const CURRENT_HOOK_VERSION: u8 = 2;
const WARN_INTERVAL_SECS: u64 = 24 * 3600;
/// Check if the installed hook is outdated, warn once per day.
pub fn maybe_warn() {
// Don't block startup — fail silently on any error
let _ = check_and_warn();
}
fn check_and_warn() -> Option<()> {
let hook_path = hook_installed_path()?;
let content = std::fs::read_to_string(&hook_path).ok()?;
let installed_version = parse_hook_version(&content);
if installed_version >= CURRENT_HOOK_VERSION {
return Some(());
}
// Rate limit: warn once per day
let marker = warn_marker_path()?;
if let Ok(meta) = std::fs::metadata(&marker) {
if let Ok(elapsed) = meta.modified().ok()?.elapsed() {
if elapsed.as_secs() < WARN_INTERVAL_SECS {
return Some(());
}
}
}
// Touch marker
let _ = std::fs::create_dir_all(marker.parent()?);
let _ = std::fs::write(&marker, b"");
eprintln!("[rtk] Hook outdated — run `rtk init -g` to update");
Some(())
}
pub fn parse_hook_version(content: &str) -> u8 {
for line in content.lines().take(5) {
if let Some(rest) = line.strip_prefix("# rtk-hook-version:") {
if let Ok(v) = rest.trim().parse::<u8>() {
return v;
}
}
}
0 // No version tag = version 0 (outdated)
}
fn hook_installed_path() -> Option<PathBuf> {
let home = dirs::home_dir()?;
let path = home.join(".claude").join("hooks").join("rtk-rewrite.sh");
if path.exists() {
Some(path)
} else {
None
}
}
fn warn_marker_path() -> Option<PathBuf> {
let data_dir = dirs::data_local_dir()?.join("rtk");
Some(data_dir.join(".hook_warn_last"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_hook_version_present() {
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 2\n# some comment\n";
assert_eq!(parse_hook_version(content), 2);
}
#[test]
fn test_parse_hook_version_missing() {
let content = "#!/usr/bin/env bash\n# old hook without version\n";
assert_eq!(parse_hook_version(content), 0);
}
#[test]
fn test_parse_hook_version_future() {
let content = "#!/usr/bin/env bash\n# rtk-hook-version: 5\n";
assert_eq!(parse_hook_version(content), 5);
}
}
+41 -19
View File
@@ -228,12 +228,8 @@ fn ensure_hook_installed(hook_path: &Path, verbose: u8) -> Result<bool> {
// Store SHA-256 hash for runtime integrity verification.
// Always store (idempotent) to ensure baseline exists even for
// hooks installed before integrity checks were added.
integrity::store_hash(hook_path).with_context(|| {
format!(
"Failed to store integrity hash for {}",
hook_path.display()
)
})?;
integrity::store_hash(hook_path)
.with_context(|| format!("Failed to store integrity hash for {}", hook_path.display()))?;
if verbose > 0 && changed {
eprintln!("Stored integrity hash for hook");
}
@@ -680,7 +676,7 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
// 1. Prepare hook directory and install hook
let (_hook_dir, hook_path) = prepare_hook_paths()?;
ensure_hook_installed(&hook_path, verbose)?;
let hook_changed = ensure_hook_installed(&hook_path, verbose)?;
// 2. Write RTK.md
write_if_changed(&rtk_md_path, RTK_SLIM, "RTK.md", verbose)?;
@@ -689,7 +685,12 @@ fn run_default_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Result<
let migrated = patch_claude_md(&claude_md_path, verbose)?;
// 4. Print success message
println!("\nRTK hook installed (global).\n");
let hook_status = if hook_changed {
"installed/updated"
} else {
"already up to date"
};
println!("\nRTK hook {} (global).\n", hook_status);
println!(" Hook: {}", hook_path.display());
println!(" RTK.md: {} (10 lines)", rtk_md_path.display());
println!(" CLAUDE.md: @RTK.md reference added");
@@ -737,9 +738,14 @@ fn run_hook_only_mode(global: bool, patch_mode: PatchMode, verbose: u8) -> Resul
// Prepare and install hook
let (_hook_dir, hook_path) = prepare_hook_paths()?;
ensure_hook_installed(&hook_path, verbose)?;
let hook_changed = ensure_hook_installed(&hook_path, verbose)?;
println!("\nRTK hook installed (hook-only mode).\n");
let hook_status = if hook_changed {
"installed/updated"
} else {
"already up to date"
};
println!("\nRTK hook {} (hook-only mode).\n", hook_status);
println!(" Hook: {}", hook_path.display());
println!(
" Note: No RTK.md created. Claude won't know about meta commands (gain, discover, proxy)."
@@ -1022,14 +1028,28 @@ pub fn show_config() -> Result<()> {
let hook_content = fs::read_to_string(&hook_path)?;
let has_guards =
hook_content.contains("command -v rtk") && hook_content.contains("command -v jq");
let is_thin_delegator = hook_content.contains("rtk rewrite");
let hook_version = crate::hook_check::parse_hook_version(&hook_content);
if is_executable && has_guards {
println!("✅ Hook: {} (executable, with guards)", hook_path.display());
} else if !is_executable {
if !is_executable {
println!(
"⚠️ Hook: {} (NOT executable - run: chmod +x)",
hook_path.display()
);
} else if !is_thin_delegator {
println!(
"⚠️ Hook: {} (outdated — inline logic, not thin delegator)",
hook_path.display()
);
println!(
" → Run `rtk init --global` to upgrade to the single source of truth hook"
);
} else if is_executable && has_guards {
println!(
"✅ Hook: {} (thin delegator, version {})",
hook_path.display(),
hook_version
);
} else {
println!("⚠️ Hook: {} (no guards - outdated)", hook_path.display());
}
@@ -1061,7 +1081,8 @@ pub fn show_config() -> Result<()> {
Ok(integrity::IntegrityStatus::NoBaseline) => {
println!("⚠️ Integrity: no baseline hash (run: rtk init -g to establish)");
}
Ok(integrity::IntegrityStatus::NotInstalled) | Ok(integrity::IntegrityStatus::OrphanedHash) => {
Ok(integrity::IntegrityStatus::NotInstalled)
| Ok(integrity::IntegrityStatus::OrphanedHash) => {
// Don't show integrity line if hook isn't installed
}
Err(_) => {
@@ -1175,12 +1196,13 @@ mod tests {
fn test_hook_has_guards() {
assert!(REWRITE_HOOK.contains("command -v rtk"));
assert!(REWRITE_HOOK.contains("command -v jq"));
// Guards must be BEFORE set -euo pipefail
let guard_pos = REWRITE_HOOK.find("command -v rtk").unwrap();
let set_pos = REWRITE_HOOK.find("set -euo pipefail").unwrap();
// Guards (rtk/jq availability checks) must appear before the actual delegation call.
// The thin delegating hook no longer uses set -euo pipefail.
let jq_pos = REWRITE_HOOK.find("command -v jq").unwrap();
let rtk_delegate_pos = REWRITE_HOOK.find("rtk rewrite \"$CMD\"").unwrap();
assert!(
guard_pos < set_pos,
"Guards must come before set -euo pipefail"
jq_pos < rtk_delegate_pos,
"Guards must appear before rtk rewrite delegation"
);
}
+16 -4
View File
@@ -164,7 +164,10 @@ fn read_stored_hash(path: &Path) -> Result<String> {
// sha256sum format uses two-space separator: "<hash> <filename>"
let parts: Vec<&str> = line.splitn(2, " ").collect();
if parts.len() != 2 {
anyhow::bail!("Invalid hash format in {} (expected 'hash filename')", path.display());
anyhow::bail!(
"Invalid hash format in {} (expected 'hash filename')",
path.display()
);
}
let hash = parts[0];
@@ -250,8 +253,14 @@ pub fn runtime_check() -> Result<()> {
}
IntegrityStatus::Tampered { expected, actual } => {
eprintln!("rtk: hook integrity check FAILED");
eprintln!(" Expected hash: {}...", expected.get(..16).unwrap_or(&expected));
eprintln!(" Actual hash: {}...", actual.get(..16).unwrap_or(&actual));
eprintln!(
" Expected hash: {}...",
expected.get(..16).unwrap_or(&expected)
);
eprintln!(
" Actual hash: {}...",
actual.get(..16).unwrap_or(&actual)
);
eprintln!();
eprintln!(" The hook at ~/.claude/hooks/rtk-rewrite.sh has been modified.");
eprintln!(" This may indicate tampering. RTK will not execute.");
@@ -483,7 +492,10 @@ mod tests {
.unwrap();
let result = verify_hook_at(&hook);
assert!(result.is_err(), "Should reject hash-only format (no filename)");
assert!(
result.is_err(),
"Should reject hash-only format (no filename)"
);
}
#[test]
+66 -1
View File
@@ -1,12 +1,41 @@
use crate::tracking;
use anyhow::{Context, Result};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::fs;
use std::io::{self, Read};
use std::path::Path;
/// Reject non-JSON files with a clear error before doing any I/O.
fn validate_json_extension(file: &Path) -> Result<()> {
if let Some(ext) = file.extension().and_then(|e| e.to_str()) {
let format_name = match ext {
"toml" => Some("TOML"),
"yaml" | "yml" => Some("YAML"),
"xml" => Some("XML"),
"csv" => Some("CSV"),
"ini" => Some("INI"),
"env" => Some("env"),
"txt" => Some("plain text"),
_ => None,
};
if let Some(fmt) = format_name {
let mut msg = format!(
"{} is not a JSON file (detected {}). Use `rtk read` for non-JSON files.",
file.display(),
fmt
);
if ext == "toml" && file.file_name().is_some_and(|n| n == "Cargo.toml") {
msg.push_str(" Tip: use `rtk deps` for Cargo.toml.");
}
bail!("{}", msg);
}
}
Ok(())
}
/// Show JSON structure without values
pub fn run(file: &Path, max_depth: usize, verbose: u8) -> Result<()> {
validate_json_extension(file)?;
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -147,6 +176,42 @@ fn extract_schema(value: &Value, depth: usize, max_depth: usize) -> String {
mod tests {
use super::*;
// --- #347: validate_json_extension ---
#[test]
fn test_toml_file_rejected() {
let err = validate_json_extension(Path::new("config.toml")).unwrap_err();
assert!(err.to_string().contains("not a JSON file"));
assert!(err.to_string().contains("TOML"));
}
#[test]
fn test_cargo_toml_suggests_deps() {
let err = validate_json_extension(Path::new("Cargo.toml")).unwrap_err();
assert!(err.to_string().contains("rtk deps"));
}
#[test]
fn test_yaml_file_rejected() {
let err = validate_json_extension(Path::new("config.yaml")).unwrap_err();
assert!(err.to_string().contains("YAML"));
}
#[test]
fn test_json_file_accepted() {
assert!(validate_json_extension(Path::new("data.json")).is_ok());
}
#[test]
fn test_unknown_extension_accepted() {
assert!(validate_json_extension(Path::new("data.xyz")).is_ok());
}
#[test]
fn test_no_extension_accepted() {
assert!(validate_json_extension(Path::new("Makefile")).is_ok());
}
#[test]
fn test_extract_schema_simple() {
let json: Value = serde_json::from_str(r#"{"name": "test", "count": 42}"#).unwrap();
+112 -11
View File
@@ -52,16 +52,43 @@ fn is_python_linter(linter: &str) -> bool {
matches!(linter, "ruff" | "pylint" | "mypy" | "flake8")
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
/// Strip package manager prefixes (npx, bunx, pnpm, pnpm exec, yarn) from args.
/// Returns the number of args to skip.
fn strip_pm_prefix(args: &[String]) -> usize {
let pm_names = ["npx", "bunx", "pnpm", "yarn"];
let mut skip = 0;
for arg in args {
if pm_names.contains(&arg.as_str()) || arg == "exec" {
skip += 1;
} else {
break;
}
}
skip
}
// Detect linter name (first arg if not a path/flag, else default to eslint)
/// Detect the linter name from args (after stripping PM prefixes).
/// Returns the linter name and whether it was explicitly specified.
fn detect_linter(args: &[String]) -> (&str, bool) {
let is_path_or_flag = args.is_empty()
|| args[0].starts_with('-')
|| args[0].contains('/')
|| args[0].contains('.');
let linter = if is_path_or_flag { "eslint" } else { &args[0] };
if is_path_or_flag {
("eslint", false)
} else {
(&args[0], true)
}
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let skip = strip_pm_prefix(args);
let effective_args = &args[skip..];
let (linter, explicit) = detect_linter(effective_args);
// Python linters use Command::new() directly (they're on PATH via pip/pipx)
// JS linters use package_manager_exec (npx/pnpm exec)
@@ -78,13 +105,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
"ruff" => {
// Force JSON output for ruff check
if !args.contains(&"--output-format".to_string()) {
if !effective_args.contains(&"--output-format".to_string()) {
cmd.arg("check").arg("--output-format=json");
}
}
"pylint" => {
// Force JSON2 output for pylint
if !args.contains(&"--output-format".to_string()) {
if !effective_args.contains(&"--output-format".to_string()) {
cmd.arg("--output-format=json2");
}
}
@@ -97,11 +124,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
// Add user arguments (skip first if it was the linter name, and skip "check" for ruff if we added it)
let start_idx = if is_path_or_flag {
let start_idx = if !explicit {
0
} else if linter == "ruff" && !args.is_empty() && args[0] == "ruff" {
} else if linter == "ruff" && !effective_args.is_empty() && effective_args[0] == "ruff" {
// Skip "ruff" and "check" if we already added "check"
if args.len() > 1 && args[1] == "check" {
if effective_args.len() > 1 && effective_args[1] == "check" {
2
} else {
1
@@ -110,7 +137,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
1
};
for arg in &args[start_idx..] {
for arg in &effective_args[start_idx..] {
// Skip --output-format if we already added it
if linter == "ruff" && arg.starts_with("--output-format") {
continue;
@@ -123,7 +150,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Default to current directory if no path specified (for ruff/pylint/mypy/eslint)
if matches!(linter, "ruff" | "pylint" | "mypy" | "eslint") {
let has_path = args
let has_path = effective_args
.iter()
.skip(start_idx)
.any(|a| !a.starts_with('-') && !a.contains('='));
@@ -580,6 +607,80 @@ mod tests {
assert!(result.contains("utils.py"));
}
#[test]
fn test_strip_pm_prefix_npx() {
let args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
assert_eq!(strip_pm_prefix(&args), 1);
}
#[test]
fn test_strip_pm_prefix_bunx() {
let args: Vec<String> = vec!["bunx".into(), "eslint".into(), ".".into()];
assert_eq!(strip_pm_prefix(&args), 1);
}
#[test]
fn test_strip_pm_prefix_pnpm_exec() {
let args: Vec<String> = vec!["pnpm".into(), "exec".into(), "eslint".into()];
assert_eq!(strip_pm_prefix(&args), 2);
}
#[test]
fn test_strip_pm_prefix_none() {
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
assert_eq!(strip_pm_prefix(&args), 0);
}
#[test]
fn test_strip_pm_prefix_empty() {
let args: Vec<String> = vec![];
assert_eq!(strip_pm_prefix(&args), 0);
}
#[test]
fn test_detect_linter_eslint() {
let args: Vec<String> = vec!["eslint".into(), "src/".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(explicit);
}
#[test]
fn test_detect_linter_default_on_path() {
let args: Vec<String> = vec!["src/".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(!explicit);
}
#[test]
fn test_detect_linter_default_on_flag() {
let args: Vec<String> = vec!["--max-warnings=0".into()];
let (linter, explicit) = detect_linter(&args);
assert_eq!(linter, "eslint");
assert!(!explicit);
}
#[test]
fn test_detect_linter_after_npx_strip() {
// Simulates: rtk lint npx eslint src/ → after strip_pm_prefix, args = ["eslint", "src/"]
let full_args: Vec<String> = vec!["npx".into(), "eslint".into(), "src/".into()];
let skip = strip_pm_prefix(&full_args);
let effective = &full_args[skip..];
let (linter, _) = detect_linter(effective);
assert_eq!(linter, "eslint");
}
#[test]
fn test_detect_linter_after_pnpm_exec_strip() {
let full_args: Vec<String> =
vec!["pnpm".into(), "exec".into(), "biome".into(), "check".into()];
let skip = strip_pm_prefix(&full_args);
let effective = &full_args[skip..];
let (linter, _) = detect_linter(effective);
assert_eq!(linter, "biome");
}
#[test]
fn test_is_python_linter() {
assert!(is_python_linter("ruff"));
+159 -53
View File
@@ -20,6 +20,7 @@ mod go_cmd;
mod golangci_cmd;
mod grep_cmd;
mod hook_audit_cmd;
mod hook_check;
mod init;
mod integrity;
mod json_cmd;
@@ -40,10 +41,12 @@ mod prisma_cmd;
mod psql_cmd;
mod pytest_cmd;
mod read;
mod rewrite_cmd;
mod ruff_cmd;
mod runner;
mod summary;
mod tee;
mod telemetry;
mod tracking;
mod tree;
mod tsc_cmd;
@@ -234,19 +237,11 @@ enum Commands {
show_all: bool,
},
/// Find files with compact tree output
/// Find files with compact tree output (accepts native find flags like -name, -type)
Find {
/// Pattern to search (glob)
pattern: String,
/// Path to search in
#[arg(default_value = ".")]
path: String,
/// Maximum results to show
#[arg(short, long, default_value = "50")]
max: usize,
/// Filter by type: f (file), d (directory)
#[arg(short = 't', long, default_value = "f")]
file_type: String,
/// All find arguments (supports both RTK and native find syntax)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Ultra-condensed diff (only changed lines)
@@ -606,6 +601,18 @@ enum Commands {
#[arg(short, long, default_value = "7")]
since: u64,
},
/// Rewrite a raw command to its RTK equivalent (single source of truth for hooks)
///
/// Exits 0 and prints the rewritten command if supported.
/// Exits 1 with no output if the command has no RTK equivalent.
///
/// Used by Claude Code, Gemini CLI, and other LLM hooks:
/// REWRITTEN=$(rtk rewrite "$CMD") || exit 0
Rewrite {
/// Raw command to rewrite (e.g. "git status", "cargo test && git push")
cmd: String,
},
}
#[derive(Subcommand)]
@@ -642,9 +649,9 @@ enum GitCommands {
},
/// Commit → "ok ✓ \<hash\>"
Commit {
/// Commit message (can be repeated for multi-paragraph)
#[arg(short, long)]
message: Vec<String>,
/// Git commit arguments (supports -a, -m, --amend, --allow-empty, etc)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Push → "ok ✓ \<branch\>"
Push {
@@ -948,8 +955,6 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
parse_error.exit();
}
eprintln!("[rtk: parse failed, running raw]");
let raw_command = args.join(" ");
let error_message = utils::strip_ansi(&parse_error.to_string());
@@ -985,6 +990,12 @@ fn run_fallback(parse_error: clap::Error) -> Result<()> {
}
fn main() -> Result<()> {
// Fire-and-forget telemetry ping (1/day, non-blocking)
telemetry::maybe_ping();
// Warn if installed hook is outdated (1/day, non-blocking)
hook_check::maybe_warn();
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(e) => {
@@ -1108,10 +1119,10 @@ fn main() -> Result<()> {
GitCommands::Add { args } => {
git::run(git::GitCommand::Add, &args, None, cli.verbose, &global_args)?;
}
GitCommands::Commit { message } => {
GitCommands::Commit { args } => {
git::run(
git::GitCommand::Commit { messages: message },
&[],
git::GitCommand::Commit,
&args,
None,
cli.verbose,
&global_args,
@@ -1240,13 +1251,8 @@ fn main() -> Result<()> {
env_cmd::run(filter.as_deref(), show_all, cli.verbose)?;
}
Commands::Find {
pattern,
path,
max,
file_type,
} => {
find_cmd::run(&pattern, &path, max, &file_type, cli.verbose)?;
Commands::Find { args } => {
find_cmd::run_from_args(&args, cli.verbose)?;
}
Commands::Diff { file1, file2 } => {
@@ -1687,8 +1693,14 @@ fn main() -> Result<()> {
hook_audit_cmd::run(since, cli.verbose)?;
}
Commands::Rewrite { cmd } => {
rewrite_cmd::run(&cmd)?;
}
Commands::Proxy { args } => {
use std::process::Command;
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::thread;
if args.is_empty() {
anyhow::bail!(
@@ -1708,18 +1720,74 @@ fn main() -> Result<()> {
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
}
let output = Command::new(cmd_name.as_ref())
let mut child = Command::new(cmd_name.as_ref())
.args(&cmd_args)
.output()
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context(format!("Failed to execute command: {}", cmd_name))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let full_output = format!("{}{}", stdout, stderr);
let stdout_pipe = child
.stdout
.take()
.context("Failed to capture child stdout")?;
let stderr_pipe = child
.stderr
.take()
.context("Failed to capture child stderr")?;
// Print output
print!("{}", stdout);
eprint!("{}", stderr);
let stdout_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
let mut reader = stdout_pipe;
let mut captured = Vec::new();
let mut buf = [0u8; 8192];
loop {
let count = reader.read(&mut buf)?;
if count == 0 {
break;
}
captured.extend_from_slice(&buf[..count]);
let mut out = std::io::stdout().lock();
out.write_all(&buf[..count])?;
out.flush()?;
}
Ok(captured)
});
let stderr_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
let mut reader = stderr_pipe;
let mut captured = Vec::new();
let mut buf = [0u8; 8192];
loop {
let count = reader.read(&mut buf)?;
if count == 0 {
break;
}
captured.extend_from_slice(&buf[..count]);
let mut err = std::io::stderr().lock();
err.write_all(&buf[..count])?;
err.flush()?;
}
Ok(captured)
});
let status = child
.wait()
.context(format!("Failed waiting for command: {}", cmd_name))?;
let stdout_bytes = stdout_handle
.join()
.map_err(|_| anyhow::anyhow!("stdout streaming thread panicked"))??;
let stderr_bytes = stderr_handle
.join()
.map_err(|_| anyhow::anyhow!("stderr streaming thread panicked"))??;
let stdout = String::from_utf8_lossy(&stdout_bytes);
let stderr = String::from_utf8_lossy(&stderr_bytes);
let full_output = format!("{}{}", stdout, stderr);
// Track usage (input = output since no filtering)
timer.track(
@@ -1730,8 +1798,8 @@ fn main() -> Result<()> {
);
// Exit with same code as child process
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
}
@@ -1805,10 +1873,10 @@ mod tests {
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-m", "fix: typo"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["fix: typo"]);
assert_eq!(args, vec!["-m", "fix: typo"]);
}
_ => panic!("Expected Git Commit command"),
}
@@ -1828,10 +1896,43 @@ mod tests {
.unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["feat: add support", "Body paragraph here."]);
assert_eq!(
args,
vec!["-m", "feat: add support", "-m", "Body paragraph here."]
);
}
_ => panic!("Expected Git Commit command"),
}
}
// #327: git commit -am "msg" was rejected by Clap
#[test]
fn test_git_commit_am_flag() {
let cli = Cli::try_parse_from(["rtk", "git", "commit", "-am", "quick fix"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { args },
..
} => {
assert_eq!(args, vec!["-am", "quick fix"]);
}
_ => panic!("Expected Git Commit command"),
}
}
#[test]
fn test_git_commit_amend() {
let cli =
Cli::try_parse_from(["rtk", "git", "commit", "--amend", "-m", "new msg"]).unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { args },
..
} => {
assert_eq!(args, vec!["--amend", "-m", "new msg"]);
}
_ => panic!("Expected Git Commit command"),
}
@@ -1875,10 +1976,20 @@ mod tests {
.unwrap();
match cli.command {
Commands::Git {
command: GitCommands::Commit { message },
command: GitCommands::Commit { args },
..
} => {
assert_eq!(message, vec!["title", "body", "footer"]);
assert_eq!(
args,
vec![
"--message",
"title",
"--message",
"body",
"--message",
"footer"
]
);
}
_ => panic!("Expected Git Commit command"),
}
@@ -1918,15 +2029,10 @@ mod tests {
}
#[test]
fn test_try_parse_git_with_dash_c_fails() {
// This is the case that triggers fallback: git -C /path status
match Cli::try_parse_from(["rtk", "git", "-C", "/path", "status"]) {
Err(e) => assert!(!matches!(
e.kind(),
ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
)),
Ok(_) => panic!("Expected parse error for git -C"),
}
fn test_try_parse_git_with_dash_c_succeeds() {
// git -C /path status is now supported via global options
let result = Cli::try_parse_from(["rtk", "git", "-C", "/path", "status"]);
assert!(result.is_ok(), "git -C should parse successfully");
}
#[test]
+40
View File
@@ -24,6 +24,25 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
// #221: If prettier is not installed or produced no meaningful output,
// show stderr as-is instead of a misleading "All files formatted" message.
let has_output = stdout.lines().any(|l| !l.trim().is_empty());
if !has_output && !output.status.success() {
let msg = stderr.trim();
if msg.is_empty() {
eprintln!("Error: prettier not found or produced no output");
} else {
eprintln!("{}", msg);
}
timer.track(
&format!("prettier {}", args.join(" ")),
&format!("rtk prettier {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = filter_prettier_output(&raw);
println!("{}", filtered);
@@ -45,6 +64,11 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
/// Filter Prettier output - show only files that need formatting
pub fn filter_prettier_output(output: &str) -> String {
// #221: empty or whitespace-only output means prettier didn't run
if output.trim().is_empty() {
return "Error: prettier produced no output".to_string();
}
let mut files_to_format: Vec<String> = Vec::new();
let mut files_checked = 0;
let mut is_check_mode = true;
@@ -178,4 +202,20 @@ Code style issues found in the above file(s). Forgot to run Prettier?
assert!(result.contains("15 files need formatting"));
assert!(result.contains("... +5 more files"));
}
// --- #221: empty output should not say "All files formatted" ---
#[test]
fn test_filter_empty_output() {
let result = filter_prettier_output("");
assert!(result.contains("Error"));
assert!(!result.contains("All files formatted"));
}
#[test]
fn test_filter_whitespace_only_output() {
let result = filter_prettier_output(" \n\n ");
assert!(result.contains("Error"));
assert!(!result.contains("All files formatted"));
}
}
+50
View File
@@ -0,0 +1,50 @@
use crate::discover::registry;
/// Run the `rtk rewrite` command.
///
/// Prints the RTK-rewritten command to stdout and exits 0.
/// Exits 1 (without output) if the command has no RTK equivalent.
///
/// Used by shell hooks to rewrite commands transparently:
/// ```bash
/// REWRITTEN=$(rtk rewrite "$CMD") || exit 0
/// [ "$CMD" = "$REWRITTEN" ] && exit 0 # already RTK, skip
/// ```
pub fn run(cmd: &str) -> anyhow::Result<()> {
let excluded = crate::config::Config::load()
.map(|c| c.hooks.exclude_commands)
.unwrap_or_default();
match registry::rewrite_command(cmd, &excluded) {
Some(rewritten) => {
print!("{}", rewritten);
Ok(())
}
None => {
std::process::exit(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_supported_command_succeeds() {
assert!(registry::rewrite_command("git status", &[]).is_some());
}
#[test]
fn test_run_unsupported_returns_none() {
assert!(registry::rewrite_command("terraform plan", &[]).is_none());
}
#[test]
fn test_run_already_rtk_returns_some() {
assert_eq!(
registry::rewrite_command("rtk git status", &[]),
Some("rtk git status".into())
);
}
}
+144
View File
@@ -0,0 +1,144 @@
use crate::config;
use crate::tracking;
use sha2::{Digest, Sha256};
use std::path::PathBuf;
const TELEMETRY_URL: Option<&str> = option_env!("RTK_TELEMETRY_URL");
const TELEMETRY_TOKEN: Option<&str> = option_env!("RTK_TELEMETRY_TOKEN");
const PING_INTERVAL_SECS: u64 = 23 * 3600; // 23 hours
/// Send a telemetry ping if enabled and not already sent today.
/// Fire-and-forget: errors are silently ignored.
pub fn maybe_ping() {
// No URL compiled in → telemetry disabled
if TELEMETRY_URL.is_none() {
return;
}
// Check opt-out: env var
if std::env::var("RTK_TELEMETRY_DISABLED").unwrap_or_default() == "1" {
return;
}
// Check opt-out: config.toml
if let Some(false) = config::telemetry_enabled() {
return;
}
// Check last ping time
let marker = telemetry_marker_path();
if let Ok(metadata) = std::fs::metadata(&marker) {
if let Ok(modified) = metadata.modified() {
if let Ok(elapsed) = modified.elapsed() {
if elapsed.as_secs() < PING_INTERVAL_SECS {
return;
}
}
}
}
// Touch marker file immediately (before sending) to avoid double-ping
touch_marker(&marker);
// Spawn thread so we never block the CLI
std::thread::spawn(|| {
let _ = send_ping();
});
}
fn send_ping() -> Result<(), Box<dyn std::error::Error>> {
let url = TELEMETRY_URL.ok_or("no telemetry URL")?;
let device_hash = generate_device_hash();
let version = env!("CARGO_PKG_VERSION").to_string();
let os = std::env::consts::OS.to_string();
let arch = std::env::consts::ARCH.to_string();
// Get stats from tracking DB
let (commands_24h, top_commands, savings_pct) = get_stats();
let payload = serde_json::json!({
"device_hash": device_hash,
"version": version,
"os": os,
"arch": arch,
"commands_24h": commands_24h,
"top_commands": top_commands,
"savings_pct": savings_pct,
});
let mut req = ureq::post(url).set("Content-Type", "application/json");
if let Some(token) = TELEMETRY_TOKEN {
req = req.set("X-RTK-Token", token);
}
// 2 second timeout — if server is down, we move on
req.timeout(std::time::Duration::from_secs(2))
.send_string(&payload.to_string())?;
Ok(())
}
fn generate_device_hash() -> String {
let hostname = hostname::get()
.map(|h| h.to_string_lossy().to_string())
.unwrap_or_default();
let username = std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.unwrap_or_default();
let mut hasher = Sha256::new();
hasher.update(hostname.as_bytes());
hasher.update(b":");
hasher.update(username.as_bytes());
format!("{:x}", hasher.finalize())
}
fn get_stats() -> (i64, Vec<String>, Option<f64>) {
let tracker = match tracking::Tracker::new() {
Ok(t) => t,
Err(_) => return (0, vec![], None),
};
// Get 24h command count and top commands from tracking DB
let commands_24h = tracker
.count_commands_since(chrono::Utc::now() - chrono::Duration::hours(24))
.unwrap_or(0);
let top_commands = tracker.top_commands(5).unwrap_or_default();
let savings_pct = tracker.overall_savings_pct().ok();
(commands_24h, top_commands, savings_pct)
}
fn telemetry_marker_path() -> PathBuf {
let data_dir = dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("/tmp"))
.join("rtk");
let _ = std::fs::create_dir_all(&data_dir);
data_dir.join(".telemetry_last_ping")
}
fn touch_marker(path: &PathBuf) {
let _ = std::fs::write(path, b"");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_device_hash_is_stable() {
let h1 = generate_device_hash();
let h2 = generate_device_hash();
assert_eq!(h1, h2);
assert_eq!(h1.len(), 64); // SHA-256 hex
}
#[test]
fn test_marker_path_exists() {
let path = telemetry_marker_path();
assert!(path.to_string_lossy().contains("rtk"));
}
}
+39
View File
@@ -886,6 +886,45 @@ impl Tracker {
Ok(rows.collect::<Result<Vec<_>, _>>()?)
}
/// Count commands since a given timestamp (for telemetry).
pub fn count_commands_since(&self, since: chrono::DateTime<chrono::Utc>) -> Result<i64> {
let ts = since.format("%Y-%m-%dT%H:%M:%S").to_string();
let count: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM commands WHERE timestamp >= ?1",
params![ts],
|row| row.get(0),
)?;
Ok(count)
}
/// Get top N commands by frequency (for telemetry).
pub fn top_commands(&self, limit: usize) -> Result<Vec<String>> {
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, COUNT(*) as cnt FROM commands
GROUP BY rtk_cmd ORDER BY cnt DESC LIMIT ?1",
)?;
let rows = stmt.query_map(params![limit as i64], |row| {
let cmd: String = row.get(0)?;
// Extract just the command name (e.g. "rtk git status" → "git")
Ok(cmd.split_whitespace().nth(1).unwrap_or(&cmd).to_string())
})?;
Ok(rows.filter_map(|r| r.ok()).collect())
}
/// Get overall savings percentage (for telemetry).
pub fn overall_savings_pct(&self) -> Result<f64> {
let (total_input, total_saved): (i64, i64) = self.conn.query_row(
"SELECT COALESCE(SUM(input_tokens), 0), COALESCE(SUM(saved_tokens), 0) FROM commands",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)?;
if total_input > 0 {
Ok((total_saved as f64 / total_input as f64) * 100.0)
} else {
Ok(0.0)
}
}
}
fn get_db_path() -> Result<PathBuf> {