Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak 6cee6c60b8 fix(git): inherit stdin for commit and push to preserve SSH signing (#733)
Command::output() sets stdin to Stdio::piped() by default, creating an
empty pipe instead of inheriting the terminal. SSH signing tools
(1Password, YubiKey, gpg-agent with pinentry) need TTY access on stdin
for passphrase prompts or agent communication. This caused signatures
to be silently dropped — commits succeeded but without gpgsig headers.

Fix: add .stdin(Stdio::inherit()) to git commit and git push commands
so they inherit the parent's stdin (terminal or hook pipe). Output
capture via stdout/stderr pipes is preserved.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-04-02 21:04:46 +02:00
aesoft 5bd35a33ad Merge pull request #952 from rtk-ai/fix/pr-934-review
fix(review): PR #934
2026-03-31 20:45:44 +02:00
aesoft bae7930119 fix(review): PR #934 2026-03-31 20:43:59 +02:00
Florian BRUNIAUXandClaude Sonnet 4.6 13e37bf7a8 ci: enforce test presence on new/modified filter modules
Add check-test-presence.sh script and CI job that fails if any *_cmd.rs
file added or modified in a PR is missing a #[cfg(test)] block.

- New CI job runs with no dependencies (parallel to all other jobs, <10s)
- Uses --diff-filter=AM to catch both added files and test deletions
- --self-test mode for local verification
- Add missing tests to wget_cmd.rs (17 tests) and env_cmd.rs (12 tests)
  covering pure functions: compact_url, format_size, parse_error,
  extract_filename, mask_value, is_lang_var, is_cloud_var, etc.

Fixes the enforcement gap: CONTRIBUTING.md required tests but CI did not
check. Now 34/34 *_cmd.rs modules have #[cfg(test)].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-31 12:02:53 +02:00
Florian BRUNIAUX 7e6452c543 Merge pull request #528 from ousamabenyounes/fix/rtk-disabled-warning
warn: emit stderr warning on RTK_DISABLED=1 (#508)
2026-03-31 11:37:24 +02:00
aesoft 14265b48c3 Merge pull request #933 from rtk-ai/maintainers-apply-doc
fix(docs): add maintainers docs
2026-03-30 19:56:32 +02:00
aesoft 0c3aad8156 Update MAINTAINERS_APPLY.md 2026-03-30 19:45:04 +02:00
aesoft 47a76ea35e Merge pull request #932 from rtk-ai/refacto-folders-and-documentation
fix(refacto-p2): more standardize
2026-03-30 19:37:45 +02:00
aesoft 2f7278ac59 fix(docs): add documentation 2026-03-30 19:36:27 +02:00
aesoft 5af18f87ae Merge branch 'develop' into refacto-folders-and-documentation 2026-03-30 19:29:34 +02:00
Adrien Eppling d75e864f20 fix(rules): add wc RtkRule with pattern field for develop compat
Aligns with PR #884 (wc rewrite support) already on develop.
2026-03-30 19:26:44 +02:00
aesoft 92c671a175 Merge pull request #910 from rtk-ai/refacto-files-and-constants
fix(refacto-p2):  more standardize
2026-03-30 18:51:37 +02:00
aesoft 75bd607d55 Merge pull request #904 from rtk-ai/refacto-folders-and-documentation
fix(refacto-p1): unified cmds execution flow  (+ rm dead code)
2026-03-30 18:43:54 +02:00
Florian BRUNIAUXandClaude Sonnet 4.6 bbe3da642b fix(ci): fix validate-docs.sh broken module count check
Two issues:
1. Module count compared top-level `mod` in main.rs (8) against
   "Total: 64 modules" in ARCHITECTURE.md -- incompatible metrics,
   always fails. Replaced with a simple .rs source file count (informational only).
2. CLAUDE.md check for Python/Go commands was too strict -- these
   commands belong in README.md (user-facing), not CLAUDE.md (Claude Code guidance).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-30 18:26:04 +02:00
Florian BRUNIAUXandClaude Sonnet 4.6 a9def11139 chore(skills): add missing frontmatter to all project-level skills
All 8 .claude/skills/ files were missing effort, tags, and allowed-tools
fields. Also added name field to issue-triage, pr-triage, and rtk-triage
which had none. Effort levels inferred from content analysis.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-30 18:22:34 +02:00
Adrien Eppling 0a8b8fd069 fix(review): address PR #910 review feedback
- container.rs: warn on kubectl JSON parse failure instead of silent fallback
- runner.rs: fix savings inflation when filter_stdout_only by tracking stdout only
- README.md: document automod behavior in module registration step
2026-03-30 18:13:39 +02:00
Adrien EpplingandAndrew Hundt f3217a467b fix(registry): quoted env prefix + inline regex cleanup + routing docs
- ENV_PREFIX now handles FOO="bar baz", FOO='val', escaped quotes
- Move 6 inline lazy_static regex to module level
- Merge rewrite_head_numeric + rewrite_tail_lines → rewrite_line_range
- Consolidate head/tail call sites in rewrite_segment
- Add rewrite pipeline documentation to TECHNICAL.md
- Rewrite discover README as concept/flow documentation
- Add lexer-based tokenizer for shell command parsing

Co-Authored-By: Andrew Hundt <ATHundt@gmail.com>
2026-03-30 17:58:03 +02:00
aesoft 08aabb95c3 fix(standardize): merge pattern into rues 2026-03-30 17:58:02 +02:00
aesoft 7fd221f446 fix(standardize): git+kube sub wrappers run_filtered 2026-03-30 17:58:01 +02:00
aesoft 234909d2c7 fix(automod): add auto discovery for cmds 2026-03-30 17:58:00 +02:00
aesoft e48485adc6 fix(cmds): more covering for run_filtered 2026-03-30 17:57:59 +02:00
aesoft aabc0167bc fix(cleaning): constant extract 2026-03-30 17:57:57 +02:00
aesoft ba9fa345f3 fix(cmds): migrate remaining exit_code to exit_code_from_output 2026-03-30 17:55:15 +02:00
Adrien EpplingandClaude Opus 4.6 c1c56f24d7 style: fix cargo fmt in ls.rs assert macros
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 15:02:17 +02:00
aesoft 495a152059 fix(emots): replace 📊 with "Summary:" 2026-03-30 14:41:21 +02:00
Adrien Eppling 9521dcab83 Merge remote-tracking branch 'origin/master' into develop
# Conflicts:
#	src/hooks/init.rs
2026-03-30 12:45:18 +02:00
Florian BRUNIAUX c54afe3da8 Merge pull request #884 from manulqwerty/fix/hook-rewrite-wc 2026-03-30 10:22:55 +02:00
aesoft 48ec28d531 fix(go): align go tool golangci-lint with Result<i32> 2026-03-29 14:08:45 +02:00
aesoft 23c0b7e433 fix(cloud): reuse early exit for edge case 2026-03-29 13:40:57 +02:00
aesoft 078ad1d503 fix(cmds): add run_filtered wrapper to remaining cmd 2026-03-29 13:40:57 +02:00
aesoft 6878819798 fix: remove dead code 2026-03-29 13:40:56 +02:00
aesoft 32ff4663cd fix(cmds): exit code unified return code flow 2026-03-29 13:40:54 +02:00
aesoft 77a0951433 fix(cmds): shared cmd execution flow + clean & update docs
shared cmd exec flow and also removed some notes in technical docs (does not belong here)
2026-03-29 13:40:10 +02:00
aesoft 6444c4b018 Merge pull request #903 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.34.1
2026-03-28 22:27:59 +01:00
github-actions[bot] ad5a155e45 chore(master): release 0.34.1 2026-03-28 21:11:03 +00:00
aesoft 92996b1272 Merge pull request #898 from rtk-ai/cherry-pick-security-fix
fix(telemetry): hash + salt
2026-03-28 22:10:35 +01:00
aesoft 5eae11d164 fix(security): set 0600 permissions on salt file 2026-03-28 14:14:13 +01:00
aesoft 22dc059310 fix(telemetry): cache salt in-process 2026-03-28 14:14:13 +01:00
aesoft 33195cc686 fix(telemetry): docs + real info from "rtk init -g" 2026-03-28 14:14:13 +01:00
aesoft 51f9c888b8 fix(security): missing toml pkg 2026-03-28 14:07:53 +01:00
aesoft 32fdbbbb69 fix(security): salt device hash for telemetry 2026-03-28 14:07:53 +01:00
aesoft 2d2f199983 Merge pull request #883 from rtk-ai/hotfix/telemetry-salt-hash
fix(security): salt device hash for telemetry
2026-03-28 14:00:26 +01:00
aesoft 8ab0f3da47 Merge pull request #706 from shwoop/go-tool-golangci
feat(go): Support golangci-lint via go tool
2026-03-28 11:47:57 +01:00
aesoft 8e42120ea3 fix(security): set 0600 permissions on salt file 2026-03-28 10:46:08 +01:00
Florian BRUNIAUX 9b9075cbb1 Merge pull request #847 from MauroDeryckere/fix/cat-flag-rewrite
Correct fix. cat flags like -A/-v/-e have no rtk read equivalent — skipping rewrite is the right behavior. cat -n correctly preserved. Well tested.
2026-03-28 02:07:23 +01:00
Florian BRUNIAUX a0d6874f7b Merge pull request #677 from TechWizard9999/fix/cargo-clippy-show-error-details
LGTM after code review. truncate() correctly imported, error_details block placed before rule frequency table, test covers the main case. Minor duplication for error[Exxxx] style but not a bug.
2026-03-28 01:57:32 +01:00
Florian BRUNIAUX 9ecdc02aee Merge pull request #753 from sveitser/fix-shebangs
Standard portability fix. /bin/bash is not guaranteed on NixOS or macOS with Homebrew bash. /usr/bin/env bash is the correct practice.
2026-03-28 01:53:02 +01:00
Florian BRUNIAUX 5a0144d185 Merge pull request #763 from mvanhorn/osc/759-include-finished-line-in-cargo-output
Correct. The Finished line carries useful signal (build time + profile). Defensive implementation with Option fallback.
2026-03-28 01:50:18 +01:00
Florian BRUNIAUX 0a5d5d5392 Merge pull request #650 from tobwen/fix/psql-disable-help-flag
Correct fix. disable_help_flag = true is the right pattern for passthrough commands — consistent with other commands in the codebase.
2026-03-28 01:49:32 +01:00
Florian BRUNIAUX da67c3e46a Merge pull request #562 from yogasw/fix/gain-history-utc-to-local-time
Correct fix. UTC timestamps in a local CLI history view is a UX bug — chrono::Local is already a dependency.
2026-03-28 01:48:40 +01:00
Florian BRUNIAUX cb30d174f7 Merge pull request #525 from zerone0x/fix/docs-branch-naming-474
Docs correct — branch names use slash prefixes, not conventional-commit format in parentheses.
2026-03-28 01:46:47 +01:00
Florian BRUNIAUX fb35e23952 Merge pull request #865 from timeshift92/fix/windows-startup-stack-849
LGTM. Correct fix — Clap's command graph can overflow the default 1MB Windows stack. /STACK:8388608 is a standard mitigation.
2026-03-28 01:46:45 +01:00
Florian BRUNIAUX b79623c3a6 fix(ls): suppress summary line when stdout is piped
fix(ls): suppress summary line when stdout is piped
2026-03-28 01:15:21 +01:00
shwoop 8f985a22d1 feat(go): Support golangci-lint via go tool
As of go v1.24, tools such as golanci-lint can be managed via the mod
file and called directly on the go binary via the tool subcommand.

When called via tools, we now apply the same logic to compact the
results as in the directly called command.

Signed-off-by: shwoop <monkey.mambo.al.ferguson@gmail.com>
2026-03-27 19:53:39 +01:00
aesoft 699f68236b fix(telemetry): cache salt in-process 2026-03-27 19:36:41 +01:00
aesoft f7ec883a78 fix(telemetry): docs + real info from "rtk init -g" 2026-03-27 19:28:43 +01:00
aesoft eae2fee0c2 fix(security): missing toml pkg 2026-03-27 19:20:15 +01:00
Manuel LOpez 099a8f3e6d fix(hook): rewrite wc commands to rtk wc 2026-03-27 19:19:35 +01:00
aesoft 60cba0f5d8 fix(security): salt device hash for telemetry 2026-03-27 19:17:00 +01:00
Mauro Deryckere 2fce6bfee7 fix(rewrite): skip cat rewrite when incompatible flags are present
cat flags like -v, -A, -e, -t, -s have different semantics than
rtk read flags (-v means verbose, -n means line numbers). Blindly
forwarding flags caused incorrect behavior (e.g. cat -A file →
rtk read -A file which fails).

Only skip rewrite for incompatible flags. cat -n (line numbers) maps
correctly to rtk read -n, so it is still rewritten for token savings.
Plain `cat file` continues to rewrite to `rtk read file` as before.
2026-03-27 09:13:26 +01:00
Yoga Setiawan 140e1f5958 fix(gain): convert history timestamps from UTC to local timezone 2026-03-27 14:43:34 +07:00
Roopesh def3424eb4 fix(cargo): show clippy error details in compact output
Signed-off-by: Roopesh <roopesh1724989@gmail.com>
2026-03-27 07:18:50 +05:30
Ousama Ben YounesandClaude Opus 4.6 6e0f52b192 docs: update ARCHITECTURE.md module count from 60 to 64
Fixes Documentation Validation CI check (main.rs=64, ARCHITECTURE.md was 60).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-26 19:16:06 +00:00
Ousama Ben YounesandClaude Opus 4.6 6fe769cf00 refactor(ls): remove unnecessary entries.clone() in pipe branch
Avoids one allocation since entries is not used after the if/else.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-26 19:15:44 +00:00
Ousama Ben YounesandClaude Opus 4.6 3e1f75a8d5 fix(ls): suppress summary line when stdout is piped
rtk ls | wc -l returned N+2 instead of N because the summary line
(📊 X files, Y dirs) and blank line were always written to stdout.

Now uses std::io::stdout().is_terminal() to suppress the summary
when piped, following standard Unix convention (ls, grep, find all
do this).

Fixes #482

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-26 19:15:44 +00:00
Ousama Ben YounesandClaude Opus 4.6 4ce95a321f test: add subprocess test for RTK_DISABLED=1 stderr warning
Verifies that `rtk rewrite "RTK_DISABLED=1 git status"` emits the
warning on stderr, not just that rewrite_command returns None.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-26 19:03:09 +00:00
Ousama Ben YounesandClaude Opus 4.6 08d1abc4a8 warn: emit stderr warning when RTK_DISABLED=1 is detected
When the rewrite hook sees RTK_DISABLED=1, it now prints a warning to
stderr before skipping the rewrite. This educates AI agents to stop
overusing the bypass — a real session showed 30% of commands using
RTK_DISABLED=1 unnecessarily, dropping savings from ~65% to 48%.

The warning is on stderr (not stdout) so it doesn't affect command
output or piping. The bypass still works exactly as before.

Fixes #508

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-26 19:03:09 +00:00
Matt Van HornandClaude Opus 4.6 72b1e592d9 fix: include Finished line in cargo build success output
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 11:58:29 -07:00
sveitser bec18c40a2 fix: use /usr/bin/env shebangs for portability across systems 2026-03-26 19:46:28 +01:00
aesoft 2efe860f45 Merge pull request #826 from rtk-ai/refacto-folders-and-documentation
feat(refacto-codebase-onboarding): partie 1 - folders and technical docs
2026-03-26 19:36:50 +01:00
aesoft d9be630bef Merge branch 'develop' of https://github.com/rtk-ai/rtk into refacto-folders-and-documentation 2026-03-26 18:11:34 +01:00
Ахмедов Нурбек Медетбаевич 12276c1743 fix(build): increase Windows startup stack
Signed-off-by: Ахмедов Нурбек Медетбаевич <n.akhmedov@uzdc.uz>
2026-03-26 21:39:11 +05:00
aesoft 91992fd8dc fix(refacto): rm old tmp file 2026-03-25 20:27:53 +01:00
aesoft 135fea693e fix(refacto): conflict w/ dev 2026-03-25 19:56:53 +01:00
aesoft 967d2bfcf9 Merge branch 'develop' of https://github.com/rtk-ai/rtk into refacto-folders-and-documentation 2026-03-25 19:55:42 +01:00
aesoft 0925cf21e0 fix(docs): last review 2026-03-25 19:12:46 +01:00
aesoft 46fa31c4b8 chore(refacto-codebase): Folders + Technical docs
- codebase more clear for humans and AI agents
- alignement on vision and filter quality in technical docs
2026-03-24 22:14:35 +01:00
aesoft f1ac236e46 fix: start folder & docs refacto 2026-03-23 19:00:52 +01:00
zerone0x c253c0168b docs: correct branch naming example (#474) 2026-03-21 08:14:41 +01:00
zerone0xandClaude c5e1d7f559 docs: correct branch naming guidance (#474)
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: zerone0x <hi@trine.dev>
2026-03-21 08:14:36 +01:00
tobwen 41e089759a fix: disable help flag for psql command to allow -h host argument
Fixes #613 - psql flags like -h, -U, -d, -c were being interpreted
as rtk options instead of being forwarded to psql. By disabling the
automatic help flag, psql's own flags can pass through correctly.

Users can still access psql help via 'rtk psql --help'.
2026-03-20 06:51:02 +00:00
175 changed files with 5887 additions and 5335 deletions

No files matched your search

+9 -7
View File
@@ -14,13 +14,15 @@ Prevent bugs, performance regressions, and token savings failures before they re
## RTK Architecture Context
```
main.rs (Commands enum + routing)
→ *_cmd.rs modules (filter logic)
→ tracking.rs (SQLite, token metrics)
→ utils.rs (shared helpers)
→ tee.rs (failure recovery)
→ config.rs (user config)
→ filter.rs (language-aware filtering)
src/main.rs (Commands enum + routing)
→ src/cmds/**/*_cmd.rs (filter logic, organized by ecosystem)
→ src/core/tracking.rs (SQLite, token metrics)
→ src/core/utils.rs (shared helpers)
→ src/core/tee.rs (failure recovery)
→ src/core/config.rs (user config)
→ src/core/filter.rs (language-aware filtering)
→ src/hooks/ (init, rewrite, verify, trust)
→ src/analytics/ (gain, cc_economics, ccusage)
```
**Non-negotiable constraints:**
+20 -11
View File
@@ -337,7 +337,7 @@ docker run --rm -v $(pwd):/rtk -w /rtk rust:latest cargo test
newcmd --some-args > tests/fixtures/newcmd_raw.txt
```
2. **Add snapshot test** to `src/newcmd_cmd.rs`:
2. **Add snapshot test** to `src/cmds/<ecosystem>/newcmd_cmd.rs`:
```rust
#[cfg(test)]
mod tests {
@@ -439,18 +439,27 @@ cargo test --ignored
```
rtk/
├── src/
│ ├── git.rs # Filter implementation
│ │ └── #[cfg(test)] mod tests { ... } # Unit tests
│ ├── snapshots/ # Insta snapshots (gitignored pattern)
│ │ └── git.rs.snap # Snapshot for git tests
│ ├── cmds/
│ │ ├── git/
│ │ │ ├── git.rs # Filter implementation
│ │ │ │ └── #[cfg(test)] mod tests { ... } # Unit tests
│ │ │ └── snapshots/ # Insta snapshots for git module
│ │ ├── js/
│ │ ├── python/
│ │ └── ... # Other ecosystems
│ ├── core/
│ │ ├── filter.rs # Core filtering with tests
│ │ └── snapshots/
│ └── hooks/
├── tests/
│ ├── common/
│ │ └── mod.rs # Shared test utilities (count_tokens, etc.)
│ ├── fixtures/ # Real command output fixtures
│ │ ├── git_log_raw.txt # Real git log output
│ │ ├── cargo_test_raw.txt # Real cargo test output
│ │ └── gh_pr_view_raw.txt # Real gh pr view output
│ └── integration_test.rs # Integration tests (#[ignore])
│ │ └── mod.rs # Shared test utilities (count_tokens, etc.)
│ ├── fixtures/ # Real command output fixtures
│ │ ├── git_log_raw.txt
│ │ ├── cargo_test_raw.txt
│ │ ├── gh_pr_view_raw.txt
│ │ └── dotnet/ # Dotnet-specific fixtures
│ └── integration_test.rs # Integration tests (#[ignore])
```
**Best practices**:
+36 -24
View File
@@ -306,20 +306,27 @@ fn test_real_git_log() {
## Key Files Reference
**Core modules**:
**Core infrastructure** (`src/core/`):
- `src/main.rs` - CLI entry point, Clap command parsing, routing to modules
- `src/git.rs` - Git operations filter (log, status, diff, etc.)
- `src/grep_cmd.rs` - Code search filter (grep, ripgrep)
- `src/runner.rs` - Command execution filter (test, err)
- `src/utils.rs` - Shared utilities (truncate, strip_ansi, execute_command)
- `src/tracking.rs` - SQLite token savings tracking (`rtk gain`)
- `src/core/utils.rs` - Shared utilities (truncate, strip_ansi, execute_command)
- `src/core/tracking.rs` - SQLite token savings tracking (`rtk gain`)
- `src/core/filter.rs` - Language-aware code filtering engine
- `src/core/tee.rs` - Raw output recovery on failure
- `src/core/config.rs` - User configuration (~/.config/rtk/config.toml)
**Filter modules** (see CLAUDE.md Module Responsibilities table):
- `src/lint_cmd.rs`, `src/tsc_cmd.rs`, `src/next_cmd.rs` - JavaScript/TypeScript tooling
- `src/prettier_cmd.rs`, `src/playwright_cmd.rs`, `src/prisma_cmd.rs` - Modern JS stack
- `src/pnpm_cmd.rs`, `src/vitest_cmd.rs` - Package manager, test runner
- `src/ruff_cmd.rs`, `src/pytest_cmd.rs`, `src/pip_cmd.rs` - Python ecosystem
- `src/go_cmd.rs`, `src/golangci_cmd.rs` - Go ecosystem
**Command modules** (`src/cmds/<ecosystem>/`):
- `src/cmds/git/` - git.rs, gh_cmd.rs, gt_cmd.rs, diff_cmd.rs
- `src/cmds/rust/` - cargo_cmd.rs, runner.rs
- `src/cmds/js/` - lint_cmd.rs, tsc_cmd.rs, next_cmd.rs, prettier_cmd.rs, playwright_cmd.rs, prisma_cmd.rs, vitest_cmd.rs, pnpm_cmd.rs, npm_cmd.rs
- `src/cmds/python/` - ruff_cmd.rs, pytest_cmd.rs, mypy_cmd.rs, pip_cmd.rs
- `src/cmds/go/` - go_cmd.rs, golangci_cmd.rs
- `src/cmds/ruby/` - rake_cmd.rs, rspec_cmd.rs, rubocop_cmd.rs
- `src/cmds/cloud/` - aws_cmd.rs, container.rs, curl_cmd.rs, wget_cmd.rs, psql_cmd.rs
- `src/cmds/system/` - ls.rs, tree.rs, read.rs, grep_cmd.rs, find_cmd.rs, etc.
**Hook & analytics** (`src/hooks/`, `src/analytics/`):
- `src/hooks/init.rs` - rtk init command
- `src/analytics/gain.rs` - rtk gain command
**Tests**:
- `tests/fixtures/` - Real command output fixtures for testing
@@ -401,11 +408,11 @@ When adding a new filter (e.g., `rtk newcmd`):
### 1. Create Module
```bash
touch src/newcmd_cmd.rs
touch src/cmds/<ecosystem>/newcmd_cmd.rs
```
```rust
// src/newcmd_cmd.rs
// src/cmds/<ecosystem>/newcmd_cmd.rs
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
@@ -436,18 +443,23 @@ mod tests {
}
```
### 2. Add to main.rs Commands Enum
### 2. Register Module
Add to ecosystem `mod.rs` (e.g., `src/cmds/system/mod.rs`):
```rust
// src/main.rs
#[derive(Subcommand)]
enum Commands {
// ... existing commands
Newcmd {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
}
pub mod newcmd_cmd;
```
Add to `src/main.rs` Commands enum and routing:
```rust
// Add use import
use cmds::system::newcmd_cmd;
// In Commands enum
Newcmd {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
// In match statement
Commands::Newcmd { args } => {
+15 -12
View File
@@ -30,21 +30,24 @@ Think in terms of filter families, not individual commands. Every new `*_cmd.rs`
## RTK Architecture Map
```
main.rs
src/main.rs
├── Commands enum (clap derive)
│ ├── Git(GitArgs) → git.rs
│ ├── Cargo(CargoArgs) → runner.rs
│ ├── Gh(GhArgs) → gh_cmd.rs
│ ├── Grep(GrepArgs) → grep_cmd.rs
│ ├── ... → *_cmd.rs
│ ├── Gain → tracking.rs
│ ├── Git(GitArgs) → cmds/git/git.rs
│ ├── Cargo(CargoArgs) → cmds/rust/runner.rs
│ ├── Gh(GhArgs) → cmds/git/gh_cmd.rs
│ ├── Grep(GrepArgs) → cmds/system/grep_cmd.rs
│ ├── ... → cmds/<ecosystem>/*_cmd.rs
│ ├── Gain → analytics/gain.rs
│ └── Proxy(ProxyArgs) → passthrough
│
├── tracking.rs ← SQLite, token metrics, 90-day retention
├── config.rs ← ~/.config/rtk/config.toml
├── tee.rs ← Raw output recovery on failure
├── filter.rs ← Language-aware code filtering
└── utils.rs ← strip_ansi, truncate, execute_command
├── core/
│ ├── tracking.rs ← SQLite, token metrics, 90-day retention
│ ├── config.rs ← ~/.config/rtk/config.toml
│ ├── tee.rs ← Raw output recovery on failure
│ ├── filter.rs ← Language-aware code filtering
│ └── utils.rs ← strip_ansi, truncate, execute_command
├── hooks/ ← init, rewrite, verify, trust, integrity
└── analytics/ ← gain, cc_economics, ccusage, session_cmd
```
**TOML Filter DSL** (v0.25.0+):
+2 -2
View File
@@ -227,11 +227,11 @@ echo $LAST_COMMAND # Should show "rtk git status"
### 1. Create Filter Module
```bash
touch src/newcmd_cmd.rs
touch src/cmds/<ecosystem>/newcmd_cmd.rs
```
```rust
// src/newcmd_cmd.rs
// src/cmds/<ecosystem>/newcmd_cmd.rs
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
+5 -4
View File
@@ -57,11 +57,12 @@ git diff "$BASE_BRANCH"...HEAD --stat
| Si le diff contient... | Vérifier |
| ------------------------------ | ------------------------------------------ |
| `src/*.rs` | CLAUDE.md sections Error Handling + Tests |
| `src/filter.rs` ou `*_cmd.rs` | Filter Development Checklist (CLAUDE.md) |
| `src/**/*.rs` | CLAUDE.md sections Error Handling + Tests |
| `src/core/filter.rs` ou `src/cmds/**/*_cmd.rs` | Filter Development Checklist (CLAUDE.md) |
| `src/main.rs` | Command routing + Commands enum |
| `src/tracking.rs` | SQLite patterns + DB path config |
| `src/config.rs` | Configuration system + init patterns |
| `src/core/tracking.rs` | SQLite patterns + DB path config |
| `src/core/config.rs` | Configuration system |
| `src/hooks/init.rs` | Init patterns + hook installation |
| `.github/workflows/` | CI/CD multi-platform build targets |
| `tests/` ou `fixtures/` | Testing Strategy (CLAUDE.md) |
| `Cargo.toml` | Dependencies + build optimizations |
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Auto-format Rust code before commits
# Hook: PreToolUse for git commit
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# rtk-hook-version: 3
# RTK auto-rewrite hook for Claude Code PreToolUse:Bash
# Transparently rewrites raw commands to their RTK equivalents.
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# RTK suggest hook for Claude Code PreToolUse:Bash
# Emits system reminders when rtk-compatible commands are detected.
# Outputs JSON with systemMessage to inform Claude Code without modifying execution.
+19 -11
View File
@@ -43,7 +43,7 @@ fn test_git_log_output() {
git log -20 > tests/fixtures/git_log_raw.txt
# 2. Write test with assert_snapshot!
cat > src/git.rs <<'EOF'
cat > src/cmds/git/git.rs <<'EOF'
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
@@ -64,7 +64,7 @@ cargo test test_git_log_format
cargo insta review
# Press 'a' to accept, 'r' to reject
# 5. Snapshot saved in src/snapshots/git.rs.snap
# 5. Snapshot saved in src/cmds/git/snapshots/git__tests__*.snap
```
## Token Accuracy Testing (🔴 Critical)
@@ -299,24 +299,32 @@ diff /tmp/before.txt /tmp/after.txt
```
rtk/
├── src/
│ ├── git.rs # Filter implementation
│ │ └── #[cfg(test)] mod tests { ... } # Unit tests
│ ├── snapshots/ # Insta snapshots
│ │ └── git.rs.snap # Snapshot for git tests
│ ├── cmds/
│ │ ├── git/
│ │ │ ├── git.rs # Filter implementation
│ │ │ │ └── #[cfg(test)] mod tests { ... }
│ │ │ └── snapshots/ # Insta snapshots for git module
│ │ ├── js/ # JS/TS ecosystem filters
│ │ ├── python/ # Python ecosystem filters
│ │ └── ...
│ ├── core/ # Shared infrastructure
│ ├── hooks/ # Hook system
│ └── analytics/ # Token savings analytics
├── tests/
│ ├── common/
│ │ └── mod.rs # Shared test utilities (count_tokens)
│ ├── fixtures/ # Real command output
│ │ └── mod.rs # Shared test utilities (count_tokens)
│ ├── fixtures/ # Real command output
│ │ ├── git_log_raw.txt
│ │ ├── cargo_test_raw.txt
│ │ └── gh_pr_view_raw.txt
│ └── integration_test.rs # Integration tests (#[ignore])
│ │ ├── gh_pr_view_raw.txt
│ │ └── dotnet/ # Dotnet-specific fixtures
│ └── integration_test.rs # Integration tests (#[ignore])
```
**Best practices**:
- **Unit tests**: Embedded in module (`#[cfg(test)] mod tests`)
- **Fixtures**: Real command output in `tests/fixtures/`
- **Snapshots**: Auto-generated in `src/snapshots/` (by insta)
- **Snapshots**: Auto-generated in `src/cmds/<ecosystem>/snapshots/` (by insta)
- **Shared utils**: `tests/common/mod.rs` (count_tokens, helpers)
- **Integration**: `tests/` with `#[ignore]` attribute
+49 -26
View File
@@ -15,20 +15,43 @@ Never use Bash for search (`find`, `grep`, `rg`) — use dedicated tools.
```
src/
├── main.rs ← Commands enum + routing (start here for any command)
├── git.rs ← Git operations (log, status, diff)
├── runner.rs ← Cargo commands (test, build, clippy, check)
├── gh_cmd.rs ← GitHub CLI (pr, run, issue)
├── grep_cmd.rs ← Code search output filtering
├── ls.rs ← Directory listing
├── read.rs ← File reading with filter levels
├── filter.rs ← Language-aware code filtering engine
├── tracking.rs ← SQLite token metrics
├── config.rs ← ~/.config/rtk/config.toml
├── tee.rs ← Raw output recovery on failure
├── utils.rs ← strip_ansi, truncate, execute_command
├── init.rs ← rtk init command
└── *_cmd.rs ← All other command modules
├── main.rs ← Commands enum + routing (start here for any command)
├── core/ ← Shared infrastructure
│ ├── config.rs ← ~/.config/rtk/config.toml
│ ├── tracking.rs ← SQLite token metrics
│ ├── tee.rs ← Raw output recovery on failure
│ ├── utils.rs ← strip_ansi, truncate, execute_command
│ ├── filter.rs ← Language-aware code filtering engine
│ ├── toml_filter.rs ← TOML DSL filter engine
│ ├── display_helpers.rs ← Terminal formatting helpers
│ └── telemetry.rs ← Analytics ping
├── hooks/ ← Hook system
│ ├── init.rs ← rtk init command
│ ├── rewrite_cmd.rs ← rtk rewrite command
│ ├── hook_cmd.rs ← Gemini/Copilot hook processors
│ ├── hook_check.rs ← Hook status detection
│ ├── verify_cmd.rs ← rtk verify command
│ ├── trust.rs ← Project trust/untrust
│ └── integrity.rs ← SHA-256 hook verification
├── analytics/ ← Token savings analytics
│ ├── gain.rs ← rtk gain command
│ ├── cc_economics.rs ← Claude Code economics
│ ├── ccusage.rs ← ccusage data parsing
│ └── session_cmd.rs ← Session adoption reporting
├── cmds/ ← Command filter modules
│ ├── git/ ← git, gh, gt, diff
│ ├── rust/ ← cargo, runner (err/test)
│ ├── js/ ← npm, pnpm, vitest, lint, tsc, next, prettier, playwright, prisma
│ ├── python/ ← ruff, pytest, mypy, pip
│ ├── go/ ← go, golangci-lint
│ ├── dotnet/ ← dotnet, binlog, trx, format_report
│ ├── cloud/ ← aws, container (docker/kubectl), curl, wget, psql
│ ├── system/ ← ls, tree, read, grep, find, wc, env, json, log, deps, summary, format, local_llm
│ └── ruby/ ← rake, rspec, rubocop
├── discover/ ← Claude Code history analysis
├── learn/ ← CLI correction detection
├── parser/ ← Parser infrastructure
└── filters/ ← 60 TOML filter configs
```
## Common Search Patterns
@@ -40,7 +63,7 @@ src/
Grep pattern="Gh\|Cargo\|Git\|Grep" path="src/main.rs" output_mode="content"
# Step 2: Follow to module
Read file_path="src/gh_cmd.rs"
Read file_path="src/cmds/git/gh_cmd.rs"
```
### "Where is function X defined?"
@@ -52,8 +75,8 @@ Grep pattern="fn filter_git_log\|fn run\b" type="rust"
### "All command modules"
```
Glob pattern="src/*_cmd.rs"
# Then: src/git.rs, src/runner.rs for non-*_cmd.rs modules
Glob pattern="src/cmds/**/*_cmd.rs"
# Also: src/cmds/git/git.rs, src/cmds/rust/runner.rs, src/cmds/cloud/container.rs
```
### "Find all lazy_static regex definitions"
@@ -92,27 +115,27 @@ Glob pattern="tests/fixtures/*.txt"
### Adding a new filter
1. Check `src/main.rs` for Commands enum structure
2. Check existing `*_cmd.rs` for patterns to follow (e.g., `src/gh_cmd.rs`)
3. Check `src/utils.rs` for shared helpers before reimplementing
2. Check existing modules in `src/cmds/<ecosystem>/` for patterns to follow (e.g., `src/cmds/git/gh_cmd.rs`)
3. Check `src/core/utils.rs` for shared helpers before reimplementing
4. Check `tests/fixtures/` for existing fixture patterns
### Debugging filter output
1. Start with `src/<cmd>_cmd.rs` → find `run()` function
1. Start with `src/cmds/<ecosystem>/<cmd>_cmd.rs` → find `run()` function
2. Trace filter function (usually `filter_<cmd>()`)
3. Check `lazy_static!` regex patterns in same file
4. Check `src/utils.rs::strip_ansi()` if ANSI codes involved
4. Check `src/core/utils.rs::strip_ansi()` if ANSI codes involved
### Tracking/metrics issues
1. `src/tracking.rs` → `track_command()` function
2. `src/config.rs` → `tracking.database_path` field
1. `src/core/tracking.rs` → `track_command()` function
2. `src/core/config.rs` → `tracking.database_path` field
3. `RTK_DB_PATH` env var overrides config
### Configuration issues
1. `src/config.rs` → `RtkConfig` struct
2. `src/init.rs` → `rtk init` command
1. `src/core/config.rs` → `RtkConfig` struct
2. `src/hooks/init.rs` → `rtk init` command
3. Config file: `~/.config/rtk/config.toml`
4. Filter files: `~/.config/rtk/filters/` (global) or `.rtk/filters/` (project)
@@ -120,7 +143,7 @@ Glob pattern="tests/fixtures/*.txt"
```
Glob pattern=".rtk/filters/*.toml" # Project-local filters
Glob pattern="src/filter_*.rs" # TOML filter engine
Glob pattern="src/core/toml_filter.rs" # TOML filter engine
Grep pattern="FilterRule\|FilterConfig" type="rust"
```
+7
View File
@@ -7,6 +7,13 @@ triggers:
- "over-engineered"
- "refactor this"
- "make this idiomatic"
allowed-tools:
- Read
- Grep
- Glob
- Edit
effort: low
tags: [rust, simplify, refactor, idioms, rtk]
---
# RTK Code Simplifier
+6
View File
@@ -6,6 +6,12 @@ triggers:
- "how to structure"
- "best pattern for"
- "refactor to pattern"
allowed-tools:
- Read
- Grep
- Glob
effort: medium
tags: [rust, design-patterns, architecture, newtype, builder, rtk]
---
# RTK Rust Design Patterns
+7
View File
@@ -1,7 +1,14 @@
---
name: issue-triage
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.
allowed-tools:
- Bash
- Read
- Grep
effort: medium
tags: [triage, issues, github, categorize, duplicates, risk]
---
# Issue Triage
+6
View File
@@ -8,6 +8,12 @@ triggers:
- "benchmark"
- "binary size"
- "memory usage"
allowed-tools:
- Bash
- Read
- Grep
effort: medium
tags: [performance, benchmark, startup, binary-size, memory, rtk]
---
# RTK Performance Analysis
+8
View File
@@ -1,7 +1,15 @@
---
name: pr-triage
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.
allowed-tools:
- Bash
- Read
- Grep
- Glob
effort: medium
tags: [triage, pr, github, review, code-review, rtk]
---
# PR Triage
+7
View File
@@ -5,6 +5,13 @@ description: >
implementation, testing, refactoring, and bug fixing tasks. Provides
Rust-idiomatic testing patterns with anyhow/thiserror, cfg(test), and
Arrange-Act-Assert workflow.
allowed-tools:
- Read
- Write
- Edit
- Bash
effort: medium
tags: [tdd, testing, rust, red-green-refactor, rtk]
---
# Rust TDD Workflow
+3
View File
@@ -1,4 +1,5 @@
---
name: rtk-triage
description: >
Triage complet RTK : exécute issue-triage + pr-triage en parallèle,
puis croise les données pour détecter doubles couvertures, trous sécurité,
@@ -9,6 +10,8 @@ allowed-tools:
- Write
- Read
- AskUserQuestion
effort: high
tags: [triage, orchestration, issues, pr, security, cross-analysis, rtk]
---
# /rtk-triage
+7
View File
@@ -8,6 +8,13 @@ triggers:
- "write tests for"
- "test coverage"
- "fix failing test"
allowed-tools:
- Read
- Write
- Edit
- Bash
effort: medium
tags: [tdd, testing, rust, filters, snapshots, token-savings, rtk]
---
# RTK TDD Workflow
+19 -80
View File
@@ -1,10 +1,10 @@
# Copilot Instructions for rtk
**rtk (Rust Token Killer)** is a CLI proxy that filters and compresses command outputs before they reach an LLM context, saving 60–90% of tokens. It wraps common tools (`git`, `cargo`, `grep`, `pnpm`, `go`, etc.) and outputs condensed summaries instead of raw output.
**rtk (Rust Token Killer)** is a CLI proxy that filters and compresses command outputs before they reach an LLM context, saving 60-90% of tokens. It wraps common tools (`git`, `cargo`, `grep`, `pnpm`, `go`, etc.) and outputs condensed summaries instead of raw output.
## Using rtk in this session
**Always prefix commands with `rtk` when running shell commands** — this is the entire point of the project and reduces token consumption for every operation you perform.
**Always prefix commands with `rtk` when running shell commands** — this reduces token consumption for every operation you perform.
```bash
# Instead of: Use:
@@ -17,7 +17,7 @@ grep -r "pattern" src/ rtk grep -r "pattern" src/
**rtk meta-commands** (always use these directly, no prefix needed):
```bash
rtk gain # Show token savings analytics for this session
rtk gain # Show token savings analytics
rtk gain --history # Full command history with per-command savings
rtk discover # Scan session history for missed rtk opportunities
rtk proxy <cmd> # Run a command raw (no filtering) but still track it
@@ -29,99 +29,38 @@ rtk --version # Should print: rtk X.Y.Z
rtk gain # Should show a dashboard (not "command not found")
```
> ⚠️ **Name collision**: `rtk gain` failing means you have `reachingforthejack/rtk` (Rust Type Kit) installed instead of this project. Run `which rtk` and check the binary source.
> Name collision: `rtk gain` failing means you have `reachingforthejack/rtk` (Rust Type Kit) installed instead. Run `which rtk` to check.
## Build, Test & Lint
```bash
# Development build
cargo build
# Run all tests
cargo test
# Run a single test by name
cargo test test_filter_git_log
# Run all tests in a module
cargo test git::tests::
# Run tests with stdout
cargo test -- --nocapture
cargo build # Development build
cargo test # All tests
cargo test test_name # Single test
cargo test module::tests:: # Module tests
cargo test -- --nocapture # With stdout
# Pre-commit gate (must all pass before any PR)
cargo fmt --all --check && cargo clippy --all-targets && cargo test
# Smoke tests (requires installed binary)
bash scripts/test-all.sh
bash scripts/test-all.sh # Smoke tests (requires installed binary)
```
PRs target the **`develop`** branch, not `main`. All commits require a DCO sign-off (`git commit -s`).
## Architecture
```
main.rs ← Clap Commands enum → specialized module (git.rs, *_cmd.rs, etc.)
↓
execute subprocess
↓
filter/compress output
↓
tracking::TimedExecution → SQLite (~/.local/share/rtk/tracking.db)
```
rtk routes CLI commands via a Clap `Commands` enum in `main.rs` to specialized filter modules in `src/cmds/*/`, each executing the underlying command and compressing output. Token savings are tracked in SQLite via `src/core/tracking.rs`.
Key modules:
- **`main.rs`** — Clap `Commands` enum routes every subcommand to its module. Each arm calls `tracking::TimedExecution::start()` before running, then `.track(...)` after.
- **`filter.rs`** — Language-aware filtering with `FilterLevel` (`none` / `minimal` / `aggressive`) and `Language` enum. Used by `read` and `smart` commands.
- **`tracking.rs`** — SQLite persistence for token savings, scoped per project path. Powers `rtk gain`.
- **`tee.rs`** — On filter failure, saves raw output to `~/.local/share/rtk/tee/` and prints a one-line hint so the LLM can re-read without re-running the command.
- **`utils.rs`** — Shared helpers: `truncate`, `strip_ansi`, `execute_command`, package-manager auto-detection (pnpm/yarn/npm/npx).
New commands follow this structure: one file `src/<cmd>_cmd.rs` with a `pub fn run(...)` entry point, registered in the `Commands` enum in `main.rs`.
For full details see [ARCHITECTURE.md](../ARCHITECTURE.md) and [docs/TECHNICAL.md](../docs/TECHNICAL.md). Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header.
## Key Conventions
### Error handling
- Use `anyhow::Result` throughout (this is a binary, not a library).
- Always attach context: `operation.context("description")?` — never bare `?` without context.
- No `unwrap()` in production code; `expect("reason")` is acceptable only in tests.
- Every filter must fall back to raw command execution on error — never break the user's workflow.
- **Error handling**: `anyhow::Result` with `.context("description")?` — no bare `?`, no `unwrap()` in production. Filters must fall back to raw command on error.
- **Regex**: Always `lazy_static!`, never compile inside a function body.
- **Testing**: Unit tests inside modules (`#[cfg(test)] mod tests`). Fixtures in `tests/fixtures/`. Token savings assertions with `count_tokens()`.
- **Exit codes**: Preserve the underlying command's exit code via `std::process::exit(code)`.
- **Performance**: Startup <10ms (no async runtime), binary <5MB stripped.
- **Branch naming**: `fix(scope):`, `feat(scope):`, `chore(scope):` where scope is the affected component.
### Regex
- Compile once with `lazy_static!`, never inside a function body:
```rust
lazy_static! {
static ref RE: Regex = Regex::new(r"pattern").unwrap();
}
```
### Testing
- Unit tests live **inside the module file** in `#[cfg(test)] mod tests { ... }` — not in `tests/`.
- Fixtures are real captured command output in `tests/fixtures/<cmd>_raw.txt`, loaded with `include_str!("../tests/fixtures/...")`.
- Each test module defines its own local `fn count_tokens(text: &str) -> usize` (word-split approximation) — there is no shared utility for this.
- Token savings assertions use `assert!(savings >= 60.0, ...)`.
- Snapshot tests use `assert_snapshot!()` from the `insta` crate; review with `cargo insta review`.
### Adding a new command
1. Create `src/<cmd>_cmd.rs` with `pub fn run(...)`.
2. Add `mod <cmd>_cmd;` at the top of `main.rs`.
3. Add a variant to the `Commands` enum with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]` for pass-through flags.
4. Route the variant in the `match` block, wrapping execution with `tracking::TimedExecution`.
5. Write a fixture from real output, then unit tests in the module file.
6. Update `README.md` (command list + savings %) and `CHANGELOG.md`.
### Exit codes
Preserve the underlying command's exit code. Use `std::process::exit(code)` when the child process exits non-zero.
### Performance constraints
- Startup must stay under 10ms — no async runtime (no `tokio`/`async-std`).
- No blocking I/O at startup; config is loaded on-demand.
- Binary size target: <5 MB stripped.
### Branch naming
```
fix(scope): short-description
feat(scope): short-description
chore(scope): short-description
```
`scope` is the affected component (e.g. `git`, `filter`, `tracking`).
For the full contribution workflow, design philosophy, and new-filter checklist, see [CONTRIBUTING.md](../CONTRIBUTING.md).
+12
View File
@@ -14,6 +14,18 @@ env:
jobs:
# ─── Fast gates (fail early, save CI minutes) ───
check-test-presence:
name: test presence
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 50
- name: Check filter modules have tests
run: |
git fetch origin "${{ github.base_ref }}" --depth=1 || true
bash scripts/check-test-presence.sh "origin/${{ github.base_ref }}"
fmt:
name: fmt
runs-on: ubuntu-latest
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.34.0"
".": "0.34.1"
}
+50 -518
View File
@@ -1,8 +1,8 @@
# rtk Architecture Documentation
> **rtk (Rust Token Killer)** - A high-performance CLI proxy that minimizes LLM token consumption through intelligent output filtering and compression.
> **Deep reference** for RTK's system design, filtering taxonomy, performance characteristics, and architecture decisions. For a guided tour of the end-to-end flow, start with [docs/TECHNICAL.md](docs/TECHNICAL.md).
This document provides a comprehensive architectural overview of rtk, including system design, data flows, module organization, and implementation patterns.
**rtk (Rust Token Killer)** is a high-performance CLI proxy that minimizes LLM token consumption through intelligent output filtering and compression.
---
@@ -17,51 +17,16 @@ This document provides a comprehensive architectural overview of rtk, including
7. [Global Flags Architecture](#global-flags-architecture)
8. [Error Handling](#error-handling)
9. [Configuration System](#configuration-system)
10. [Module Development Pattern](#module-development-pattern)
10. [Common Patterns](#common-patterns)
11. [Build Optimizations](#build-optimizations)
12. [Extensibility Guide](#extensibility-guide)
13. [Architecture Decision Records](#architecture-decision-records)
---
## System Overview
### Proxy Pattern Architecture
```
┌────────────────────────────────────────────────────────────────────────┐
│ rtk - Token Optimization Proxy │
└────────────────────────────────────────────────────────────────────────┘
User Input CLI Layer Router Module Layer
────────── ───────── ────── ────────────
$ rtk git log ─→ Clap Parser ─→ Commands ─→ git::run()
-v --oneline (main.rs) enum match
• Parse args Execute: git log
• Extract flags Capture output
• Route command ↓
Filter/Compress
↓
$ 3 commits ←─ Terminal ←─ Format ←─ Compact Stats
+142/-89 colored optimized (90% reduction)
output ↓
tracking::track()
↓
SQLite INSERT
(~/.local/share/rtk/)
```
### Key Components
| Component | Location | Responsibility |
|-----------|----------|----------------|
| **CLI Parser** | main.rs | Clap-based argument parsing, global flags |
| **Command Router** | main.rs | Dispatch to specialized modules |
| **Module Layer** | src/*_cmd.rs, src/git.rs, etc. | Command execution + filtering |
| **Shared Utils** | utils.rs | Package manager detection, text processing |
| **Filter Engine** | filter.rs | Language-aware code filtering |
| **Tracking** | tracking.rs | SQLite-based token metrics |
| **Config** | config.rs, init.rs | User preferences, LLM integration |
> For the proxy pattern diagram and key components table, see [docs/TECHNICAL.md](docs/TECHNICAL.md#2-architecture-overview).
### Design Principles
@@ -73,39 +38,7 @@ $ 3 commits ←─ Terminal ←─ Format ←─ Compact Sta
### Hook Architecture (v0.9.5+)
The recommended deployment mode uses a Claude Code PreToolUse hook for 100% transparent command rewriting.
```
┌────────────────────────────────────────────────────────────────────────┐
│ Hook-Based Command Rewriting │
└────────────────────────────────────────────────────────────────────────┘
Claude Code settings.json rtk-rewrite.sh RTK binary
│ │ │ │
│ Bash: "git status" │ │ │
│ ─────────────────────►│ │ │
│ │ PreToolUse hook │ │
│ │ ───────────────────►│ │
│ │ │ detect: git │
│ │ │ rewrite: │
│ │ │ rtk git status │
│ │◄────────────────────│ │
│ │ updatedInput │ │
│ │ │
│ execute: rtk git status ────────────────────────────────────────►
│ │ run git
│ │ filter
│ │ track
│◄──────────────────────────────────────────────────────────────────
│ "3 modified, 1 untracked ✓" (~10 tokens vs ~200 raw)
│
│ Claude never sees the rewrite — it only sees optimized output.
Files:
~/.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)
```
> For the hook interception diagram and agent-specific JSON formats, see [docs/TECHNICAL.md](docs/TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](hooks/README.md).
Two hook strategies:
@@ -224,91 +157,42 @@ Database: ~/.local/share/rtk/history.db
## Module Organization
### Complete Module Map (30 Modules)
### Module Map
> For the full file-level module tree, see [docs/TECHNICAL.md](docs/TECHNICAL.md#4-folder-map) and each folder's README.
**Token savings by ecosystem:**
```
┌────────────────────────────────────────────────────────────────────────┐
│ Module Organization │
└────────────────────────────────────────────────────────────────────────┘
Category Module Commands Savings File
──────────────────────────────────────────────────────────────────────────
GIT git.rs status, diff, log 85-99% ✓
add, commit, push
branch, checkout
CODE SEARCH grep_cmd.rs grep 60-80% ✓
diff_cmd.rs diff 70-85% ✓
find_cmd.rs find 50-70% ✓
FILE OPS ls.rs ls 50-70% ✓
read.rs read 40-90% ✓
EXECUTION runner.rs err, test 60-99% ✓
summary.rs smart (heuristic) 50-80% ✓
local_llm.rs smart (LLM mode) 60-90% ✓
LOGS/DATA log_cmd.rs log 70-90% ✓
json_cmd.rs json 80-95% ✓
JS/TS STACK lint_cmd.rs lint 84% ✓
tsc_cmd.rs tsc 83% ✓
next_cmd.rs next 87% ✓
prettier_cmd.rs prettier 70% ✓
playwright_cmd.rs playwright 94% ✓
prisma_cmd.rs prisma 88% ✓
vitest_cmd.rs vitest 99.5% ✓
pnpm_cmd.rs pnpm 70-90% ✓
CONTAINERS container.rs podman, docker 60-80% ✓
VCS gh_cmd.rs gh 26-87% ✓
PYTHON ruff_cmd.rs ruff check/format 80%+ ✓
pytest_cmd.rs pytest 90%+ ✓
pip_cmd.rs pip list/outdated 70-85% ✓
GO go_cmd.rs go test/build/vet 75-90% ✓
golangci_cmd.rs golangci-lint 85% ✓
RUBY rake_cmd.rs rake/rails test 85-90% ✓
rspec_cmd.rs rspec 60%+ ✓
rubocop_cmd.rs rubocop 60%+ ✓
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% ✓
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 ✓
permissions.rs CC permission checks N/A ✓
SHARED utils.rs Helpers N/A ✓
filter.rs Language filters N/A ✓
tracking.rs Token tracking N/A ✓
tee.rs Full output recovery N/A ✓
Savings by ecosystem:
GIT (cmds/git/) 85-99% status, diff, log, gh, gt
JS/TS (cmds/js/) 70-99% lint, tsc, next, prettier, playwright, prisma, vitest, pnpm
PYTHON (cmds/python/) 70-90% ruff, pytest, mypy, pip
GO (cmds/go/) 75-90% go test/build/vet, golangci-lint
RUBY (cmds/ruby/) 60-90% rake, rspec, rubocop
DOTNET (cmds/dotnet/) 70-85% dotnet build/test, binlog
CLOUD (cmds/cloud/) 60-80% aws, docker/kubectl, curl, wget, psql
SYSTEM (cmds/system/) 50-90% ls, tree, read, grep, find, json, log, env, deps
RUST (cmds/rust/) 60-99% cargo test/build/clippy, err
```
**Total: 71 modules** (49 command modules + 22 infrastructure modules)
**Total: 64 modules** (42 command modules + 22 infrastructure modules)
### Module Breakdown
- **Command Modules**: `src/cmds/` — organized by ecosystem (git, rust, js, python, go, dotnet, cloud, system, ruby). Each ecosystem README lists its files.
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, tee, config, toml_filter, display_helpers, telemetry
- **Hook System**: `src/hooks/` — init, rewrite, permissions, hook_cmd, hook_check, hook_audit, verify, trust, integrity
- **Analytics**: `src/analytics/` — gain, cc_economics, ccusage, session_cmd
### Module Count Breakdown
- **Command Modules**: 45 (directly exposed to users)
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, trust, etc.)
- **Command Modules**: 42 (directly exposed to users)
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, etc.)
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
- **Python Tooling**: 3 modules (ruff, pytest, pip)
- **Go Tooling**: 2 modules (go test/build/vet, golangci-lint)
- **Ruby Tooling**: 3 modules (rake/minitest, rspec, rubocop) + 1 TOML filter (bundle install)
---
@@ -423,7 +307,7 @@ Strategy Modules Technique Reduction
Used by: go test (NDJSON stream, interleaved package events)
```
### Code Filtering Levels (filter.rs)
### Code Filtering Levels (src/core/filter.rs)
```rust
// FilterLevel::None - Keep everything
@@ -483,7 +367,7 @@ Mirrors: lint, prettier Mirrors: git, cargo
```
┌────────────────────────────────────────────────────────────────────────┐
│ Python Commands (3 modules) │
│ Python Commands │
└────────────────────────────────────────────────────────────────────────┘
Module Strategy Output Format Savings
@@ -540,7 +424,7 @@ Commands respect active virtualenv via `sys.executable` paths.
```
┌────────────────────────────────────────────────────────────────────────┐
│ Go Commands (2 modules) │
│ Go Commands │
└────────────────────────────────────────────────────────────────────────┘
Module Strategy Output Format Savings
@@ -577,29 +461,7 @@ golangci_cmd.rs JSON PARSING JSON API 85%
#### Sub-Enum Pattern (go_cmd.rs)
```rust
// main.rs enum definition
Commands::Go {
#[command(subcommand)]
command: GoCommand,
}
// go_cmd.rs sub-enum
pub enum GoCommand {
Test { args: Vec<String> },
Build { args: Vec<String> },
Vet { args: Vec<String> },
}
// Router
pub fn run(command: &GoCommand, verbose: u8) -> Result<()> {
match command {
GoCommand::Test { args } => run_test(args, verbose),
GoCommand::Build { args } => run_build(args, verbose),
GoCommand::Vet { args } => run_vet(args, verbose),
}
}
```
Uses `Commands::Go { #[command(subcommand)] command: GoCommand }` in main.rs, with `GoCommand` enum routing to `run_test/run_build/run_vet`. Mirrors git/cargo patterns.
**Why Sub-Enum?**
- `go test/build/vet` are semantically related (core Go toolchain)
@@ -665,38 +527,6 @@ Output format known?
Examples: go vet, go build
```
### Testing Patterns
#### Python Module Tests
```rust
// pytest_cmd.rs tests
#[test]
fn test_pytest_state_machine() {
let output = "test_auth.py::test_login PASSED\ntest_db.py::test_query FAILED";
let result = parse_pytest_output(output);
assert!(result.contains("1 failed"));
assert!(result.contains("test_db.py::test_query"));
}
```
#### Go Module Tests
```rust
// go_cmd.rs tests
#[test]
fn test_go_test_ndjson_interleaved() {
let output = r#"{"Action":"run","Package":"pkg1"}
{"Action":"fail","Package":"pkg1","Test":"TestA"}
{"Action":"run","Package":"pkg2"}
{"Action":"pass","Package":"pkg2","Test":"TestB"}"#;
let result = parse_go_test_ndjson(output);
assert!(result.contains("pkg1: 1 failed"));
assert!(!result.contains("pkg2")); // pkg2 passed, hidden
}
```
### Performance Characteristics
```
@@ -739,30 +569,13 @@ When adding Python/Go module support:
## Shared Infrastructure
### Utilities Layer (utils.rs)
### Utilities Layer
```
┌────────────────────────────────────────────────────────────────────────┐
│ Shared Utilities Layer │
└────────────────────────────────────────────────────────────────────────┘
utils.rs provides common functionality:
┌─────────────────────────────────────────┐
│ truncate(s: &str, max: usize) → String │ Text truncation with "..."
├─────────────────────────────────────────┤
│ strip_ansi(text: &str) → String │ Remove ANSI color codes
├─────────────────────────────────────────┤
│ execute_command(cmd, args) │ Shell execution helper
│ → (stdout, stderr, exit_code) │ with error context
└─────────────────────────────────────────┘
Used by: All command modules (24 modules depend on utils.rs)
```
> For the full utilities API (`truncate`, `strip_ansi`, `execute_command`, `ruby_exec`, etc.), see [src/core/README.md](src/core/README.md). Used by most command modules.
### Package Manager Detection Pattern
**Critical Infrastructure for JS/TS Stack (8 modules)**
**Critical Infrastructure for JS/TS Stack**
```
┌────────────────────────────────────────────────────────────────────────┐
@@ -919,15 +732,7 @@ Flow:
### Thread Safety
```rust
// tracking.rs:9-11
lazy_static::lazy_static! {
static ref TRACKER: Mutex<Option<Tracker>> = Mutex::new(None);
}
```
**Design**: Single-threaded execution with Mutex for future-proofing.
**Current State**: No multi-threading, but Mutex enables safe concurrent access if needed.
Single-threaded execution with `Mutex<Option<Tracker>>` for future-proofing. No multi-threading currently, but safe concurrent access is possible if needed.
---
@@ -1065,43 +870,11 @@ Modules with Exit Code Preservation:
## Configuration System
### Two-Tier Configuration
### Configuration
```
┌────────────────────────────────────────────────────────────────────────┐
│ Configuration Architecture │
└────────────────────────────────────────────────────────────────────────┘
> For config file format, tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
1. User Settings (config.toml)
───────────────────────────
Location: ~/.config/rtk/config.toml
Format:
[general]
default_filter_level = "minimal"
enable_tracking = true
retention_days = 90
Loaded by: config.rs (main.rs:650-656)
2. LLM Integration (CLAUDE.md)
────────────────────────────
Locations:
• Global: ~/.config/rtk/CLAUDE.md
• Local: ./CLAUDE.md (project-specific)
Purpose: Instruct LLM (Claude Code) to use rtk prefix
Created by: rtk init [--global]
Template (init.rs:40-60):
# CLAUDE.md
Use `rtk` prefix for all commands:
- rtk git status
- rtk grep "pattern"
- rtk read file.rs
Benefits: 60-90% token reduction
```
Two tiers: **User settings** (`~/.config/rtk/config.toml`) and **LLM integration** (CLAUDE.md via `rtk init`).
### Initialization Flow
@@ -1138,85 +911,7 @@ Success: "✓ Initialized rtk for LLM integration"
---
## Module Development Pattern
### Standard Module Template
```rust
// src/example_cmd.rs
use anyhow::{Context, Result};
use std::process::Command;
use crate::{tracking, utils};
/// Public entry point called by main.rs router
pub fn run(args: &[String], verbose: u8) -> Result<()> {
// 1. Execute underlying command
let raw_output = execute_command(args)?;
// 2. Apply filtering strategy
let filtered = filter_output(&raw_output, verbose);
// 3. Print result
println!("{}", filtered);
// 4. Track token savings
tracking::track(
"original_command",
"rtk command",
&raw_output,
&filtered
);
Ok(())
}
/// Execute the underlying tool
fn execute_command(args: &[String]) -> Result<String> {
let output = Command::new("tool")
.args(args)
.output()
.context("Failed to execute tool")?;
// Preserve exit codes (critical for CI/CD)
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
/// Apply filtering strategy
fn filter_output(raw: &str, verbose: u8) -> String {
// Choose strategy: stats, grouping, deduplication, etc.
// See "Filtering Strategies" section for options
if verbose >= 3 {
eprintln!("Raw output:\n{}", raw);
}
// Apply compression logic
let compressed = compress(raw);
compressed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_output() {
let raw = "verbose output here";
let filtered = filter_output(raw, 0);
assert!(filtered.len() < raw.len());
}
}
```
### Common Patterns
## Common Patterns
#### 1. Package Manager Detection (JS/TS modules)
@@ -1235,18 +930,7 @@ let mut cmd = if is_pnpm {
};
```
#### 2. Lazy Static Regex (filter.rs, runner.rs)
```rust
lazy_static::lazy_static! {
static ref PATTERN: Regex = Regex::new(r"ERROR:.*").unwrap();
}
// Usage: compiled once, reused across invocations
let matches: Vec<_> = PATTERN.find_iter(text).collect();
```
#### 3. Verbosity Guards
#### 2. Verbosity Guards
```rust
if verbose > 0 {
@@ -1309,162 +993,11 @@ Overhead Sources:
• SQLite tracking: ~1-3ms
```
### Compilation
```bash
# Development build (fast compilation, debug symbols)
cargo build
# Release build (optimized, stripped)
cargo build --release
# Check without building (fast feedback)
cargo check
# Run tests
cargo test
# Lint with clippy
cargo clippy --all-targets
# Format code
cargo fmt
```
---
## Extensibility Guide
### Adding a New Command
**Step-by-step process to add a new rtk command:**
#### 1. Create Module File
```bash
touch src/mycmd.rs
```
#### 2. Implement Module (src/mycmd.rs)
```rust
use anyhow::{Context, Result};
use std::process::Command;
use crate::tracking;
pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Execute underlying command
let output = Command::new("mycmd")
.args(args)
.output()
.context("Failed to execute mycmd")?;
let raw = String::from_utf8_lossy(&output.stdout);
// Apply filtering strategy
let filtered = filter(&raw, verbose);
// Print result
println!("{}", filtered);
// Track savings
tracking::track("mycmd", "rtk mycmd", &raw, &filtered);
Ok(())
}
fn filter(raw: &str, verbose: u8) -> String {
// Implement your filtering logic
raw.lines().take(10).collect::<Vec<_>>().join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter() {
let raw = "line1\nline2\n";
let result = filter(raw, 0);
assert!(result.contains("line1"));
}
}
```
#### 3. Declare Module (main.rs)
```rust
// Add to module declarations (alphabetically)
mod mycmd;
```
#### 4. Add Command Enum Variant (main.rs)
```rust
#[derive(Subcommand)]
enum Commands {
// ... existing commands ...
/// Description of your command
Mycmd {
/// Arguments your command accepts
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
}
```
#### 5. Add Router Match Arm (main.rs)
```rust
match cli.command {
// ... existing matches ...
Commands::Mycmd { args } => {
mycmd::run(&args, verbose)?;
}
}
```
#### 6. Test Your Command
```bash
# Build and test
cargo build
./target/debug/rtk mycmd arg1 arg2
# Run tests
cargo test mycmd::tests
# Check with clippy
cargo clippy --all-targets
```
#### 7. Document Your Command
Update CLAUDE.md:
```markdown
### New Commands
**rtk mycmd** - Description of what it does
- Strategy: [stats/grouping/filtering/etc.]
- Savings: X-Y%
- Used by: [workflow description]
```
### Design Checklist
When implementing a new command, consider:
- [ ] **Filtering Strategy**: Which of the 9 strategies fits best?
- [ ] **Exit Code Preservation**: Does your command need to preserve exit codes for CI/CD?
- [ ] **Verbosity Support**: Add debug output for `-v`, `-vv`, `-vvv`
- [ ] **Error Handling**: Use `.context()` for meaningful error messages
- [ ] **Package Manager Detection**: For JS/TS tools, use the standard detection pattern
- [ ] **Tests**: Add unit tests for filtering logic
- [ ] **Token Tracking**: Integrate with `tracking::track()`
- [ ] **Documentation**: Update CLAUDE.md with token savings and use cases
> For the complete step-by-step process to add a new command (module file, enum variant, routing, tests, documentation), see [src/cmds/README.md — Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter).
---
@@ -1501,11 +1034,11 @@ When implementing a new command, consider:
## Resources
- **[docs/TECHNICAL.md](docs/TECHNICAL.md)**: Guided tour of end-to-end flow
- **[CONTRIBUTING.md](CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
- **CLAUDE.md**: Quick reference for AI agents (dev commands, build verification)
- **README.md**: User guide, installation, examples
- **CLAUDE.md**: Developer documentation, module details, PR history
- **Cargo.toml**: Dependencies, build profiles, package metadata
- **src/**: Source code organized by module
- **.github/workflows/**: CI/CD automation (multi-platform builds, releases)
---
@@ -1523,6 +1056,5 @@ When implementing a new command, consider:
---
**Last Updated**: 2026-02-22
**Architecture Version**: 2.2
**rtk Version**: 0.28.2
**Last Updated**: 2026-03-24
**Architecture Version**: 3.1
+14
View File
@@ -5,6 +5,18 @@ 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.34.1](https://github.com/rtk-ai/rtk/compare/v0.34.0...v0.34.1) (2026-03-28)
### Bug Fixes
* **security:** missing toml pkg ([51f9c88](https://github.com/rtk-ai/rtk/commit/51f9c888b81169309df92f7fa3a6f705d44adcab))
* **security:** salt device hash for telemetry ([32fdbbb](https://github.com/rtk-ai/rtk/commit/32fdbbbb6923c70d343fab14b4b0ce70424e610f))
* **security:** set 0600 permissions on salt file ([5eae11d](https://github.com/rtk-ai/rtk/commit/5eae11d16410dc4ff26e97672e5367b14efaab76))
* **telemetry:** cache salt in-process ([22dc059](https://github.com/rtk-ai/rtk/commit/22dc059310b0408adedc2d1228de339e16ea6c0a))
* **telemetry:** docs + real info from "rtk init -g" ([33195cc](https://github.com/rtk-ai/rtk/commit/33195cc686318ddcca54edfdd1215bd9fd28f891))
* **telemetry:** hash + salt ([92996b1](https://github.com/rtk-ai/rtk/commit/92996b127257eae16d3e17179592b2899f19254f))
## [0.34.0](https://github.com/rtk-ai/rtk/compare/v0.33.1...v0.34.0) (2026-03-26)
@@ -29,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug Fixes
* **wc:** `wc` filter was never invoked by the hook — removed `"wc "` from `IGNORED_PREFIXES` and added registry entry so `wc` commands are rewritten to `rtk wc`
* **diff:** correct truncation overflow count in condense_unified_diff ([#833](https://github.com/rtk-ai/rtk/pull/833)) ([5399f83](https://github.com/rtk-ai/rtk/commit/5399f83))
* **git:** replace vague truncation markers with exact counts in log and grep output ([#833](https://github.com/rtk-ai/rtk/pull/833)) ([185fb97](https://github.com/rtk-ai/rtk/commit/185fb97))
@@ -241,6 +254,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug Fixes
* **cargo clippy:** include actionable error details in compact output instead of summary-only counts ([#602](https://github.com/rtk-ai/rtk/issues/602))
* **curl:** skip JSON schema replacement when schema is larger than original payload ([#297](https://github.com/rtk-ai/rtk/issues/297))
* **toml-dsl:** fix regex overmatch on `tofu-plan/init/validate/fmt` and `mix-format/compile` — add `(\s|$)` word boundary to prevent matching subcommands (e.g. `tofu planet`, `mix formats`) ([#349](https://github.com/rtk-ai/rtk/issues/349))
* **toml-dsl:** remove 3 dead built-in filters (`docker-inspect`, `docker-compose-ps`, `pnpm-build`) — Clap routes these commands before `run_fallback`, so the TOML filters never fire ([#351](https://github.com/rtk-ai/rtk/issues/351))
+42 -490
View File
@@ -8,11 +8,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
This is a fork with critical fixes for git argument parsing and modern JavaScript stack support (pnpm, vitest, Next.js, TypeScript, Playwright, Prisma).
### ⚠️ Name Collision Warning
### Name Collision Warning
**Two different "rtk" projects exist:**
- ✅ **This project**: Rust Token Killer (rtk-ai/rtk)
- ❌ **reachingforthejack/rtk**: Rust Type Kit (DIFFERENT - generates Rust types)
- This project: Rust Token Killer (rtk-ai/rtk)
- reachingforthejack/rtk: Rust Type Kit (DIFFERENT - generates Rust types)
**Verify correct installation:**
```bash
@@ -29,133 +29,51 @@ If `rtk gain` fails, you have the wrong package installed.
### Build & Run
```bash
# Development build
cargo build # raw
rtk cargo build # preferred (token-optimized)
# Release build (optimized)
cargo build --release
rtk cargo build --release
# Run directly
cargo run -- <command>
# Install locally
cargo install --path .
cargo build --release # release build (optimized)
cargo run -- <command> # run directly
cargo install --path . # install locally
```
### Testing
```bash
# Run all tests
cargo test # raw
cargo test # all tests
rtk cargo test # preferred (token-optimized)
# Run specific test
cargo test <test_name>
rtk cargo test <test_name>
# Run tests with output
cargo test -- --nocapture
rtk cargo test -- --nocapture
# Run tests in specific module
cargo test <module_name>::
rtk cargo test <module_name>::
cargo test <test_name> # specific test
cargo test <module_name>:: # module tests
cargo test -- --nocapture # with stdout
bash scripts/test-all.sh # smoke tests (installed binary required)
```
### Linting & Quality
```bash
# Check without building
cargo check # raw
rtk cargo check # preferred (token-optimized)
cargo check # check without building
cargo fmt # format code
cargo clippy --all-targets # all clippy lints
rtk cargo clippy --all-targets # preferred
```
# Format code
cargo fmt # passthrough (0% savings, but works)
# Run clippy lints
cargo clippy # raw
rtk cargo clippy # preferred (token-optimized)
# Check all targets
cargo clippy --all-targets
rtk cargo clippy --all-targets
### Pre-commit Gate
```bash
cargo fmt --all && cargo clippy --all-targets && cargo test --all
```
### Package Building
```bash
# Build DEB package (Linux)
cargo install cargo-deb
cargo deb
# Build RPM package (Fedora/RHEL)
cargo install cargo-generate-rpm
cargo build --release
cargo generate-rpm
cargo deb # DEB package (needs cargo-deb)
cargo generate-rpm # RPM package (needs cargo-generate-rpm, after release build)
```
## Architecture
### Core Design Pattern
rtk uses a **command proxy architecture**: `main.rs` routes CLI commands via a Clap `Commands` enum to specialized filter modules in `src/cmds/*/`, each of which executes the underlying command and compresses its output. Token savings are tracked in SQLite via `src/core/tracking.rs`.
rtk uses a **command proxy architecture** with specialized modules for each output type:
For the full architecture, component details, and module development patterns, see:
- [ARCHITECTURE.md](ARCHITECTURE.md) — System design, module organization, filtering strategies, error handling
- [docs/TECHNICAL.md](docs/TECHNICAL.md) — End-to-end flow, folder map, hook system, filter pipeline
```
main.rs (CLI entry)
→ Clap command parsing
→ Route to specialized modules
→ tracking.rs (SQLite) records token savings
```
### Key Architectural Components
**1. Command Modules** (src/*_cmd.rs, src/git.rs, src/container.rs)
- Each module handles a specific command type (git, grep, etc.)
- Responsible for executing underlying commands and transforming output
- Implement token-optimized formatting strategies
**2. Core Filtering** (src/filter.rs)
- Language-aware code filtering (Rust, Python, JavaScript, etc.)
- Filter levels: `none`, `minimal`, `aggressive`
- Strips comments, whitespace, and function bodies (aggressive mode)
- Used by `read` and `smart` commands
**3. Token Tracking** (src/tracking.rs)
- SQLite-based persistent storage (~/.local/share/rtk/tracking.db)
- Records: original_cmd, rtk_cmd, input_tokens, output_tokens, savings_pct
- 90-day retention policy with automatic cleanup
- Powers the `rtk gain` analytics command
- **Configurable database path**: Via `RTK_DB_PATH` env var or `config.toml`
- Priority: env var > config file > default location
**4. Configuration System** (src/config.rs, src/init.rs)
- Manages CLAUDE.md initialization (global vs local)
- Reads ~/.config/rtk/config.toml for user preferences
- `rtk init` command bootstraps LLM integration
- **New**: `tracking.database_path` field for custom DB location
**5. Tee Output Recovery** (src/tee.rs)
- Saves raw unfiltered output to `~/.local/share/rtk/tee/` on command failure
- Prints one-line hint `[full output: ~/.local/share/rtk/tee/...]` so LLMs can read instead of re-run
- Configurable via `[tee]` section in config.toml or env vars (`RTK_TEE`, `RTK_TEE_DIR`)
- Default mode: failures only, skip outputs < 500 chars, 20 file rotation, 1MB cap
- Silent error handling: tee failure never affects command output or exit code
**6. Shared Utilities** (src/utils.rs)
- Common functions for command modules: truncate, strip_ansi, execute_command
- Package manager auto-detection (pnpm/yarn/npm/npx)
- Consistent error handling and output formatting
- Used by all modern JavaScript/TypeScript tooling commands
### Command Routing Flow
All commands follow this pattern:
```rust
main.rs:Commands enum
→ match statement routes to module
→ module::run() executes logic
→ tracking::track_command() records metrics
→ Result<()> propagates errors
```
Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header. Browse `src/cmds/*/` to discover available filters.
### Proxy Mode
@@ -167,293 +85,30 @@ main.rs:Commands enum
- **Bypass RTK filtering**: Workaround bugs or get full unfiltered output
- **Track usage metrics**: Measure which commands Claude uses most (visible in `rtk gain --history`)
- **Guaranteed compatibility**: Always works even if RTK doesn't implement the command
- **Prototyping**: Test new commands before implementing optimized filtering
**Examples**:
```bash
# Full git log output (no truncation)
rtk proxy git log --oneline -20
# Raw npm output (no filtering)
rtk proxy npm install express
# Any command works
rtk proxy curl https://api.example.com/data
# Tracking shows 0% savings (expected)
rtk gain --history | grep proxy
rtk proxy git log --oneline -20 # Full git log output (no truncation)
rtk proxy npm install express # Raw npm output (no filtering)
rtk proxy curl https://api.example.com/data # Any command works
```
**Tracking**: All proxy commands appear in `rtk gain --history` with 0% savings (input = output) but preserve usage statistics.
All proxy commands appear in `rtk gain --history` with 0% savings (input = output).
### Critical Implementation Details
## Coding Rules
**Git Argument Handling** (src/git.rs)
- Uses `trailing_var_arg = true` + `allow_hyphen_values = true` to properly handle git flags
- Auto-detects `--merges` flag to avoid conflicting with `--no-merges` injection
- Propagates git exit codes for CI/CD reliability (PR #5 fix)
Rust patterns, error handling, and anti-patterns are defined in `.claude/rules/rust-patterns.md` (auto-loaded into context). Key points:
**Output Filtering Strategy**
- Compact mode: Show only summary/failures
- Full mode: Available with `-v` verbosity flags
- Test output: Show only failures (90% token reduction)
- Git operations: Ultra-compressed confirmations ("ok ✓")
- **anyhow::Result** everywhere, always `.context("description")?`
- **No unwrap()** in production code
- **lazy_static!** for all regex (never compile inside a function)
- **Fallback pattern**: if filter fails, execute raw command unchanged
- **No async**: single-threaded by design (startup <10ms)
- **Exit code propagation**: `std::process::exit(code)` on child failure
**Language Detection** (src/filter.rs)
- File extension-based with fallback heuristics
- Supports Rust, Python, JS/TS, Java, Go, C/C++, etc.
- Tokenization rules vary by language (comments, strings, blocks)
Testing strategy and performance targets are defined in `.claude/rules/cli-testing.md` (auto-loaded). Key targets: <10ms startup, <5MB memory, 60-90% token savings.
### Module Responsibilities
| Module | Purpose | Token Strategy |
|--------|---------|----------------|
| git.rs | Git operations | Stat summaries + compact diffs |
| grep_cmd.rs | Code search | Group by file, truncate lines |
| ls.rs | Directory listing | Tree format, aggregate counts |
| read.rs | File reading | Filter-level based stripping |
| runner.rs | Command execution | Stderr only (err), failures only (test) |
| log_cmd.rs | Log parsing | Deduplication with counts |
| json_cmd.rs | JSON inspection | Structure without values |
| lint_cmd.rs | ESLint/Biome linting | Group by rule, file summary (84% reduction) |
| tsc_cmd.rs | TypeScript compiler | Group by file/error code (83% reduction) |
| next_cmd.rs | Next.js build/dev | Route metrics, bundle stats only (87% reduction) |
| prettier_cmd.rs | Format checking | Files needing changes only (70% reduction) |
| playwright_cmd.rs | E2E test results | Failures only, grouped by suite (94% reduction) |
| prisma_cmd.rs | Prisma CLI | Strip ASCII art and verbose output (88% reduction) |
| gh_cmd.rs | GitHub CLI | Compact PR/issue/run views (26-87% reduction) |
| vitest_cmd.rs | Vitest test runner | Failures only with ANSI stripping (99.5% reduction) |
| pnpm_cmd.rs | pnpm package manager | Compact dependency trees (70-90% reduction) |
| ruff_cmd.rs | Ruff linter/formatter | JSON for check, text for format (80%+ reduction) |
| pytest_cmd.rs | Pytest test runner | State machine text parser (90%+ reduction) |
| mypy_cmd.rs | Mypy type checker | Group by file/error code (80% reduction) |
| pip_cmd.rs | pip/uv package manager | JSON parsing, auto-detect uv (70-85% reduction) |
| go_cmd.rs | Go commands | NDJSON for test, text for build/vet (80-90% reduction) |
| golangci_cmd.rs | golangci-lint | JSON parsing, group by rule (85% reduction) |
| rake_cmd.rs | Minitest via rake/rails test | State machine text parser, failures only (85-90% reduction) |
| rspec_cmd.rs | RSpec test runner | JSON injection + text fallback, failures only (60%+ reduction) |
| rubocop_cmd.rs | RuboCop linter | JSON injection, group by cop/severity (60%+ reduction) |
| tee.rs | Full output recovery | Save raw output to file on failure, print hint for LLM re-read |
| utils.rs | Shared utilities | Package manager detection, ruby_exec, common formatting |
| discover/ | Claude Code history analysis | Scan JSONL sessions, classify commands, report missed savings |
## Performance Constraints
RTK has **strict performance targets** to maintain zero-overhead CLI experience:
| Metric | Target | Verification Method |
|--------|--------|---------------------|
| **Startup time** | <10ms | `hyperfine 'rtk git status' 'git status'` |
| **Memory overhead** | <5MB resident | `/usr/bin/time -l rtk git status` (macOS) |
| **Token savings** | 60-90% | Verify in tests with `count_tokens()` assertions |
| **Binary size** | <5MB stripped | `ls -lh target/release/rtk` |
**Performance regressions are release blockers** - always benchmark before/after changes:
```bash
# Before changes
hyperfine 'rtk git log -10' --warmup 3 > /tmp/before.txt
# After changes
cargo build --release
hyperfine 'target/release/rtk git log -10' --warmup 3 > /tmp/after.txt
# Compare (should be <10ms)
diff /tmp/before.txt /tmp/after.txt
```
**Why <10ms matters**: Claude Code users expect CLI tools to be instant. Any perceptible delay (>10ms) breaks the developer flow. RTK achieves this through:
- **Zero async overhead**: Single-threaded, no tokio runtime
- **Lazy regex compilation**: Compile once with `lazy_static!`, reuse forever
- **Minimal allocations**: Borrow over clone, in-place filtering
- **No user config**: Zero file I/O on startup (config loaded on-demand)
## Error Handling
RTK follows Rust best practices for error handling:
**Rules**:
- **anyhow::Result** for CLI binary (RTK is an application, not a library)
- **ALWAYS** use `.context("description")` with `?` operator
- **NO unwrap()** in production code (tests only - use `expect("explanation")` if needed)
- **Graceful degradation**: If filter fails, fallback to raw command execution
**Example**:
```rust
use anyhow::{Context, Result};
pub fn filter_git_log(input: &str) -> Result<String> {
let lines: Vec<_> = input
.lines()
.filter(|line| !line.is_empty())
.collect();
// ✅ RIGHT: Context on error
let hash = extract_hash(lines[0])
.context("Failed to extract commit hash from git log")?;
// ❌ WRONG: No context
let hash = extract_hash(lines[0])?;
// ❌ WRONG: Panic in production
let hash = extract_hash(lines[0]).unwrap();
Ok(format!("Commit: {}", hash))
}
```
**Fallback pattern** (critical for all filters):
```rust
// ✅ RIGHT: Fallback to raw command if filter fails
pub fn execute_with_filter(cmd: &str, args: &[&str]) -> Result<()> {
match get_filter(cmd) {
Some(filter) => match filter.apply(cmd, args) {
Ok(output) => println!("{}", output),
Err(e) => {
eprintln!("Filter failed: {}, falling back to raw", e);
execute_raw(cmd, args)?;
}
},
None => execute_raw(cmd, args)?,
}
Ok(())
}
// ❌ WRONG: Panic if no filter
pub fn execute_with_filter(cmd: &str, args: &[&str]) -> Result<()> {
let filter = get_filter(cmd).expect("Filter must exist");
filter.apply(cmd, args)?;
Ok(())
}
```
## Common Pitfalls
**Don't add async dependencies** (kills startup time)
- RTK is single-threaded by design
- Adding tokio/async-std adds ~5-10ms startup overhead
- Use blocking I/O with fallback to raw command
**Don't recompile regex at runtime** (kills performance)
- ❌ WRONG: `let re = Regex::new(r"pattern").unwrap();` inside function
- ✅ RIGHT: `lazy_static! { static ref RE: Regex = Regex::new(r"pattern").unwrap(); }`
**Don't panic on filter failure** (breaks user workflow)
- Always fallback to raw command execution
- Log error to stderr, execute original command unchanged
**Don't assume command output format** (breaks across versions)
- Test with real fixtures from multiple versions
- Use flexible regex patterns that tolerate format changes
**Don't skip cross-platform testing** (macOS ≠ Linux ≠ Windows)
- Shell escaping differs: bash/zsh vs PowerShell
- Path separators differ: `/` vs `\`
- Line endings differ: LF vs CRLF
**Don't break pipe compatibility** (users expect Unix behavior)
- `rtk git status | grep modified` must work
- Preserve stdout/stderr separation
- Respect exit codes (0 = success, non-zero = failure)
## Fork-Specific Features
### PR #5: Git Argument Parsing Fix (CRITICAL)
- **Problem**: Git flags like `--oneline`, `--cached` were rejected
- **Solution**: Fixed Clap parsing with proper trailing_var_arg configuration
- **Impact**: All git commands now accept native git flags
### PR #6: pnpm Support
- **New Commands**: `rtk pnpm list`, `rtk pnpm outdated`, `rtk pnpm install`
- **Token Savings**: 70-90% reduction on package manager operations
- **Security**: Package name validation prevents command injection
### PR #9: Modern JavaScript/TypeScript Tooling (2026-01-29)
- **New Commands**: 6 commands for T3 Stack workflows
- `rtk lint`: ESLint/Biome with grouped rule violations (84% reduction)
- `rtk tsc`: TypeScript compiler errors grouped by file/code (83% reduction)
- `rtk next`: Next.js build with route/bundle metrics (87% reduction)
- `rtk prettier`: Format checker showing files needing changes (70% reduction)
- `rtk playwright`: E2E test results showing failures only (94% reduction)
- `rtk prisma`: Prisma CLI without ASCII art (88% reduction)
- **Shared Infrastructure**: utils.rs module for package manager auto-detection
- **Features**: Exit code preservation, error grouping, consistent formatting
- **Testing**: Validated on a production T3 Stack project
### Python & Go Support (2026-02-12)
- **Python Commands**: 3 commands for Python development workflows
- `rtk ruff check/format`: Ruff linter/formatter with JSON (check) and text (format) parsing (80%+ reduction)
- `rtk pytest`: Pytest test runner with state machine text parser (90%+ reduction)
- `rtk pip list/outdated/install`: pip package manager with auto-detect uv (70-85% reduction)
- **Go Commands**: 4 commands via sub-enum for Go ecosystem
- `rtk go test`: NDJSON line-by-line parser for interleaved events (90%+ reduction)
- `rtk go build`: Text filter showing errors only (80% reduction)
- `rtk go vet`: Text filter for issues (75% reduction)
- `rtk golangci-lint`: JSON parsing grouped by rule (85% reduction)
- **Architecture**: Standalone Python commands (mirror lint/prettier), Go sub-enum (mirror git/cargo)
- **Patterns**: JSON for structured output (ruff check, golangci-lint, pip), NDJSON streaming (go test), text state machine (pytest), text filters (go build/vet, ruff format)
### Ruby on Rails Support (2026-03-15)
- **Ruby Commands**: 3 modules for Ruby/Rails development
- `rtk rspec`: RSpec test runner with JSON injection (`--format json`), text fallback (60%+ reduction)
- `rtk rubocop`: RuboCop linter with JSON injection, group by cop/severity (60%+ reduction)
- `rtk rake test`: Minitest filter via rake/rails test, state machine parser (85-90% reduction)
- **TOML Filter**: `bundle-install.toml` for bundle install/update — strips `Using` lines (90%+ reduction)
- **Shared Infrastructure**: `ruby_exec()` in utils.rs auto-detects `bundle exec` when Gemfile exists
- **Hook Integration**: Rewrites `rspec`, `rubocop`, `rake test`, `rails test`, `bundle exec` variants
## Testing Strategy
### TDD Workflow (mandatory)
All code follows Red-Green-Refactor. See `.claude/skills/rtk-tdd/` for the full workflow and Rust-idiomatic patterns. See `.claude/skills/rtk-tdd/references/testing-patterns.md` for RTK-specific patterns and untested module backlog.
### Test Architecture
- **Unit tests**: Embedded `#[cfg(test)] mod tests` in each module (105+ tests, 25+ files)
- **Smoke tests**: `scripts/test-all.sh` (69 assertions on all commands)
- **Dominant pattern**: raw string input -> filter function -> assert output contains/excludes
### Pre-commit gate
```bash
cargo fmt --all --check && rtk cargo clippy --all-targets && rtk cargo test
```
### Test commands
```bash
cargo test # All tests
cargo test filter::tests:: # Module-specific
cargo test -- --nocapture # With stdout
bash scripts/test-all.sh # Smoke tests (installed binary required)
```
## Dependencies
Core dependencies (see Cargo.toml):
- **clap**: CLI parsing with derive macros
- **anyhow**: Error handling
- **rusqlite**: SQLite for tracking database
- **regex**: Pattern matching for filtering
- **ignore**: gitignore-aware file traversal
- **colored**: Terminal output formatting
- **serde/serde_json**: Configuration and JSON parsing
## Build Optimizations
Release profile (Cargo.toml:31-36):
- `opt-level = 3`: Maximum optimization
- `lto = true`: Link-time optimization
- `codegen-units = 1`: Single codegen for better optimization
- `strip = true`: Remove debug symbols
- `panic = "abort"`: Smaller binary size
## CI/CD
GitHub Actions workflow (.github/workflows/release.yml):
- Multi-platform builds (macOS, Linux x86_64/ARM64, Windows)
- DEB/RPM package generation
- Automated releases on version tags (v*)
- Checksums for binary verification
For contribution workflow and design philosophy, see [CONTRIBUTING.md](CONTRIBUTING.md). For the step-by-step filter implementation checklist, see [src/cmds/README.md](src/cmds/README.md#adding-a-new-command-filter).
## Build Verification (Mandatory)
@@ -467,55 +122,14 @@ cargo fmt --all && cargo clippy --all-targets && cargo test --all
- Never commit code that hasn't passed all 3 checks
- Fix ALL clippy warnings before moving on (zero tolerance)
- If build fails, fix it immediately before continuing to next task
- Pre-commit hook will auto-enforce this (see `.claude/hooks/bash/pre-commit-format.sh`)
**Why**: RTK is a production CLI tool used by developers in their workflows. Bugs break developer productivity. Quality gates prevent regressions and maintain user trust.
**Performance verification** (for filter changes):
```bash
# Benchmark before/after
hyperfine 'rtk git log -10' --warmup 3
hyperfine 'rtk git log -10' --warmup 3 # before
cargo build --release
hyperfine 'target/release/rtk git log -10' --warmup 3
# Memory profiling
/usr/bin/time -l target/release/rtk git status # macOS
/usr/bin/time -v target/release/rtk git status # Linux
hyperfine 'target/release/rtk git log -10' --warmup 3 # after (should be <10ms)
```
## Testing Policy
**Manual testing is REQUIRED** for filter changes and new commands:
- **For new filters**: Test with real command (`rtk <cmd>`), verify output matches expectations
- Example: `rtk git log -10` → inspect output, verify condensed correctly
- Example: `rtk cargo test` → verify only failures shown, not full output
- **For hook changes**: Test in real Claude Code session, verify command rewriting works
- Create test Claude Code session
- Type raw command (e.g., `git status`)
- Verify hook rewrites to `rtk git status`
- **For performance**: Run `hyperfine` comparison (before/after), verify <10ms startup
- Benchmark baseline: `hyperfine 'rtk git status' --warmup 3`
- Make changes, rebuild
- Benchmark again: `hyperfine 'target/release/rtk git status' --warmup 3`
- Compare results: startup time should be <10ms
- **For cross-platform**: Test on macOS + Linux (Docker) + Windows (CI), verify shell escaping
- macOS (zsh): Test locally
- Linux (bash): Use Docker `docker run --rm -v $(pwd):/rtk -w /rtk rust:latest cargo test`
- Windows (PowerShell): Trust CI/CD pipeline or test manually if available
**Anti-pattern**: Running only automated tests (`cargo test`, `cargo clippy`) without actually executing `rtk <cmd>` and inspecting output.
**Example**: If fixing the `git log` filter, run `rtk git log -10` and verify:
1. Output is condensed (shorter than raw `git log -10`)
2. Critical info preserved (commit hashes, messages)
3. Format is readable and consistent
4. Exit code matches git's exit code (0 for success)
## Working Directory Confirmation
**ALWAYS confirm working directory before starting any work**:
@@ -553,65 +167,3 @@ When user provides a numbered plan (QW1-QW4, Phase 1-5, sprint tasks, etc.):
3. **Never skip or reorder**: If a step is blocked, report it and ask before proceeding
4. **Track progress**: Use task list (TaskCreate/TaskUpdate) for plans with 3+ steps
5. **Validate assumptions**: Before starting, verify all referenced file paths exist and working directory is correct
**Why**: Plan-driven execution produces better outcomes than ad-hoc implementation. Structured plans help maintain focus and prevent scope creep.
## Filter Development Checklist
When adding a new filter (e.g., `rtk newcmd`):
### Implementation
- [ ] Create filter module in `src/<cmd>_cmd.rs` (or extend existing)
- [ ] Add `lazy_static!` regex patterns for parsing (compile once, reuse)
- [ ] Implement fallback to raw command on error (graceful degradation)
- [ ] Preserve exit codes (`std::process::exit(code)` if non-zero)
### Testing
- [ ] Write snapshot test with real command output fixture (`tests/fixtures/<cmd>_raw.txt`)
- [ ] Verify token savings ≥60% with `count_tokens()` assertion
- [ ] Test cross-platform shell escaping (macOS, Linux, Windows)
- [ ] Write unit tests for edge cases (empty output, errors, unicode, ANSI codes)
### Integration
- [ ] Register filter in main.rs Commands enum
- [ ] Update README.md with new command support and token savings %
- [ ] Update CHANGELOG.md with feature description
### Quality Gates
- [ ] Run `cargo fmt --all && cargo clippy --all-targets && cargo test`
- [ ] Benchmark startup time with `hyperfine` (verify <10ms)
- [ ] Test manually: `rtk <cmd>` and inspect output for correctness
- [ ] Verify fallback: Break filter intentionally, confirm raw command executes
### Documentation
- [ ] Add command to this CLAUDE.md Module Responsibilities table
- [ ] Document token savings % (from tests)
- [ ] Add usage examples to README.md
**Example workflow** (adding `rtk newcmd`):
```bash
# 1. Create module
touch src/newcmd_cmd.rs
# 2. Write test first (TDD)
echo 'raw command output fixture' > tests/fixtures/newcmd_raw.txt
# Add test in src/newcmd_cmd.rs
# 3. Implement filter
# Add lazy_static regex, implement logic, add fallback
# 4. Quality checks
cargo fmt --all && cargo clippy --all-targets && cargo test
# 5. Benchmark
hyperfine 'rtk newcmd args'
# 6. Manual test
rtk newcmd args
# Inspect output, verify condensed
# 7. Document
# Update README.md, CHANGELOG.md, this file
```
+109 -54
View File
@@ -7,6 +7,7 @@
- [Report an Issue](../../issues/new)
- [Open Pull Requests](../../pulls)
- [Start a Discussion](../../discussions)
- [Technical Documentation](docs/TECHNICAL.md) — Architecture, end-to-end flow, folder map, how to write tests
---
@@ -22,30 +23,107 @@
|------|----------|
| **Report** | File a clear issue with steps to reproduce, expected vs actual behavior |
| **Fix** | Bug fixes, broken filter repairs |
| **Build** | New filters, new command support, performance improvements |
| **Build** | New filters, new command support, new features (for core features, discuss with maintainers before) |
| **Review** | Review open PRs, test changes locally, leave constructive feedback |
| **Document** | Improve docs, add usage examples, clarify existing docs |
| **Document** | Improve docs, clarify |
---
## Design Philosophy
Four principles guide every RTK design decision. Understanding them helps you write contributions that fit naturally into the project.
### Correctness VS Token Savings
When a user or LLM explicitly requests detailed output via flags (e.g., `git log --comments`, `cargo test -- --nocapture`, `ls -la`), respect that intent. Compressing explicitly-requested detail defeats the purpose — the LLM asked for it because it needs it.
Filters should be flag-aware: default output (no flags) gets aggressively compressed, but verbose/detailed flags should pass through more content. When in doubt, preserve correctness.
> Example: `rtk cargo test` shows failures only (90% savings). But `rtk cargo test -- --nocapture` preserves all output because the user explicitly asked for it.
### Transparency
The LLM doesn't know RTK is involved for which commands, hooks rewrite commands silently. RTK's output must be a valid, useful subset of the original tool's output, not a different format the LLM wouldn't expect. If an LLM parses `git diff` output, RTK's filtered version must still look like `git diff` output.
Don't invent new output formats. Don't add RTK-specific headers or markers in the default output. The filtered output should be indistinguishable from "a shorter version of the real command."
### Never Block
If a filter fails, fall back to raw output. RTK should never prevent a command from executing or producing output. Better to pass through unfiltered than to error out. Same for hooks: exit 0 on all error paths so the agent's command runs unmodified.
Every filter needs a fallback path. Every hook must handle malformed input gracefully.
### Zero Overhead
<10ms startup. No async runtime. No config file I/O on the critical path. If developers perceive any delay, they'll disable RTK. Speed is the difference between adoption and abandonment.
`lazy_static!` for all regex. No network calls. No disk reads in the hot path. Benchmark before/after with `hyperfine`.
### Extensibility
Always use components already in place to avoid duplication, also use extensible modules when this is possible.
If you want to submit a new core feature, this is an important point to watch.
---
## What Belongs in RTK?
### In Scope
Commands that produce **text output** (typically 100+ tokens) and can be compressed **60%+** without losing essential information for the LLM.
- Test runners (vitest, pytest, cargo test, go test)
- Linters and type checkers (eslint, ruff, tsc, mypy)
- Build tools (cargo build, dotnet build, make, next build)
- VCS operations (git status/log/diff, gh pr/issue)
- Package managers (pnpm, pip, cargo install, brew)
- File operations (ls, tree, grep, find, cat/head/tail)
- Infrastructure tools with text output (docker, kubectl, terraform)
When implementing a new filter/cmds, be aware of the [Design Philosophy](#design-philosophy) above.
### Out of Scope
- Interactive TUIs (htop, vim, less): not batch-mode compatible
- Binary output (images, compiled artifacts): no text to filter
- Trivial commands: not worth the overhead and may loose important informations
- Commands with no text output: nothing to compress
- Others features not related to a LLM-proxy like RTK
### TOML vs Rust: Which One?
| Use **TOML filter** when | Use **Rust module** when |
|--------------------------|--------------------------|
| Output is plain text with predictable line structure | Output is structured (JSON, NDJSON) |
| Regex line filtering achieves 60%+ savings | Needs state machine parsing (e.g., pytest phases) |
| No need to inject CLI flags | Needs to inject flags like `--format json` |
| No cross-command routing | Routes to other commands (lint → ruff/mypy) |
| Examples: brew, df, shellcheck, rsync, ping | Examples: vitest, pytest, golangci-lint, gh |
See [`src/filters/README.md`](src/filters/README.md) for TOML filter guidance and [`src/cmds/README.md`](src/cmds/README.md) for Rust module guidance.
### Adding a Filter
For the step-by-step checklist (create filter, register rewrite pattern, register in main.rs, write tests, update docs), see [src/cmds/README.md — Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter).
---
## Branch Naming Convention
Every branch **must** follow one of these prefixes to identify the level of change:
Git branch names cannot include spaces or colons, so we use slash-prefixed names. Pick the prefix that matches your change type and follow it with an optional scope and a short, kebab-case description.
| Prefix | Semver Impact | When to Use |
|--------|---------------|-------------|
| `fix(scope): ...` | Patch | Bug fixes, corrections, minor adjustments |
| `feat(scope): ...` | Minor | New features, new filters, new command support |
| `chore(scope): ...` | Major | Breaking changes, API changes, removed functionality |
| `fix/` | Patch | Bug fixes, corrections, minor adjustments |
| `feat/` | Minor | New features, new filters, new command support |
| `chore/` | Major | Breaking changes, API changes, removed functionality |
The **scope** in parentheses indicates which part of the project is concerned (e.g. `git`, `kubectl`, `filter`, `tracking`, `config`).
**Branch title must clearly describe what is affected and the goal.**
Combine the prefix with a scope if it adds clarity (e.g. `git`, `kubectl`, `filter`, `tracking`, `config`) and finish with a descriptive slug: `fix/<scope>-<description>` or `feat/<description>`.
Examples:
```
fix(git): log-filter-drops-merge-commits
feat(kubectl): add-pod-list-filter
chore(proxy): remove-deprecated-flags
fix/git-log-filter-drops-merge-commits
feat/kubectl-add-pod-list-filter
chore/release-pipeline-cleanup
```
---
@@ -57,18 +135,19 @@ chore(proxy): remove-deprecated-flags
**Each PR must focus on a single feature, fix, or change.** The diff must stay in-scope with the description written by the author in the PR title and body. Out-of-scope changes (unrelated refactors, drive-by fixes, formatting of untouched files) must go in a separate PR.
**For large features or refactors**, prefer multi-part PRs over one enormous PR. Split the work into logical, reviewable chunks that can each be merged independently. Examples:
- Part 1: Add data model and tests
- Part 2: Add CLI command and integration
- Part 3: Update documentation and CHANGELOG
- feat(Part 1): Add data model and tests
- feat(Part 2): Add CLI command and integration
- feat(Part 3): Update documentation and CHANGELOG
**Why**: Small, focused PRs are easier to review, safer to merge, and faster to ship. Large PRs slow down review, hide bugs, and increase merge conflict risk.
### 1. Create Your Branch
```bash
git checkout develop
git pull origin develop
git checkout -b "feat(scope): your-clear-description"
git checkout -b feat/scope-your-clear-description
```
### 2. Make Your Changes
@@ -79,7 +158,7 @@ git checkout -b "feat(scope): your-clear-description"
**No obvious comments.** Don't comment what the code already says. Comments should explain *why*, never *what* to avoid noise.
**Large command files are expected.** Command modules (`*_cmd.rs`) contain the implementation, tests, and fixture in the same file. A big file is fine when it's self-contained for one command.
**Large command files are expected.** Command modules (`*_cmd.rs`) contain the implementation, tests, and fixture in the same file. A big file is fine when it's self-contained for one command. This will be moved in the future.
### 3. Add Tests
@@ -124,6 +203,8 @@ your branch --> develop (review + CI + integration testing) --> version branch -
Every change **must** include tests. We follow **TDD (Red-Green-Refactor)**: write a failing test first, implement the minimum to pass, then refactor.
For how to write tests (fixtures, snapshots, token savings verification), see [docs/TECHNICAL.md — Testing](docs/TECHNICAL.md#testing).
### Test Types
| Type | Where | Run With |
@@ -133,36 +214,6 @@ Every change **must** include tests. We follow **TDD (Red-Green-Refactor)**: wri
| **Smoke tests** | `scripts/test-all.sh` (69 assertions) | `bash scripts/test-all.sh` |
| **Integration tests** | `#[ignore]` tests requiring installed binary | `cargo test --ignored` |
### How to Write Tests
Tests for new commands live **in the module file itself** inside a `#[cfg(test)] mod tests` block (e.g. tests for `src/kubectl_cmd.rs` go at the bottom of that same file).
**1. Create a fixture from real command output** (not synthetic data):
```bash
kubectl get pods > tests/fixtures/kubectl_pods_raw.txt
```
**2. Write your test in the same module file** (`#[cfg(test)] mod tests`):
```rust
#[test]
fn test_my_filter() {
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
let output = filter_my_cmd(input);
assert_snapshot!(output);
}
```
**3. Verify token savings**:
```rust
#[test]
fn test_my_filter_savings() {
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
let output = filter_my_cmd(input);
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(input) as f64 * 100.0);
assert!(savings >= 60.0, "Expected >=60% savings, got {:.1}%", savings);
}
```
### Pre-Commit Gate (mandatory)
All three must pass before any PR:
@@ -184,15 +235,19 @@ cargo fmt --all --check && cargo clippy --all-targets && cargo test
## Documentation
Every change **must** include documentation updates. Update the relevant file(s) depending on what you changed:
Every change **must** include documentation updates. Use this table to find which docs to update:
| What you changed | Update |
|------------------|--------|
| New command or filter | [README.md](README.md) (command list + examples) and [CHANGELOG.md](CHANGELOG.md) |
| Architecture or internal design | [ARCHITECTURE.md](ARCHITECTURE.md) |
| Installation or setup | [INSTALL.md](INSTALL.md) |
| What you changed | Update these docs |
|------------------|-------------------|
| New Rust filter (`src/cmds/`) | Ecosystem `README.md` (e.g., `src/cmds/git/README.md`), [README.md](README.md) command list, [CHANGELOG.md](CHANGELOG.md) |
| New TOML filter (`src/filters/`) | [src/filters/README.md](src/filters/README.md) if naming conventions change, [README.md](README.md) command list, [CHANGELOG.md](CHANGELOG.md) |
| New rewrite pattern | `src/discover/rules.rs` — see [Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter) |
| Core infrastructure (`src/core/`) | [src/core/README.md](src/core/README.md), [docs/TECHNICAL.md](docs/TECHNICAL.md) if flow changes |
| Hook system (`src/hooks/`) | [src/hooks/README.md](src/hooks/README.md), [hooks/README.md](hooks/README.md) for agent-facing docs |
| Architecture or design change | [ARCHITECTURE.md](ARCHITECTURE.md), [docs/TECHNICAL.md](docs/TECHNICAL.md) |
| Bug fix or breaking change | [CHANGELOG.md](CHANGELOG.md) |
| Tracking / analytics | [docs/tracking.md](docs/tracking.md) |
**Navigation**: [CONTRIBUTING.md](CONTRIBUTING.md) (you are here) → [docs/TECHNICAL.md](docs/TECHNICAL.md) (architecture + flow) → each folder's `README.md` (implementation details).
Keep documentation concise and practical -- examples over explanations.
Generated
+14 -2
View File
@@ -100,6 +100,17 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "automod"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8b5778837666541195063243828c5b6139221b47dc4ec3ba81738e532469ab1"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "base64"
version = "0.22.1"
@@ -892,14 +903,16 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.34.0"
version = "0.34.1"
dependencies = [
"anyhow",
"automod",
"chrono",
"clap",
"colored",
"dirs",
"flate2",
"getrandom 0.4.2",
"hostname",
"ignore",
"lazy_static",
@@ -910,7 +923,6 @@ dependencies = [
"serde_json",
"sha2",
"tempfile",
"thiserror",
"toml",
"ureq",
"walkdir",
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.34.0"
version = "0.34.1"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
@@ -25,14 +25,15 @@ dirs = "5"
rusqlite = { version = "0.31", features = ["bundled"] }
toml = "0.8"
chrono = "0.4"
thiserror = "1.0"
tempfile = "3"
sha2 = "0.10"
ureq = "2"
hostname = "0.4"
getrandom = "0.4"
flate2 = "1.0"
quick-xml = "0.37"
which = "8"
automod = "1"
[build-dependencies]
toml = "0.8"
+3 -3
View File
@@ -33,7 +33,7 @@
---
rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, zero dependencies, <10ms overhead.
rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, 100+ supported commands, <10ms overhead.
## Token Savings (30-min Claude Code Session)
@@ -472,10 +472,10 @@ brew uninstall rtk # If installed via Homebrew
## Privacy & Telemetry
RTK collects **anonymous, aggregate usage metrics** once per day to help prioritize development. This is standard practice for open-source CLI tools.
RTK collects **anonymous, aggregate usage metrics** once per day, **enabled by default**. This helps prioritize development. See opt-out options below.
**What is collected:**
- Device hash (SHA-256 of hostname+username, not reversible)
- Device hash (salted SHA-256 — per-user random salt stored locally, not reversible)
- RTK version, OS, architecture
- Command count (last 24h) and top command names (e.g. "git", "cargo" — no arguments, no file paths)
- Token savings percentage
-102
View File
@@ -1,102 +0,0 @@
# Testing Execution Time Tracking
## Quick Test
```bash
# 1. Install latest version
cargo install --path .
# 2. Run a few commands to populate data
rtk git status
rtk ls .
rtk grep "tracking" src/
# 3. Check gain stats (should show execution times)
rtk gain
# Expected output:
# Total exec time: XX.Xs (avg XXms)
# By Command table should show Time column
```
## Detailed Test Scenarios
### 1. Basic Time Tracking
```bash
# Run commands with different execution times
rtk git log -10 # Fast (~10ms)
rtk cargo test # Slow (~300ms)
rtk vitest run # Very slow (seconds)
# Verify times are recorded
rtk gain
# Should show different avg times per command
```
### 2. Daily Breakdown
```bash
rtk gain --daily
# Expected:
# Date column + Time column showing avg time per day
# Today should have non-zero times
# Historical data shows 0ms (no time recorded)
```
### 3. Export Formats
**JSON Export:**
```bash
rtk gain --daily --format json | jq '.summary'
# Should include:
# "total_time_ms": 12345,
# "avg_time_ms": 67
```
**CSV Export:**
```bash
rtk gain --daily --format csv
# Headers should include:
# date,commands,input_tokens,...,total_time_ms,avg_time_ms
```
### 4. Multiple Commands
```bash
# Run 10 commands and measure total time
for i in {1..10}; do rtk git status; done
rtk gain
# Total exec time should be ~10-50ms (10 × 1-5ms)
```
## Verification Checklist
- [ ] `rtk gain` shows "Total exec time: X (avg Yms)"
- [ ] By Command table has "Time" column
- [ ] `rtk gain --daily` shows time per day
- [ ] JSON export includes `total_time_ms` and `avg_time_ms`
- [ ] CSV export has time columns
- [ ] New commands show realistic times (not 0ms)
- [ ] Historical data preserved (old entries show 0ms)
## Database Schema Verification
```bash
# Check SQLite schema includes exec_time_ms
sqlite3 ~/.local/share/rtk/history.db "PRAGMA table_info(commands);"
# Should show:
# ...
# 7|exec_time_ms|INTEGER|0|0|0
```
## Performance Impact
The timer adds negligible overhead:
- `Instant::now()` → ~10-50ns
- `elapsed()` → ~10-50ns
- SQLite insert with extra column → ~1-5µs
Total overhead: **< 0.1ms per command**
+9
View File
@@ -3,6 +3,15 @@ use std::fs;
use std::path::Path;
fn main() {
#[cfg(windows)]
{
// Clap + the full command graph can exceed the default 1 MiB Windows
// main-thread stack during process startup. Reserve a larger stack for
// the CLI binary so `rtk.exe --version`, `--help`, and hook entry
// points start reliably without requiring ad-hoc RUSTFLAGS.
println!("cargo:rustc-link-arg=/STACK:8388608");
}
let filters_dir = Path::new("src/filters");
let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR must be set by Cargo");
let dest = Path::new(&out_dir).join("builtin_filters.toml");
+432
View File
@@ -0,0 +1,432 @@
# RTK Technical Documentation
> **Start here** for a guided tour of how RTK works end-to-end.
>
> - [CONTRIBUTING.md](../CONTRIBUTING.md) — Design philosophy, PR process, branch naming, testing requirements
> - [ARCHITECTURE.md](../ARCHITECTURE.md) — Deep reference: filtering taxonomy, performance benchmarks, architecture decisions
> - Each folder has its own `README.md` with implementation details and file descriptions
---
## 1. Project Vision
LLM-powered coding agents (Claude Code, Copilot, Cursor, etc.) consume tokens for every CLI command output they process. Most command outputs contain boilerplate, progress bars, ANSI escape codes, and verbose formatting that wastes tokens without providing actionable information.
RTK sits between the agent and the CLI, filtering outputs to keep only what matters. This achieves 60-90% token savings per command, reducing costs and increasing effective context window utilization. RTK is a single Rust binary with no runtime dependencies beyond the compiled binary itself, adding less than 10ms overhead per command.
---
## 2. Architecture Overview
```
User / LLM Agent
|
v
+--------------------------------------------------+
| LLM Agent Hook |
| hooks/{claude,copilot,cursor,...}/ |
| Intercepts: "git status" -> "rtk git status" |
+-------------------------+------------------------+
|
v
+--------------------------------------------------+
| RTK CLI (main.rs) |
| |
| +-------------+ +-----------------+ |
| | Clap Parser | -> | Command Routing | |
| | (Commands | | (match on enum) | |
| | enum) | +--------+--------+ |
| +-------------+ | |
| +---------+---------+ |
| v v v |
| +----------+ +--------+ +----------+|
| |Rust Filter| |TOML DSL| |Passthru ||
| |(cmds/**) | |Filter | |(fallback)||
| +-----+----+ +----+---+ +----+-----+|
| | | | |
| +-----+-----+-----------+ |
| v |
| +---------------------+ |
| | Token Tracking | |
| | (core/tracking) | |
| | SQLite DB | |
| +---------------------+ |
+--------------------------------------------------+
```
**Design principles:**
- Single-threaded, no async (startup < 10ms)
- Graceful degradation: filter failure falls back to raw output
- Exit code propagation: RTK never swallows non-zero exits
- Transparent proxy: unknown commands pass through unchanged
---
## 3. End-to-End Flow
This is the full lifecycle of a command through RTK, from LLM agent to filtered output.
### 3.1 Hook Installation (`rtk init`)
The user runs `rtk init` to set up hooks for their LLM agent. This:
1. Writes a thin shell hook script (e.g., `~/.claude/hooks/rtk-rewrite.sh`)
2. Stores its SHA-256 hash for integrity verification
3. Patches the agent's settings file (e.g., `settings.json`) to register the hook
4. Writes RTK awareness instructions (e.g., `RTK.md`) for prompt-level guidance
RTK supports 7 agents, each with its own installation mode. The hook scripts are embedded in the binary and written at install time.
> **Details**: [`src/hooks/README.md`](../src/hooks/README.md) covers all installation modes, configuration files, and the uninstall flow.
### 3.2 Hook Interception (Command Rewriting)
When an LLM agent runs a command (e.g., `git status`):
1. The agent fires a `PreToolUse` event (or equivalent) containing the command as JSON
2. The hook script reads the JSON, extracts the command string
3. The hook calls `rtk rewrite "git status"` as a subprocess
4. `rtk rewrite` consults the command registry and returns `rtk git status`
5. The hook sends a response telling the agent to use the rewritten command
6. If anything fails (jq missing, rtk not found, no match), the hook exits silently -- the raw command runs unchanged
All rewrite logic lives in Rust (`src/discover/registry.rs`). Hooks are thin delegates that handle agent-specific JSON formats.
> **Details**: [`hooks/README.md`](../hooks/README.md) covers each agent's JSON format, the rewrite registry, compound command handling, and the `RTK_DISABLED` override.
#### Rewrite Pipeline
The rewrite pipeline is how RTK intercepts and rewrites commands. The call chain is:
```
hook shell → rewrite_cmd.rs → rewrite_command() → rewrite_compound() → rewrite_segment() → classify_command()
```
Traced step by step for `cargo fmt --all && cargo test 2>&1 | tail -20`:
```
LLM Agent: "cargo fmt --all && cargo test 2>&1 | tail -20"
|
| Hook shell (hooks/claude/rtk-rewrite.sh)
| Reads JSON from agent, extracts command, calls `rtk rewrite "$CMD"`
| On failure (jq missing, rtk missing, old version): exit 0 (passthrough)
|
v
rewrite_cmd::run(cmd) [src/hooks/rewrite_cmd.rs]
| 1. Load config → hooks.exclude_commands
| 2. check_command(cmd) → Deny → exit(2)
| 3. registry::rewrite_command(cmd, excluded)
| → None → exit(1) (no RTK equivalent, passthrough)
| → Some + Allow → print, exit(0)
| → Some + Ask → print, exit(3)
|
v
rewrite_command(cmd, excluded) [src/discover/registry.rs]
| Early exits:
| - Empty → None
| - Contains "<<" or "$((" (heredoc/arithmetic) → None
| - Simple "rtk ..." (no operators) → return as-is
| - Otherwise → rewrite_compound(cmd, excluded)
|
v
rewrite_compound(cmd, excluded) [src/discover/registry.rs]
|
| Step 1 — Tokenize (lexer.rs)
| tokenize() produces typed tokens with byte offsets:
| Arg("cargo") Arg("fmt") Arg("--all")
| Operator("&&")
| Arg("cargo") Arg("test") Redirect("2>&1")
| Pipe("|")
| Arg("tail") Arg("-20")
|
| Step 2 — Split on operators, rewrite each segment
| Operator (&&, ||, ;) → rewrite both sides
| Pipe (|) → rewrite left side only, keep right side raw
| exception: find/fd before pipe → skip rewrite
| Shellism (&) → rewrite both sides (background)
|
| Calls rewrite_segment() per segment:
| segment 1: "cargo fmt --all"
| segment 2: "cargo test 2>&1"
| after pipe: "tail -20" kept raw
|
v
rewrite_segment(seg, excluded) [src/discover/registry.rs]
|
| Step 3 — Strip trailing redirects
| strip_trailing_redirects() re-tokenizes the segment:
| "cargo test 2>&1" → cmd_part="cargo test", redirect=" 2>&1"
| (simple commands like "cargo fmt --all" → no redirect, suffix is "")
|
| Step 4 — Already RTK → return as-is
|
| Step 5 — Special cases (short-circuit before classification)
| head -N / --lines=N → rewrite_line_range() → "rtk read file --max-lines N"
| tail -N / -n N / --lines N → rewrite_line_range() → "rtk read file --tail-lines N"
| head/tail with unsupported flag (-c, -f) → None (skip rewrite)
| cat with incompatible flag (-A, -v, -e) → None (skip rewrite)
|
| Step 6 — classify_command(cmd_part) [see below]
| → Supported → check excluded list → continue
| → Unsupported/Ignored → None (skip rewrite)
|
| Step 7 — Build rewritten command
| a. Find matching rule from rules.rs
| b. Extract env prefix (ENV_PREFIX regex, second pass — first was in classify)
| e.g. "GIT_SSH_COMMAND=\"ssh -o ...\" git push" → prefix="GIT_SSH_COMMAND=..."
| c. Guard: RTK_DISABLED=1 in prefix → None
| d. Guard: gh with --json/--jq/--template → None
| e. Apply rule's rewrite_prefixes: "cargo fmt" → "rtk cargo fmt"
| f. Reassemble: env_prefix + rtk_cmd + args + redirect_suffix
|
v
classify_command(cmd) [src/discover/registry.rs]
| 1. Check IGNORED_EXACT (cd, echo, fi, done, ...)
| 2. Check IGNORED_PREFIXES (rtk, mkdir, mv, ...)
| 3. Strip env prefix with ENV_PREFIX regex (for pattern matching only)
| 4. Normalize absolute paths: /usr/bin/grep → grep
| 5. Strip git global opts: git -C /tmp status → git status
| 6. Guard: cat/head/tail with redirect (>, >>) → Unsupported (write, not read)
| 7. Match against REGEX_SET (60+ compiled patterns from rules.rs)
| 8. Extract subcommand → lookup custom savings/status overrides
| 9. Return Classification::Supported { rtk_equivalent, category, savings, status }
|
v
Result: "rtk cargo fmt --all && rtk cargo test 2>&1 | tail -20"
|
| Hook response
| Hook wraps result in agent-specific JSON, returns to LLM agent
|
v
LLM Agent executes rewritten command
(bash handles && and |, each rtk invocation is a separate process)
```
Key design decisions:
- **Lexer-based tokenization**: A single-pass state machine (`lexer.rs`) handles all shell constructs (quotes, escapes, redirects, operators). Used for both compound splitting and redirect stripping.
- **Segment-level rewriting**: Compound commands are split by operators, each segment rewritten independently. Bash recombines them at execution time.
- **Pipe semantics**: Only the left side of `|` is rewritten. The pipe consumer (grep, head, wc) runs raw. `find`/`fd` before a pipe is never rewritten (output format incompatible with xargs).
- **Double env prefix handling**: `classify_command()` strips env prefixes to match the underlying command against rules. `rewrite_segment()` extracts the same prefix separately to re-prepend it to the rewritten command.
- **Fallback contract**: If any segment fails to match, it stays raw. `rewrite_command()` returns `None` only when zero segments were rewritten.
### 3.3 CLI Parsing and Routing
Once the rewritten command reaches RTK:
1. **Telemetry**: `telemetry::maybe_ping()` fires a non-blocking daily usage ping
2. **Clap parsing**: `Cli::try_parse()` matches against the `Commands` enum
3. **Hook check**: `hook_check::maybe_warn()` warns if the installed hook is outdated (rate-limited to 1/day)
4. **Integrity check**: `integrity::runtime_check()` verifies the hook's SHA-256 hash for operational commands
5. **Routing**: A `match cli.command` dispatches to the specialized filter module
If Clap parsing fails (command not in the enum), the fallback path runs instead.
### 3.4 Filter Execution
RTK has two filter systems:
**Rust Filters**: Compiled modules in `src/cmds/` that execute the command, parse its output, and apply specialized transformations (regex, JSON, state machines).
**TOML DSL Filters**: Declarative filters in `src/filters/*.toml` that apply regex-based line filtering, truncation, and section extraction. Applied in `run_fallback()` when no Rust filter matches.
Each filter module follows the same pattern:
1. Start a timer (`TimedExecution::start()`)
2. Execute the underlying command (`std::process::Command`)
3. Apply filtering (strip boilerplate, group errors, truncate)
4. On filter error, fall back to raw output
5. Track token savings to SQLite
6. Propagate exit code
> **Details**: [`src/cmds/README.md`](../src/cmds/README.md) covers the common pattern, ecosystem organization, cross-command dependencies, and how to add new filters.
### 3.5 Fallback Path
When Clap parsing fails (unknown command):
1. Guard: check if the command is an RTK meta-command (`gain`, `init`, etc.) -- if so, show Clap error
2. Look up TOML DSL filters via `toml_filter::find_matching_filter()`
3. If TOML match: capture stdout, apply filter pipeline, track savings
4. If no match: pure passthrough with `Stdio::inherit`, track as 0% savings
```
Command received
-> Clap parse succeeds?
-> Yes: Route to Rust filter module
-> No: run_fallback()
-> TOML filter match?
-> Yes: Capture stdout, apply filter, track savings
-> No: Passthrough (inherit stdio, track 0% savings)
```
> **Details**: [`src/core/README.md`](../src/core/README.md) covers the TOML filter engine, filter pipeline stages, and trust-gated project filters.
### 3.6 Token Tracking
Every command execution records metrics to SQLite (`~/.local/share/rtk/tracking.db`):
- Input tokens (raw output size) and output tokens (filtered size)
- Savings percentage, execution time, project path
- 90-day automatic retention cleanup
- Token estimation: `ceil(chars / 4.0)` approximation
Analytics commands (`rtk gain`, `rtk cc-economics`, `rtk session`) query this database to produce dashboards and ROI reports.
> **Details**: [`src/analytics/README.md`](../src/analytics/README.md) covers the analytics modules, and [`src/core/README.md`](../src/core/README.md) covers the tracking database schema.
### 3.7 Tee Recovery
On command failure (non-zero exit code):
1. Raw unfiltered output is saved to `~/.local/share/rtk/tee/{epoch}_{slug}.log`
2. A hint line is printed: `[full output: ~/.../tee/1234_cargo_test.log]`
3. LLM agents can re-read the file instead of re-running the failed command
Tee is configurable (enabled/disabled, min size, max files, max file size) and never affects command output or exit code on failure.
> **Details**: [`src/core/README.md`](../src/core/README.md) covers tee configuration and the rotation strategy.
---
## 4. Folder Map
Start here, then drill down into each README for file-level details.
### `src/` — Rust source code
| Directory | What it does | What you'll find in its README |
|-----------|-------------|-------------------------------|
| `main.rs` | CLI entry point, `Commands` enum, routing match | _(no README — read the file directly)_ |
| [`core/`](../src/core/README.md) | Shared infrastructure | Tracking DB schema, config system, tee recovery, TOML filter engine, utility functions |
| [`hooks/`](../src/hooks/README.md) | Hook system | Installation flow (`rtk init`), integrity verification, rewrite command, trust model |
| [`analytics/`](../src/analytics/README.md) | Token savings analytics | `rtk gain` dashboard, Claude Code economics, ccusage parsing |
| [`cmds/`](../src/cmds/README.md) | **Command filters (9 ecosystems)** | Common filter pattern, cross-command routing, token savings table, **links to each ecosystem** |
| [`discover/`](../src/discover/README.md) | History analysis + rewrite registry | Rewrite patterns, session providers, compound command splitting |
| [`learn/`](../src/learn/README.md) | CLI correction detection | Error classification, correction pair detection, rule generation |
| [`parser/`](../src/parser/README.md) | Parser infrastructure | Canonical types (TestResult, LintResult, etc.), 3-tier format modes, migration guide |
| [`filters/`](../src/filters/README.md) | TOML filter configs | TOML DSL syntax, 8-stage pipeline, inline testing, naming conventions |
### `hooks/` — Deployed hook artifacts (root directory)
| Directory | Agent | What you'll find in its README |
|-----------|-------|-------------------------------|
| [`hooks/`](../hooks/README.md) | _(parent)_ | **All JSON formats**, rewrite registry overview, exit code contract, override controls |
| [`claude/`](../hooks/claude/README.md) | Claude Code | Shell hook mechanism, `PreToolUse` JSON, test script |
| [`copilot/`](../hooks/copilot/README.md) | GitHub Copilot | Rust binary hook, VS Code Chat vs Copilot CLI dual format |
| [`cursor/`](../hooks/cursor/README.md) | Cursor IDE | Shell hook, empty JSON response requirement |
| [`cline/`](../hooks/cline/README.md) | Cline / Roo Code | Rules file (prompt-level, no programmatic hook) |
| [`windsurf/`](../hooks/windsurf/README.md) | Windsurf / Cascade | Rules file (workspace-scoped) |
| [`codex/`](../hooks/codex/README.md) | OpenAI Codex CLI | Awareness document, AGENTS.md integration |
| [`opencode/`](../hooks/opencode/README.md) | OpenCode | TypeScript plugin, zx library, in-place mutation |
---
## 5. Hook System Summary
RTK supports the following LLM agents through hook integrations:
| Agent | Hook Type | Mechanism | Can Modify Command? |
|-------|-----------|-----------|---------------------|
| Claude Code | Shell hook | `PreToolUse` in `settings.json` | Yes (`updatedInput`) |
| GitHub Copilot (VS Code) | Rust binary | `rtk hook copilot` reads JSON | Yes (`updatedInput`) |
| GitHub Copilot CLI | Rust binary | `rtk hook copilot` reads JSON | No (deny + suggestion) |
| Cursor | Shell hook | `preToolUse` hook | Yes (`updated_input`) |
| Gemini CLI | Rust binary | `rtk hook gemini` reads JSON | Yes (`hookSpecificOutput`) |
| Cline/Roo Code | Rules file | Prompt-level guidance | N/A (prompt) |
| Windsurf | Rules file | Prompt-level guidance | N/A (prompt) |
| Codex CLI | Awareness doc | AGENTS.md integration | N/A (prompt) |
| OpenCode | TS plugin | `tool.execute.before` event | Yes (in-place mutation) |
> **Details**: [`hooks/README.md`](../hooks/README.md) has the full JSON schemas for each agent. [`src/hooks/README.md`](../src/hooks/README.md) covers installation, integrity verification, and the rewrite command.
---
## 6. Filter Pipeline Summary
### Rust Filters (cmds/**)
Compiled filter modules for complex transformations with 60-95% token savings.
> **Details**: [`src/cmds/README.md`](../src/cmds/README.md) and each ecosystem subdirectory README.
### TOML DSL Filters (src/filters/*.toml)
Declarative filters with an 8-stage pipeline: strip ANSI, regex replace, match output, strip/keep lines, truncate lines, head/tail, max lines, on-empty message. Loaded from three tiers: built-in (compiled), global (`~/.config/rtk/filters/`), project-local (`.rtk/filters/`, trust-gated).
> **Details**: [`src/core/README.md`](../src/core/README.md) covers the TOML filter engine.
---
## 7. Performance Constraints
| Metric | Target | Verification |
|--------|--------|--------------|
| Startup time | < 10ms | `hyperfine 'rtk git status' 'git status'` |
| Memory usage | < 5MB resident | `/usr/bin/time -v rtk git status` |
| Binary size | < 5MB stripped | `ls -lh target/release/rtk` |
| Token savings | 60-90% per filter | Snapshot + token count tests |
Achieved through:
- Zero async overhead (single-threaded, no tokio)
- Lazy regex compilation (`lazy_static!`)
- Minimal allocations (borrow over clone)
- No config file I/O on startup (loaded on-demand)
---
## 8. Testing
Tests live **in the module file itself** inside a `#[cfg(test)] mod tests` block (e.g., tests for `src/cmds/cloud/container.rs` go at the bottom of that same file).
### How to Write Tests
**1. Create a fixture from real command output** (not synthetic data):
```bash
kubectl get pods > tests/fixtures/kubectl_pods_raw.txt
```
**2. Write your test in the same module file** (`#[cfg(test)] mod tests`):
```rust
#[test]
fn test_my_filter() {
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
let output = filter_my_cmd(input);
assert!(output.contains("expected content"));
assert!(!output.contains("noise line"));
}
```
**3. Verify token savings** (60% minimum required):
```rust
#[test]
fn test_my_filter_savings() {
let input = include_str!("../tests/fixtures/my_cmd_raw.txt");
let output = filter_my_cmd(input);
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(input) as f64 * 100.0);
assert!(savings >= 60.0, "Expected >=60% savings, got {:.1}%", savings);
}
```
### Test Organization
```
tests/
├── fixtures/ # Real command output (never synthetic)
│ ├── git_log_raw.txt
│ ├── cargo_test_raw.txt
│ └── dotnet/ # Ecosystem-specific fixtures
└── integration_test.rs # Integration tests (#[ignore])
```
- **Unit tests**: `#[cfg(test)] mod tests` embedded in each module
- **Fixtures**: real command output in `tests/fixtures/`
- **Integration tests**: `#[ignore]` attribute, run with `cargo test --ignored`
> For testing requirements, pre-commit gate, and PR checklist, see [CONTRIBUTING.md — Testing](../CONTRIBUTING.md#testing).
---
## 9. Future Improvements
- **Extract cli.rs**: Move `Commands` enum, 13 sub-enums (`GitCommands`, `CargoCommands`, etc.), and `AgentTarget` from main.rs to a dedicated cli.rs module. This would reduce main.rs from ~2600 to ~1500 lines.
- **Split routing**: Extract the `match cli.command { ... }` block into a separate routing module.
- **Streaming filters**: For long-running commands, filter output line-by-line as it arrives instead of buffering.
+72
View File
@@ -0,0 +1,72 @@
# RTK Maintainers Application
RTK is growing fast, with more contributors, PRs, and ideas than ever. To keep things moving smoothly, we're looking for new maintainers.
We've introduced two types of maintainers to progressively build a clean process and strong collaboration between contributors.
For now, we're starting by recruiting **Ecosystem Maintainers** only. As the project evolves, we'll soon begin accepting **Core Maintainers** as well.
> Maintainers are expected to be active and involved over time, not just occasional contributors.
---
## How to apply guide
#### ✅ Requirements
To apply, you should have:
- 3+ merged PRs to RTK (filters, fixes, docs — all contributions count)
- 3+ PR reviews with helpful, constructive feedback
---
### ✍️ How to Apply
1. Open a discussion in [rtk-ai/rtk Maintainers Applications · Discussions · GitHub](https://github.com/rtk-ai/rtk/discussions/categories/maintainers-applications) titled **Maintainer Application: [Your GitHub Handle]**
2. In your application, include:
- The ecosystem(s) you're interested in
- Your experience with those ecosystems
- Links to your merged PRs and reviews
- Your Discord username (and make sure you've joined the server)
- Your PRs that have been accepted in RTK
3. For **Core Maintainer** applications, also include:
- Your experience with Rust
- Your experience with Open Source
4. A Core Maintainer will get back to you as soon as possible
5. If it's a good fit, we'll continue the conversation on Discord and guide you through the next steps
---
### 👀 What to Expect
- A review of your ecosystem experience and understanding of RTK concepts
- A discussion with current maintainers
- Introduction to the team
---
## What Maintainers Do
### 🌱 Ecosystem Maintainers
Ecosystem Maintainers are responsible for specific environments inside the `cmds/` folder (e.g. `git`, `system`, etc.). They own and manage their ecosystem end-to-end:
- Responsible for the quality of filters
- Review and ensure quality of contributions
- Maintain consistency with the rest of the RTK ecosystem
- Help shape and grow their specific domain
- Handle issues and PRs related to their environment *(security and quality review from core maintainers still required for release)*
### 🔧 Core Maintainers (once we've fully integrated some Ecosystem Maintainers)
Core Maintainers are responsible for the core of RTK. They have a broader scope and higher responsibilities and permissions, including:
- Maintaining core functionalities and architecture
- Reviewing and merging PRs for release with the core team
- Defining project direction and standards with the core team
- Ensuring consistency across the entire project
- Refactoring for optimization, standardization & conformity
---
If you enjoy contributing and want to help RTK scale in a healthy way, we'd be excited to have you onboard 🚀
+2 -2
View File
@@ -538,8 +538,8 @@ let _ = conn.execute(
## Security & Privacy
- **Local storage only**: Database never leaves the machine
- **No telemetry**: RTK does not phone home or send analytics
- **Local storage only**: Tracking database never leaves the machine
- **Telemetry enabled by default**: RTK sends a daily anonymous usage ping (version, OS, command counts, token savings). Device identity is a salted SHA-256 hash. Opt out with `RTK_TELEMETRY_DISABLED=1` or `[telemetry] enabled = false` in `~/.config/rtk/config.toml`
- **User control**: Users can delete `~/.local/share/rtk/tracking.db` anytime
- **90-day retention**: Old data automatically purged
+235
View File
@@ -0,0 +1,235 @@
# LLM Agent Hooks
## Scope
**Deployed hook artifacts** — the actual files installed on user machines by `rtk init`. These are shell scripts, TypeScript plugins, and rules files that run outside the Rust binary. They are **thin delegates**: parse agent-specific JSON, call `rtk rewrite` as a subprocess, format agent-specific response. Zero filtering logic lives here.
Owns: per-agent hook scripts and configuration files for 7 supported agents (Claude Code, Copilot, Cursor, Cline, Windsurf, Codex, OpenCode).
Does **not** own: hook installation/uninstallation (that's `src/hooks/init.rs`), the rewrite pattern registry (that's `discover/registry`), or integrity verification (that's `src/hooks/integrity.rs`).
Relationship to `src/hooks/`: that component **creates** these files; this directory **contains** them.
## Purpose
LLM agent integrations that intercept CLI commands and route them through RTK for token optimization. Each hook transparently rewrites raw commands (e.g., `git status`) to their RTK equivalents (e.g., `rtk git status`), delivering 60-90% token savings without requiring the agent or user to change their workflow.
## How It Works
```
Agent runs command (e.g., "cargo test --nocapture")
-> Hook intercepts (PreToolUse / plugin event)
-> Reads JSON input, extracts command string
-> Calls `rtk rewrite "cargo test --nocapture"`
-> Registry matches pattern, returns "rtk cargo test --nocapture"
-> Hook sends response in agent-specific JSON format
-> Agent executes "rtk cargo test --nocapture" instead
-> Filtered output reaches LLM (~90% fewer tokens)
```
All rewrite logic lives in the Rust binary (`src/discover/registry.rs`). Hook scripts are **thin delegates** that handle agent-specific JSON formats and call `rtk rewrite` for the actual decision. This ensures a single source of truth for all 70+ rewrite patterns.
## Directory Structure
Each agent subdirectory has its own README with hook-specific details:
- **[`claude/`](claude/README.md)** — Shell hook, `PreToolUse` JSON format, `settings.json` patching, test script
- **[`copilot/`](copilot/README.md)** — Rust binary hook, dual format (VS Code Chat vs Copilot CLI), deny-with-suggestion fallback
- **[`cursor/`](cursor/README.md)** — Shell hook, Cursor JSON format, empty `{}` response requirement
- **[`cline/`](cline/README.md)** — Rules file (prompt-level), `.clinerules` project-local installation
- **[`windsurf/`](windsurf/README.md)** — Rules file (prompt-level), `.windsurfrules` workspace-scoped
- **[`codex/`](codex/README.md)** — Awareness document, `AGENTS.md` integration, `~/.codex/` location
- **[`opencode/`](opencode/README.md)** — TypeScript plugin, `zx` library, `tool.execute.before` event, in-place mutation
## Supported Agents
| Agent | Mechanism | Hook Type | Can Modify Command? |
|-------|-----------|-----------|---------------------|
| Claude Code | Shell hook (`PreToolUse`) | Transparent rewrite | Yes (`updatedInput`) |
| VS Code Copilot Chat | Rust binary (`rtk hook copilot`) | Transparent rewrite | Yes (`updatedInput`) |
| GitHub Copilot CLI | Rust binary (`rtk hook copilot`) | Deny-with-suggestion | No (agent retries) |
| Cursor | Shell hook (`preToolUse`) | Transparent rewrite | Yes (`updated_input`) |
| Gemini CLI | Rust binary (`rtk hook gemini`) | Transparent rewrite | Yes (`hookSpecificOutput`) |
| Cline / Roo Code | Custom instructions (rules file) | Prompt-level guidance | N/A |
| Windsurf | Custom instructions (rules file) | Prompt-level guidance | N/A |
| Codex CLI | AGENTS.md / instructions | Prompt-level guidance | N/A |
| OpenCode | TypeScript plugin (`tool.execute.before`) | In-place mutation | Yes |
## JSON Formats by Agent
### Claude Code (Shell Hook)
**Input** (stdin):
```json
{
"tool_name": "Bash",
"tool_input": { "command": "git status" }
}
```
**Output** (stdout, when rewritten):
```json
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": { "command": "rtk git status" }
}
}
```
### Cursor (Shell Hook)
**Input**: Same as Claude Code.
**Output** (stdout, when rewritten):
```json
{
"permission": "allow",
"updated_input": { "command": "rtk git status" }
}
```
Returns `{}` when no rewrite (Cursor requires JSON for all paths).
### Copilot CLI (Rust Binary)
**Input** (stdin, camelCase, `toolArgs` is JSON-stringified):
```json
{
"toolName": "bash",
"toolArgs": "{\"command\": \"git status\"}"
}
```
**Output** (no `updatedInput` support -- uses deny-with-suggestion):
```json
{
"permissionDecision": "deny",
"permissionDecisionReason": "Token savings: use `rtk git status` instead"
}
```
### VS Code Copilot Chat (Rust Binary)
**Input** (stdin, snake_case):
```json
{
"tool_name": "Bash",
"tool_input": { "command": "git status" }
}
```
**Output**: Same as Claude Code format (with `updatedInput`).
### Gemini CLI (Rust Binary)
**Input** (stdin):
```json
{
"tool_name": "run_shell_command",
"tool_input": { "command": "git status" }
}
```
**Output** (when rewritten):
```json
{
"decision": "allow",
"hookSpecificOutput": {
"tool_input": { "command": "rtk git status" }
}
}
```
**No rewrite**: `{"decision": "allow"}`
### OpenCode (TypeScript Plugin)
Mutates `args.command` in-place via the zx library:
```typescript
const result = await $`rtk rewrite ${command}`.quiet().nothrow()
const rewritten = String(result.stdout).trim()
if (rewritten && rewritten !== command) {
(args as Record<string, unknown>).command = rewritten
}
```
## Command Rewrite Registry
The registry (`src/discover/registry.rs`) handles command patterns across these categories:
| Category | Examples | Savings |
|----------|----------|---------|
| Test Runners | vitest, pytest, cargo test, go test, playwright | 90-99% |
| Build Tools | cargo build, npm, pnpm, dotnet, make | 70-90% |
| VCS | git status/log/diff/show | 70-80% |
| Language Servers | tsc, mypy | 80-83% |
| Linters | eslint, ruff, golangci-lint, biome | 80-85% |
| Package Managers | pip, cargo install, pnpm list | 75-80% |
| File Operations | ls, find, grep, cat, head, tail | 60-75% |
| Infrastructure | docker, kubectl, aws, terraform | 75-85% |
### Compound Command Handling
The registry handles `&&`, `||`, `;`, `|`, and `&` operators:
- **Pipe** (`|`): Only the left side is rewritten (right side consumes output format)
- **And/Or/Semicolon** (`&&`, `||`, `;`): Both sides rewritten independently
- **find/fd in pipes**: Never rewritten (output format incompatible with xargs/wc/grep)
Example: `cargo fmt --all && cargo test` becomes `rtk cargo fmt --all && rtk cargo test`
### Override Controls
- **`RTK_DISABLED=1`**: Per-command override (`RTK_DISABLED=1 git status` runs raw)
- **`exclude_commands`**: In `~/.config/rtk/config.toml`, list commands to never rewrite
- **Already-RTK**: `rtk git status` passes through unchanged (no `rtk rtk git`)
## Exit Code Contract
Hooks must **never block command execution**. All error paths (missing binary, bad JSON, rewrite failure) must exit 0 so the agent's command runs unmodified. A hook that exits non-zero prevents the user's command from executing.
When there is no rewrite to apply, the hook must produce no output (or `{}` for Cursor, which requires JSON on all paths).
### Gaps (to be fixed)
- `hook_cmd.rs::run_gemini()` — exits 1 on invalid JSON input instead of exit 0
## Graceful Degradation
Hooks are **non-blocking** -- they never prevent a command from executing:
- jq not installed: warning to stderr, exit 0 (command runs raw)
- rtk binary not found: warning to stderr, exit 0
- rtk version too old (< 0.23.0): warning to stderr, exit 0
- Invalid JSON input: pass through unchanged
- `rtk rewrite` crashes: hook exits 0 (subprocess error ignored)
- Filter logic error: fallback to raw command output
## Adding a New Agent Integration
New integrations must follow the [Exit Code Contract](#exit-code-contract) and [Graceful Degradation](#graceful-degradation) above, as well as the project's [Design Philosophy](../CONTRIBUTING.md#design-philosophy).
### Integration Tiers
| Tier | Mechanism | Maintenance | Examples |
|------|-----------|-------------|----------|
| **Full hook** | Shell script or Rust binary, intercepts commands via agent's hook API | High — must track agent API changes | Claude Code, Cursor, Copilot, Gemini |
| **Plugin** | TypeScript/JS plugin in agent's plugin system | Medium — agent manages loading | OpenCode |
| **Rules file** | Prompt-level instructions the agent reads | Low — no code to break | Cline, Windsurf, Codex |
### Eligibility
RTK supports AI coding assistants that developers actually use day-to-day. To add a new agent:
- Agent has a **documented, stable hook/plugin API** (not experimental/alpha)
- Agent is **actively maintained** (commit activity in last 3 months)
- Integration follows the **exit code contract** (exit 0 on all error paths)
- Hook output matches the **agent's expected JSON format** exactly
### Maintenance
If an agent's API changes and the hook breaks, the integration should be updated promptly. If the agent becomes unmaintained or the hook can't be fixed, the integration may be deprecated with a release note.
+24
View File
@@ -0,0 +1,24 @@
# Claude Code Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Shell-based `PreToolUse` hook -- requires `jq` for JSON parsing
- Returns `updatedInput` JSON for transparent command rewrite (agent doesn't know RTK is involved)
- Exits silently (exit 0) on any failure: jq missing, rtk missing, rtk too old (< 0.23.0), no match
- Version guard checks `rtk --version` against minimum 0.23.0
- `rtk-awareness.md` is a slim 10-line instructions file embedded into CLAUDE.md by `rtk init`
## Testing
```bash
# Run the full test suite (60+ assertions)
bash hooks/test-rtk-rewrite.sh
# Test against a specific hook path
HOOK=/path/to/rtk-rewrite.sh bash hooks/test-rtk-rewrite.sh
# Enable audit logging during testing
RTK_HOOK_AUDIT=1 RTK_AUDIT_DIR=/tmp bash hooks/test-rtk-rewrite.sh
```
File renamed without changes.
File renamed without changes.
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Test suite for rtk-rewrite.sh
# Feeds mock JSON through the hook and verifies the rewritten commands.
#
+9
View File
@@ -0,0 +1,9 @@
# Cline / Roo Code Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Prompt-level guidance only (no programmatic hook) -- relies on Cline reading custom instructions
- `rules.md` contains the instruction to prefix all shell commands with `rtk`, usage examples, and meta commands
- Installed to `.clinerules` (project-local) by `rtk init`
File renamed without changes.
+9
View File
@@ -0,0 +1,9 @@
# Codex CLI Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Prompt-level guidance via awareness document -- no programmatic hook
- `rtk-awareness.md` is injected into `AGENTS.md` with an `@RTK.md` reference
- Installed to `~/.codex/` by `rtk init --codex`
File renamed without changes.
+16
View File
@@ -0,0 +1,16 @@
# GitHub Copilot Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Uses the `rtk hook copilot` Rust binary (not a shell script) -- no `jq` dependency
- Auto-detects two input formats: VS Code Copilot Chat (snake_case `tool_name`/`tool_input`) and Copilot CLI (camelCase `toolName`/`toolArgs` with JSON-stringified args)
- VS Code format: returns `updatedInput` for transparent rewrite
- Copilot CLI format: returns `permissionDecision: "deny"` with suggestion (Copilot CLI API doesn't support `updatedInput`)
## Testing
```bash
bash hooks/test-copilot-rtk-rewrite.sh
```
File renamed without changes.
File renamed without changes.
+9
View File
@@ -0,0 +1,9 @@
# Cursor IDE Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Same delegating pattern as Claude Code hook but outputs Cursor's JSON format (`permission`/`updated_input` instead of `hookSpecificOutput`/`updatedInput`)
- Returns `{}` (empty JSON) when no rewrite applies -- Cursor requires JSON output for all code paths
- Requires `jq` and `rtk >= 0.23.0`
View File
File renamed without changes.
+11
View File
@@ -0,0 +1,11 @@
# OpenCode Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- TypeScript plugin using the zx library (not a shell hook)
- Intercepts `tool.execute.before` events, calls `rtk rewrite` as a subprocess
- Uses `.quiet().nothrow()` to silently ignore failures
- Mutates `args.command` in-place if rewrite differs from original
- Installed to `~/.config/opencode/plugins/rtk.ts` by `rtk init -g --opencode`
File renamed without changes.
+9
View File
@@ -0,0 +1,9 @@
# Windsurf (Cascade) Hooks
> Part of [`hooks/`](../README.md) — see also [`src/hooks/`](../../src/hooks/README.md) for installation code
## Specifics
- Prompt-level guidance only (no programmatic hook) -- relies on Windsurf Cascade reading rules files
- `rules.md` contains the instruction to prefix commands with `rtk`
- Installed to `.windsurfrules` (project-local, workspace-scoped) by `rtk init`
File renamed without changes.
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/sh
#!/usr/bin/env sh
# rtk installer - https://github.com/rtk-ai/rtk
# Usage: curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
# Use local release build if available, otherwise fall back to installed rtk
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# RTK Installation Verification Script
# Helps diagnose if you have the correct rtk (Token Killer) installed
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
set -euo pipefail
# check-test-presence.sh — CI guard: new/modified *_cmd.rs files must have #[cfg(test)]
#
# Usage:
# bash scripts/check-test-presence.sh [BASE_BRANCH]
# bash scripts/check-test-presence.sh --self-test
#
# BASE_BRANCH defaults to origin/develop
if [ "${1:-}" = "--self-test" ]; then
# Self-test: create a tempfile without tests and verify the check catches it
TMPFILE="src/cmds/system/_rtk_check_self_test_cmd.rs"
echo "pub fn run() {}" > "$TMPFILE"
trap 'rm -f "$TMPFILE"' EXIT
if grep -q '#\[cfg(test)\]' "$TMPFILE"; then
echo "FAIL: self-test broken (false negative)"
exit 1
fi
rm "$TMPFILE"
trap - EXIT
echo "PASS: --self-test detection works correctly"
exit 0
fi
BASE_BRANCH="${1:-origin/develop}"
EXIT_CODE=0
# Find *_cmd.rs files that were added or modified in this PR
CHANGED_FILES=$(git diff --name-only --diff-filter=AM --no-renames "$BASE_BRANCH"...HEAD \
2>/dev/null | grep -E 'src/cmds/.+_cmd\.rs$' || true)
if [ -z "$CHANGED_FILES" ]; then
echo "check-test-presence: no *_cmd.rs changes detected — OK"
exit 0
fi
echo "check-test-presence: checking $(echo "$CHANGED_FILES" | wc -l | tr -d ' ') filter module(s)..."
echo ""
while IFS= read -r file; do
if [ ! -f "$file" ]; then
continue
fi
if grep -q '#\[cfg(test)\]' "$file"; then
echo " PASS $file"
else
echo " FAIL $file"
echo " Missing #[cfg(test)] module."
echo " Every *_cmd.rs filter must include inline unit tests."
echo " Reference: src/cmds/cloud/aws_cmd.rs"
echo ""
EXIT_CODE=1
fi
done <<< "$CHANGED_FILES"
echo ""
if [ "$EXIT_CODE" -ne 0 ]; then
echo "check-test-presence: FAILED — add tests before merging."
echo "See .claude/rules/cli-testing.md for the testing guide."
else
echo "check-test-presence: all filter modules have tests — OK"
fi
exit "$EXIT_CODE"
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Install RTK from a local release build (builds from source, no network download).
set -euo pipefail
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# rtk-economics.sh
# Combine ccusage (tokens spent) with rtk (tokens saved) for economic analysis
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
REPORT="benchmark-report.md"
+13 -29
View File
@@ -1,43 +1,27 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
echo "🔍 Validating RTK documentation consistency..."
# 1. Nombre de modules cohérent
MAIN_MODULES=$(grep -c '^mod ' src/main.rs)
echo "📊 Module count in main.rs: $MAIN_MODULES"
# Extract module count from ARCHITECTURE.md
if [ -f "ARCHITECTURE.md" ]; then
ARCH_MODULES=$(grep 'Total:.*modules' ARCHITECTURE.md | grep -o '[0-9]\+' | head -1)
if [ -z "$ARCH_MODULES" ]; then
echo "⚠️ Could not extract module count from ARCHITECTURE.md"
else
echo "📊 Module count in ARCHITECTURE.md: $ARCH_MODULES"
if [ "$MAIN_MODULES" != "$ARCH_MODULES" ]; then
echo "❌ Module count mismatch: main.rs=$MAIN_MODULES, ARCHITECTURE.md=$ARCH_MODULES"
exit 1
fi
fi
fi
# 1. Source file count sanity check
SRC_FILES=$(find src -name "*.rs" ! -name "mod.rs" ! -name "main.rs" | wc -l | tr -d ' ')
echo "📊 Rust source files in src/: $SRC_FILES"
# 3. Commandes Python/Go présentes partout
PYTHON_GO_CMDS=("ruff" "pytest" "pip" "go" "golangci")
echo "🐍 Checking Python/Go commands documentation..."
for cmd in "${PYTHON_GO_CMDS[@]}"; do
for file in README.md CLAUDE.md; do
if [ ! -f "$file" ]; then
echo "⚠️ $file not found, skipping"
continue
fi
if ! grep -q "$cmd" "$file"; then
echo "❌ $file ne mentionne pas commande $cmd"
exit 1
fi
done
if [ ! -f "README.md" ]; then
echo "⚠️ README.md not found, skipping"
break
fi
if ! grep -q "$cmd" "README.md"; then
echo "❌ README.md ne mentionne pas commande $cmd"
exit 1
fi
done
echo "✅ Python/Go commands: documented in README.md and CLAUDE.md"
echo "✅ Python/Go commands: documented in README.md"
# 4. Hooks cohérents avec doc
HOOK_FILE=".claude/hooks/rtk-rewrite.sh"
+21
View File
@@ -0,0 +1,21 @@
# Analytics
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
## Scope
**Read-only dashboards** over the tracking database. Queries token savings, correlates with external spending data, and surfaces adoption metrics. Never modifies the tracking DB.
Owns: `rtk gain` (savings dashboard), `rtk cc-economics` (cost reduction), `rtk session` (adoption analysis), and Claude Code usage data parsing.
Does **not** own: recording token savings (that's `core/tracking` called by `cmds/`), or command filtering itself (that's `cmds/`).
Boundary rule: if a new module writes to the DB, it belongs in `core/` or `cmds/`, not here. Tool-specific analytics (like `cc_economics` reading Claude Code data) are fine — the boundary is "read-only presentation", not "tool-agnostic".
## Purpose
Token savings analytics, economic modeling, and adoption metrics.
These modules read from the SQLite tracking database to produce dashboards, spending estimates, and session-level adoption reports.
## Adding New Functionality
To add a new analytics view: (1) create a new `*_cmd.rs` file in this directory, (2) query `core/tracking` for the metrics you need using the existing `TrackingDb` API, (3) register the command in `main.rs` under the `Commands` enum, and (4) add `#[cfg(test)]` unit tests with sample tracking data. Analytics modules should be read-only against the tracking database and never modify it.
@@ -8,15 +8,12 @@ use chrono::NaiveDate;
use serde::Serialize;
use std::collections::HashMap;
use crate::ccusage::{self, CcusagePeriod, Granularity};
use crate::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::utils::{format_cpt, format_tokens, format_usd};
use super::ccusage::{self, CcusagePeriod, Granularity};
use crate::core::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::core::utils::{format_cpt, format_tokens, format_usd};
// ── Constants ──
#[allow(dead_code)]
const BILLION: f64 = 1e9;
// API pricing ratios (verified Feb 2026, consistent across Claude models <=200K context)
// Source: https://docs.anthropic.com/en/docs/about-claude/models
const WEIGHT_OUTPUT: f64 = 5.0; // Output = 5x input
@@ -207,7 +204,7 @@ fn merge_daily(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<DayStats>) -> Vec<Period
// Insert ccusage data
if let Some(cc_data) = cc {
for entry in cc_data {
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
let super::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
@@ -237,7 +234,7 @@ fn merge_weekly(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<WeekStats>) -> Vec<Peri
// Insert ccusage data (key = ISO Monday "2026-01-20")
if let Some(cc_data) = cc {
for entry in cc_data {
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
let super::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
@@ -275,7 +272,7 @@ fn merge_monthly(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<MonthStats>) -> Vec<Pe
// Insert ccusage data
if let Some(cc_data) = cc {
for entry in cc_data {
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
let super::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
+2 -15
View File
@@ -1,10 +1,10 @@
//! ccusage CLI integration module
//! Parses Claude Code spending data for economics reporting.
//!
//! Provides isolated interface to ccusage (npm package) for fetching
//! Claude Code API usage metrics. Handles subprocess execution, JSON parsing,
//! and graceful degradation when ccusage is unavailable.
use crate::utils::{resolved_command, tool_exists};
use crate::core::utils::{resolved_command, tool_exists};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::process::Command;
@@ -111,12 +111,6 @@ fn build_command() -> Option<Command> {
None
}
/// Check if ccusage CLI is available (binary or via npx)
#[allow(dead_code)]
pub fn is_available() -> bool {
build_command().is_some()
}
/// Fetch usage data from ccusage for the last 90 days
///
/// Returns `Ok(None)` if ccusage is unavailable (graceful degradation)
@@ -328,11 +322,4 @@ mod tests {
assert_eq!(periods[0].metrics.cache_creation_tokens, 0); // default
assert_eq!(periods[0].metrics.cache_read_tokens, 0);
}
#[test]
fn test_is_available() {
// Just smoke test - actual availability depends on system
let _available = is_available();
// No assertion - just ensure it doesn't panic
}
}
+8 -5
View File
@@ -1,8 +1,11 @@
use crate::display_helpers::{format_duration, print_period_table};
use crate::hook_check;
use crate::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::utils::format_tokens;
//! Shows users how many tokens RTK has saved them over time.
use crate::core::display_helpers::{format_duration, print_period_table};
use crate::core::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::core::utils::format_tokens;
use crate::hooks::hook_check;
use anyhow::{Context, Result};
use chrono::Local;
use colored::Colorize;
use serde::Serialize;
use std::io::IsTerminal;
@@ -228,7 +231,7 @@ pub fn run(
println!("{}", styled("Recent Commands", true)); // added: styled header
println!("──────────────────────────────────────────────────────────");
for rec in recent {
let time = rec.timestamp.format("%m-%d %H:%M");
let time = rec.timestamp.with_timezone(&Local).format("%m-%d %H:%M");
let cmd_short = if rec.rtk_cmd.len() > 25 {
format!("{}...", &rec.rtk_cmd[..22])
} else {
+6
View File
@@ -0,0 +1,6 @@
//! Token savings analytics and cost reporting.
pub mod cc_economics;
pub mod ccusage;
pub mod gain;
pub mod session_cmd;
@@ -1,6 +1,8 @@
//! Compares RTK-routed vs raw commands in a coding session.
use crate::core::utils::format_tokens;
use crate::discover::provider::{ClaudeProvider, ExtractedCommand, SessionProvider};
use crate::discover::registry::{classify_command, split_command_chain, Classification};
use crate::utils::format_tokens;
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
+203
View File
@@ -0,0 +1,203 @@
# Command Filter Modules
## Scope
**Command execution and output filtering.** Every module here calls an external CLI tool (`Command::new("some_tool")`), transforms its stdout/stderr to reduce token consumption, and records savings via `core/tracking`.
Owns: all command-specific filter logic, organized by ecosystem (git, rust, js, python, go, dotnet, cloud, system). Cross-ecosystem routing (e.g., `lint_cmd` detecting Python and delegating to `ruff_cmd`) is an intra-component concern.
Does **not** own: the TOML DSL filter engine (that's `core/toml_filter`), hook interception (that's `hooks/`), or analytics dashboards (that's `analytics/`). This component **writes** to the tracking DB; analytics **reads** from it.
Boundary rule: a module belongs here if and only if it executes an external command and filters its output. Infrastructure that serves multiple modules without calling external commands belongs in `core/`.
## When to Write a Rust Module (vs TOML Filter)
Rust modules exist here because they need capabilities TOML filters don't have: parsing structured output (JSON, NDJSON), state machine parsing across phases, injecting CLI flags (`--format json`), cross-command routing, or **flag-aware filtering** — detecting user-requested verbose flags (e.g., `--nocapture`) and adjusting compression accordingly (see [Design Philosophy](../../CONTRIBUTING.md#design-philosophy) and [TOML vs Rust decision table](../../CONTRIBUTING.md#toml-vs-rust-which-one)).
**Ecosystem placement**: Match the command's language/toolchain. Use `system/` for language-agnostic commands. New ecosystem when 3+ related commands justify it.
For the full contribution checklist (including `discover/rules.rs` registration), see [Adding a New Command Filter](#adding-a-new-command-filter) below.
## Purpose
All command-specific filter modules that execute CLI commands and transform their output to minimize LLM token consumption. Each module follows a consistent pattern: execute the underlying command, filter its output through specialized parsers, track token savings, and propagate exit codes.
## Ecosystems
Each subdirectory has its own README with file descriptions, parsing strategies, and cross-command dependencies.
- **[`git/`](git/README.md)** — git, gh, gt, diff — `trailing_var_arg` parsing, gh markdown filtering, gt passthrough
- **[`rust/`](rust/README.md)** — cargo, runner (err/test) — Cargo sub-enum routing, runner dual-mode
- **[`js/`](js/README.md)** — npm, pnpm, vitest, lint, tsc, next, prettier, playwright, prisma — Package manager auto-detection, lint routing, cross-deps with python
- **[`python/`](python/README.md)** — ruff, pytest, mypy, pip — JSON check vs text format, state machine parsing, uv auto-detection
- **[`go/`](go/README.md)** — go test/build/vet, golangci-lint — NDJSON streaming, Go sub-enum pattern
- **[`dotnet/`](dotnet/README.md)** — dotnet, binlog, trx, format_report — DotnetCommands sub-enum, internal helper modules
- **[`cloud/`](cloud/README.md)** — aws, docker/kubectl, curl, wget, psql — Docker/Kubectl sub-enums, JSON forced output
- **[`system/`](system/README.md)** — ls, tree, read, grep, find, wc, env, json, log, deps, summary, format, smart — format_cmd routing, filter levels, language detection
- **[`ruby/`](ruby/README.md)** — rake/rails test, rspec, rubocop — JSON injection pattern, `ruby_exec()` bundle exec auto-detection
## Execution Flow: `runner::run_filtered()`
The shared wrapper in [`core/runner.rs`](../core/runner.rs) encapsulates the six-phase execution skeleton. Modules build the `Command` (custom arg logic), then delegate to `run_filtered()` for everything else.
```
cmd.output() Filter applied to tee_and_hint()
| stdout or combined |
v | v
+---------+ stdout +-------+-------+ filtered +-------+
| Execute |--------->| filter_fn() |----------->| Print |
+---------+ stderr +---------------+ +-------+
| |
v v
+----------+ +---------+
| raw = | | Track |
| stdout + | | savings |
| stderr | +---------+
+----------+ |
v
+-----------+
| Ok(code) |
| returned |
+-----------+
```
**Six phases in order:**
1. **Execute** — `cmd.output()` captures stdout + stderr
2. **Filter** — `filter_fn` receives stdout-only or combined, returns compressed string
3. **Print** — filtered output printed; if tee enabled, appends recovery hint on failure
4. **Stderr passthrough** — when `filter_stdout_only`: stderr printed via `eprintln!()` unconditionally
5. **Track** — `timer.track()` records raw vs filtered for token savings
6. **Exit code** — returns `Ok(exit_code)` to caller; `main.rs` calls `process::exit(code)` once
**`RunOptions` builder:**
| Constructor | Behavior |
|-------------|----------|
| `RunOptions::default()` | Combined stdout+stderr to filter, no tee |
| `RunOptions::with_tee("label")` | Combined filtering + tee recovery |
| `RunOptions::stdout_only()` | Stdout-only to filter, stderr passthrough, no tee |
| `RunOptions::stdout_only().tee("label")` | Stdout-only + tee recovery |
**Example — filtered command (recommended):**
```rust
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("mycmd");
for arg in args { cmd.arg(arg); }
if verbose > 0 { eprintln!("Running: mycmd {}", args.join(" ")); }
runner::run_filtered(
cmd, "mycmd", &args.join(" "),
filter_mycmd_output,
runner::RunOptions::stdout_only().tee("mycmd"),
)
}
```
Exit code handling is **fully automatic** when using `run_filtered()` — the wrapper extracts the exit code (including Unix signal handling via 128+signal), tracks savings, and returns `Ok(exit_code)`. Module authors just return the result.
**Example — passthrough command (no filtering):**
```rust
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
let status = resolved_command("mycmd").args(args)
.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit())
.status().context("Failed to run mycmd")?;
Ok(exit_code_from_status(&status, "mycmd"))
}
```
**Example — manual execution (custom logic):**
```rust
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let output = resolved_command("mycmd").args(args)
.output().context("Failed to run mycmd")?;
let exit_code = exit_code_from_output(&output, "mycmd");
// ... custom filtering, tracking ...
Ok(exit_code)
}
```
Modules with deviations (subcommand dispatch, parser trait systems, two-command fallback, synthetic output).
## Cross-Command Dependencies
- `lint_cmd` routes to `mypy_cmd` or `ruff_cmd` when detecting Python projects
- `format_cmd` routes to `prettier_cmd` or `ruff_cmd` depending on the formatter detected
- `gh_cmd` imports `compact_diff()` from `git` for diff formatting (markdown helpers are defined in `gh_cmd` itself)
## Cross-Cutting Behavior Contracts
These behaviors must be uniform across all command modules. Full audit details in `docs/ISO_ANALYZE.md`.
### Exit Code Propagation
All module `run()` functions return `Result<i32>` where the `i32` is the underlying command's exit code. `main.rs` calls `std::process::exit(code)` once at the single exit point — **modules never call `process::exit()` directly**.
| Return value | Meaning | Who exits |
|--------------|---------|-----------|
| `Ok(0)` | Command succeeded | `main.rs` exits 0 |
| `Ok(N)` | Command failed with code N | `main.rs` exits N |
| `Err(e)` | RTK itself failed (not the command) | `main.rs` prints error, exits 1 |
**How exit codes are extracted:**
| Execution style | Helper | Signal handling |
|----------------|--------|-----------------|
| `cmd.output()` (filtered) | `exit_code_from_output(&output, "tool")` | 128+signal on Unix |
| `cmd.status()` (passthrough) | `exit_code_from_status(&status, "tool")` | 128+signal on Unix |
| `run_filtered()` (wrapper) | Automatic — no manual code needed | Built-in |
**When using `run_filtered()`**: exit code handling is fully automatic. The wrapper extracts the exit code, handles signals, and returns `Ok(exit_code)`. Module authors just return the wrapper's result — no exit code logic needed.
**When doing manual execution**: use `exit_code_from_output()` or `exit_code_from_status()` and return `Ok(exit_code)`. Never call `process::exit()`, never use `.code().unwrap_or(1)` (loses signal info).
### Filter Failure Passthrough
When filtering fails, fall back to raw output and warn on stderr. Never block the user.
### Tee Recovery
Modules that parse structured output (JSON, NDJSON, state machines) must call `tee::tee_and_hint()` so users can recover full output on failure.
### Stderr Handling
Modules must capture stderr and include it in the raw string passed to `timer.track()`, so token savings reflect total output.
### Tracking Completeness
All modules must call `timer.track()` on every path — success, failure, and fallback. Since modules return `Ok(exit_code)` instead of calling `process::exit()`, tracking always runs before the program exits.
### Verbose Flag
All modules accept `verbose: u8`. Use it to print debug info (command being run, savings %, filter tier). Do not accept and ignore it.
## Adding a New Command Filter
Adding a new filter or command requires changes in multiple places. For TOML-vs-Rust decision criteria, see [CONTRIBUTING.md](../../CONTRIBUTING.md#toml-vs-rust-which-one).
### Rust module (structured output, flag injection, state machines)
1. **Create module** in `src/cmds/<ecosystem>/mycmd_cmd.rs`:
- Write the `filter_mycmd()` function (pure: `&str -> String`, no side effects)
- Write `pub fn run(...) -> Result<i32>` using `runner::run_filtered()` — build the `Command`, choose `RunOptions`, delegate
- Use `RunOptions::stdout_only()` when the filter parses structured stdout (JSON, NDJSON) — stderr would corrupt parsing
- Use `RunOptions::default()` when filtering combined text output
- Add `.tee("label")` when the filter parses structured output (enables raw output recovery on failure)
- **Exit codes**: handled automatically by `run_filtered()` — just return its result
2. **Register module**:
- Ecosystem `mod.rs` files use `automod::dir!()` — any `.rs` file in the directory becomes a public module automatically. No manual `pub mod` needed, but be aware: WIP or helper files will also be exposed. Only commit command-ready modules.
- Add variant to `Commands` enum in `main.rs` with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]`
- Add routing match arm in `main.rs`: `Commands::Mycmd { args } => mycmd_cmd::run(&args, cli.verbose)?,`
3. **Add rewrite pattern** — Entry in `src/discover/rules.rs` (PATTERNS + RULES arrays at matching index) so hooks auto-rewrite the command
4. **Write tests** — Real fixture, snapshot test, token savings >= 60% (see [testing rules](../../.claude/rules/cli-testing.md))
5. **Update docs** — Ecosystem README, CHANGELOG.md
### TOML filter (simple line-based filtering)
1. **Create filter** in [`src/filters/`](../filters/README.md)
2. **Add rewrite pattern** in `src/discover/rules.rs`
3. **Write tests** and **update docs**
+11
View File
@@ -0,0 +1,11 @@
# Cloud and Infrastructure
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
## Specifics
- `aws_cmd.rs` forces `--output json` for structured parsing
- `container.rs` handles both Docker and Kubernetes; `DockerCommands` and `KubectlCommands` sub-enums in `main.rs` route to `container::run()` -- uses passthrough for unknown subcommands
- `curl_cmd.rs` auto-detects JSON responses and shows schema (structure without values)
- `wget_cmd.rs` wraps wget with output filtering
- `psql_cmd.rs` filters PostgreSQL query output
+77 -197
View File
@@ -3,9 +3,12 @@
//! Replaces verbose `--output table`/`text` with JSON, then compresses.
//! Specialized filters for high-frequency commands (STS, S3, EC2, ECS, RDS, CloudFormation).
use crate::core::tracking;
use crate::core::utils::{
exit_code_from_output, exit_code_from_status, join_with_overflow, resolved_command,
truncate_iso_date,
};
use crate::json_cmd;
use crate::tracking;
use crate::utils::{join_with_overflow, resolved_command, truncate_iso_date};
use anyhow::{Context, Result};
use serde_json::Value;
@@ -13,7 +16,7 @@ const MAX_ITEMS: usize = 20;
const JSON_COMPRESS_DEPTH: usize = 4;
/// Run an AWS CLI command with token-optimized output
pub fn run(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
pub fn run(subcommand: &str, args: &[String], verbose: u8) -> Result<i32> {
// Build the full sub-path: e.g. "sts" + ["get-caller-identity"] -> "sts get-caller-identity"
let full_sub = if args.is_empty() {
subcommand.to_string()
@@ -58,7 +61,7 @@ fn is_structured_operation(args: &[String]) -> bool {
}
/// Generic strategy: force --output json for structured ops, compress via json_cmd schema
fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -> Result<()> {
fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("aws");
@@ -95,7 +98,7 @@ fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -
&stderr,
);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "aws"));
}
let filtered = match json_cmd::filter_json_string(&raw, JSON_COMPRESS_DEPTH) {
@@ -117,7 +120,7 @@ fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -
&filtered,
);
Ok(())
Ok(0)
}
fn run_aws_json(
@@ -163,36 +166,36 @@ fn run_aws_json(
Ok((stdout, stderr, output.status))
}
fn run_sts_identity(extra_args: &[String], verbose: u8) -> Result<()> {
fn run_aws_filtered(
sub_args: &[&str],
extra_args: &[String],
verbose: u8,
filter_fn: fn(&str) -> Option<String>,
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) = run_aws_json(&["sts", "get-caller-identity"], extra_args, verbose)?;
let label = format!("aws {}", sub_args.join(" "));
let rtk_label = format!("rtk {}", label);
let (raw, stderr, status) = run_aws_json(sub_args, extra_args, verbose)?;
if !status.success() {
timer.track(
"aws sts get-caller-identity",
"rtk aws sts get-caller-identity",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
timer.track(&label, &rtk_label, &stderr, &stderr);
return Ok(exit_code_from_status(&status, "aws"));
}
let filtered = match filter_sts_identity(&raw) {
Some(f) => f,
None => raw.clone(),
};
let filtered = filter_fn(&raw).unwrap_or_else(|| raw.clone());
println!("{}", filtered);
timer.track(
"aws sts get-caller-identity",
"rtk aws sts get-caller-identity",
&raw,
&filtered,
);
Ok(())
timer.track(&label, &rtk_label, &raw, &filtered);
Ok(0)
}
fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<()> {
fn run_sts_identity(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["sts", "get-caller-identity"],
extra_args,
verbose,
filter_sts_identity,
)
}
fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// s3 ls doesn't support --output json, run as-is and filter text
@@ -213,191 +216,68 @@ fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("aws s3 ls", "rtk aws s3 ls", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "aws"));
}
let filtered = filter_s3_ls(&raw);
println!("{}", filtered);
timer.track("aws s3 ls", "rtk aws s3 ls", &raw, &filtered);
Ok(())
Ok(0)
}
fn run_ec2_describe(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) = run_aws_json(&["ec2", "describe-instances"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws ec2 describe-instances",
"rtk aws ec2 describe-instances",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_ec2_instances(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws ec2 describe-instances",
"rtk aws ec2 describe-instances",
&raw,
&filtered,
);
Ok(())
fn run_ec2_describe(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["ec2", "describe-instances"],
extra_args,
verbose,
filter_ec2_instances,
)
}
fn run_ecs_list_services(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) = run_aws_json(&["ecs", "list-services"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws ecs list-services",
"rtk aws ecs list-services",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_ecs_list_services(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws ecs list-services",
"rtk aws ecs list-services",
&raw,
&filtered,
);
Ok(())
fn run_ecs_list_services(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["ecs", "list-services"],
extra_args,
verbose,
filter_ecs_list_services,
)
}
fn run_ecs_describe_services(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) = run_aws_json(&["ecs", "describe-services"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws ecs describe-services",
"rtk aws ecs describe-services",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_ecs_describe_services(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws ecs describe-services",
"rtk aws ecs describe-services",
&raw,
&filtered,
);
Ok(())
fn run_ecs_describe_services(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["ecs", "describe-services"],
extra_args,
verbose,
filter_ecs_describe_services,
)
}
fn run_rds_describe(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) =
run_aws_json(&["rds", "describe-db-instances"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws rds describe-db-instances",
"rtk aws rds describe-db-instances",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_rds_instances(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws rds describe-db-instances",
"rtk aws rds describe-db-instances",
&raw,
&filtered,
);
Ok(())
fn run_rds_describe(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["rds", "describe-db-instances"],
extra_args,
verbose,
filter_rds_instances,
)
}
fn run_cfn_list_stacks(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) =
run_aws_json(&["cloudformation", "list-stacks"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws cloudformation list-stacks",
"rtk aws cloudformation list-stacks",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_cfn_list_stacks(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws cloudformation list-stacks",
"rtk aws cloudformation list-stacks",
&raw,
&filtered,
);
Ok(())
fn run_cfn_list_stacks(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["cloudformation", "list-stacks"],
extra_args,
verbose,
filter_cfn_list_stacks,
)
}
fn run_cfn_describe_stacks(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let (raw, stderr, status) =
run_aws_json(&["cloudformation", "describe-stacks"], extra_args, verbose)?;
if !status.success() {
timer.track(
"aws cloudformation describe-stacks",
"rtk aws cloudformation describe-stacks",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = match filter_cfn_describe_stacks(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(
"aws cloudformation describe-stacks",
"rtk aws cloudformation describe-stacks",
&raw,
&filtered,
);
Ok(())
fn run_cfn_describe_stacks(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["cloudformation", "describe-stacks"],
extra_args,
verbose,
filter_cfn_describe_stacks,
)
}
// --- Filter functions (all use serde_json::Value for resilience) ---
+128 -281
View File
@@ -1,7 +1,12 @@
use crate::tracking;
use crate::utils::resolved_command;
//! Filters Docker and kubectl output into compact summaries.
use crate::core::runner::{self, RunOptions};
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, resolved_command};
use anyhow::{Context, Result};
use serde_json::Value;
use std::ffi::OsString;
use std::process::Command;
#[derive(Debug, Clone, Copy)]
pub enum ContainerCmd {
@@ -13,7 +18,7 @@ pub enum ContainerCmd {
KubectlLogs,
}
pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<()> {
pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<i32> {
match cmd {
ContainerCmd::DockerPs => docker_ps(verbose),
ContainerCmd::DockerImages => docker_images(verbose),
@@ -24,7 +29,28 @@ pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<()> {
}
}
fn docker_ps(_verbose: u8) -> Result<()> {
fn run_kubectl_json<F>(cmd: Command, label: &str, filter_fn: F) -> Result<i32>
where
F: Fn(&Value) -> String,
{
runner::run_filtered(
cmd,
"kubectl",
label,
|stdout| match serde_json::from_str::<Value>(stdout) {
Ok(json) => filter_fn(&json),
Err(e) => {
eprintln!("[rtk] kubectl: JSON parse failed: {}", e);
stdout.to_string()
}
},
RunOptions::stdout_only()
.early_exit_on_failure()
.no_trailing_newline(),
)
}
fn docker_ps(_verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let raw = resolved_command("docker")
@@ -46,7 +72,7 @@ fn docker_ps(_verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker ps", "rtk docker ps", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "docker"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -56,7 +82,7 @@ fn docker_ps(_verbose: u8) -> Result<()> {
rtk.push_str("[docker] 0 containers");
println!("{}", rtk);
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
return Ok(());
return Ok(0);
}
let count = stdout.lines().count();
@@ -90,10 +116,10 @@ fn docker_ps(_verbose: u8) -> Result<()> {
print!("{}", rtk);
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
Ok(())
Ok(0)
}
fn docker_images(_verbose: u8) -> Result<()> {
fn docker_images(_verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let raw = resolved_command("docker")
@@ -111,7 +137,7 @@ fn docker_images(_verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker images", "rtk docker images", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "docker"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -122,7 +148,7 @@ fn docker_images(_verbose: u8) -> Result<()> {
rtk.push_str("[docker] 0 images");
println!("{}", rtk);
timer.track("docker images", "rtk docker images", &raw, &rtk);
return Ok(());
return Ok(0);
}
let mut total_size_mb: f64 = 0.0;
@@ -171,89 +197,47 @@ fn docker_images(_verbose: u8) -> Result<()> {
print!("{}", rtk);
timer.track("docker images", "rtk docker images", &raw, &rtk);
Ok(())
Ok(0)
}
fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
fn docker_logs(args: &[String], _verbose: u8) -> Result<i32> {
let container = args.first().map(|s| s.as_str()).unwrap_or("");
if container.is_empty() {
println!("Usage: rtk docker logs <container>");
return Ok(());
return Ok(0);
}
let output = resolved_command("docker")
.args(["logs", "--tail", "100", container])
.output()
.context("Failed to run docker logs")?;
let mut cmd = resolved_command("docker");
cmd.args(["logs", "--tail", "100", container]);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("docker logs {}", container),
"rtk docker logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("[docker] Logs for {}:\n{}", container, analyzed);
println!("{}", rtk);
timer.track(
&format!("docker logs {}", container),
"rtk docker logs",
&raw,
&rtk,
);
Ok(())
let label = format!("logs {}", container);
runner::run_filtered(
cmd,
"docker",
&label,
|raw| {
format!(
"[docker] Logs for {}:\n{}",
container,
crate::log_cmd::run_stdin_str(raw)
)
},
RunOptions::default().early_exit_on_failure(),
)
}
fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
fn kubectl_pods(args: &[String], _verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("kubectl");
cmd.args(["get", "pods", "-o", "json"]);
for arg in args {
cmd.arg(arg);
}
run_kubectl_json(cmd, "get pods", format_kubectl_pods)
}
let output = cmd.output().context("Failed to run kubectl get pods")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
rtk.push_str("No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
}
};
fn format_kubectl_pods(json: &Value) -> String {
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
return "No pods found\n".to_string();
};
let (mut running, mut pending, mut failed, mut restarts_total) = (0, 0, 0, 0i64);
let mut issues: Vec<String> = Vec::new();
@@ -308,61 +292,33 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
parts.push(format!("{} restarts", restarts_total));
}
rtk.push_str(&format!("{} pods: {}\n", pods.len(), parts.join(", ")));
let mut out = format!("{} pods: {}\n", pods.len(), parts.join(", "));
if !issues.is_empty() {
rtk.push_str("[warn] Issues:\n");
out.push_str("[warn] Issues:\n");
for issue in issues.iter().take(10) {
rtk.push_str(&format!(" {}\n", issue));
out.push_str(&format!(" {}\n", issue));
}
if issues.len() > 10 {
rtk.push_str(&format!(" ... +{} more", issues.len() - 10));
out.push_str(&format!(" ... +{} more", issues.len() - 10));
}
}
print!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
Ok(())
out
}
fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
fn kubectl_services(args: &[String], _verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("kubectl");
cmd.args(["get", "services", "-o", "json"]);
for arg in args {
cmd.arg(arg);
}
run_kubectl_json(cmd, "get services", format_kubectl_services)
}
let output = cmd.output().context("Failed to run kubectl get services")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
rtk.push_str("No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
}
};
fn format_kubectl_services(json: &Value) -> String {
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
return "No services found\n".to_string();
};
rtk.push_str(&format!("{} services:\n", services.len()));
let mut out = format!("{} services:\n", services.len());
for svc in services.iter().take(15) {
let ns = svc["metadata"]["namespace"].as_str().unwrap_or("-");
@@ -387,7 +343,7 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
.collect()
})
.unwrap_or_default();
rtk.push_str(&format!(
out.push_str(&format!(
" {}/{} {} [{}]\n",
ns,
name,
@@ -396,21 +352,16 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
));
}
if services.len() > 15 {
rtk.push_str(&format!(" ... +{} more", services.len() - 15));
out.push_str(&format!(" ... +{} more", services.len() - 15));
}
print!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
Ok(())
out
}
fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
fn kubectl_logs(args: &[String], _verbose: u8) -> Result<i32> {
let pod = args.first().map(|s| s.as_str()).unwrap_or("");
if pod.is_empty() {
println!("Usage: rtk kubectl logs <pod>");
return Ok(());
return Ok(0);
}
let mut cmd = resolved_command("kubectl");
@@ -419,33 +370,20 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run kubectl logs")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("kubectl logs {}", pod),
"rtk kubectl logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("Logs for {}:\n{}", pod, analyzed);
println!("{}", rtk);
timer.track(
&format!("kubectl logs {}", pod),
"rtk kubectl logs",
&raw,
&rtk,
);
Ok(())
let label = format!("logs {}", pod);
runner::run_filtered(
cmd,
"kubectl",
&label,
|stdout| {
format!(
"Logs for {}:\n{}",
pod,
crate::log_cmd::run_stdin_str(stdout)
)
},
RunOptions::stdout_only().early_exit_on_failure(),
)
}
/// Format `docker compose ps --format` output into compact form.
@@ -585,32 +523,12 @@ fn compact_ports(ports: &str) -> String {
}
}
/// Runs an unsupported docker subcommand by passing it through directly
pub fn run_docker_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("docker passthrough: {:?}", args);
}
let status = resolved_command("docker")
.args(args)
.status()
.context("Failed to run docker")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("docker {}", args_str),
&format!("rtk docker {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
pub fn run_docker_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
crate::core::runner::run_passthrough("docker", args, verbose)
}
/// Run `docker compose ps` with compact output
pub fn run_compose_ps(verbose: u8) -> Result<()> {
pub fn run_compose_ps(verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Raw output for token tracking
@@ -622,7 +540,7 @@ pub fn run_compose_ps(verbose: u8) -> Result<()> {
if !raw_output.status.success() {
let stderr = String::from_utf8_lossy(&raw_output.stderr);
eprintln!("{}", stderr);
std::process::exit(raw_output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&raw_output, "docker"));
}
let raw = String::from_utf8_lossy(&raw_output.stdout).to_string();
@@ -640,7 +558,7 @@ pub fn run_compose_ps(verbose: u8) -> Result<()> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "docker"));
}
let structured = String::from_utf8_lossy(&output.stdout).to_string();
@@ -651,132 +569,61 @@ pub fn run_compose_ps(verbose: u8) -> Result<()> {
let rtk = format_compose_ps(&structured);
println!("{}", rtk);
timer.track("docker compose ps", "rtk docker compose ps", &raw, &rtk);
Ok(())
Ok(0)
}
/// Run `docker compose logs` with deduplication
pub fn run_compose_logs(service: Option<&str>, verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run_compose_logs(service: Option<&str>, verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("docker");
cmd.args(["compose", "logs", "--tail", "100"]);
if let Some(svc) = service {
cmd.arg(svc);
}
let output = cmd.output().context("Failed to run docker compose logs")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if verbose > 0 {
eprintln!("raw docker compose logs:\n{}", raw);
}
let rtk = format_compose_logs(&raw);
println!("{}", rtk);
let svc_label = service.unwrap_or("all");
timer.track(
&format!("docker compose logs {}", svc_label),
"rtk docker compose logs",
&raw,
&rtk,
);
Ok(())
runner::run_filtered(
cmd,
"docker",
&format!("compose logs {}", svc_label),
|raw| {
if verbose > 0 {
eprintln!("raw docker compose logs:\n{}", raw);
}
format_compose_logs(raw)
},
RunOptions::default().early_exit_on_failure(),
)
}
/// Run `docker compose build` with summary output
pub fn run_compose_build(service: Option<&str>, verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run_compose_build(service: Option<&str>, verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("docker");
cmd.args(["compose", "build"]);
if let Some(svc) = service {
cmd.arg(svc);
}
let output = cmd.output().context("Failed to run docker compose build")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if verbose > 0 {
eprintln!("raw docker compose build:\n{}", raw);
}
let rtk = format_compose_build(&raw);
println!("{}", rtk);
let svc_label = service.unwrap_or("all");
timer.track(
&format!("docker compose build {}", svc_label),
"rtk docker compose build",
&raw,
&rtk,
);
Ok(())
runner::run_filtered(
cmd,
"docker",
&format!("compose build {}", svc_label),
|raw| {
if verbose > 0 {
eprintln!("raw docker compose build:\n{}", raw);
}
format_compose_build(raw)
},
RunOptions::default().early_exit_on_failure(),
)
}
/// Runs an unsupported docker compose subcommand by passing it through directly
pub fn run_compose_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("docker compose passthrough: {:?}", args);
}
let status = resolved_command("docker")
.arg("compose")
.args(args)
.status()
.context("Failed to run docker compose")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("docker compose {}", args_str),
&format!("rtk docker compose {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
pub fn run_compose_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
let mut combined = vec![OsString::from("compose")];
combined.extend_from_slice(args);
crate::core::runner::run_passthrough("docker", &combined, verbose)
}
/// Runs an unsupported kubectl subcommand by passing it through directly
pub fn run_kubectl_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("kubectl passthrough: {:?}", args);
}
let status = resolved_command("kubectl")
.args(args)
.status()
.context("Failed to run kubectl")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("kubectl {}", args_str),
&format!("rtk kubectl {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
pub fn run_kubectl_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
crate::core::runner::run_passthrough("kubectl", args, verbose)
}
#[cfg(test)]
+10 -5
View File
@@ -1,9 +1,13 @@
//! Runs curl and auto-compresses JSON responses.
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, resolved_command, truncate};
use crate::json_cmd;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
pub fn run(args: &[String], verbose: u8) -> Result<()> {
/// Not using run_filtered: on failure, curl can return HTML error pages (404, 500)
/// that the JSON schema filter would mangle. The early exit skips filtering entirely.
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("curl");
cmd.arg("-s"); // Silent mode (no progress bar)
@@ -20,6 +24,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
// Early exit: don't feed HTTP error bodies (HTML 404 etc.) through JSON schema filter
if !output.status.success() {
let msg = if stderr.trim().is_empty() {
stdout.trim().to_string()
@@ -27,7 +32,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
stderr.trim().to_string()
};
eprintln!("FAILED: curl {}", msg);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "curl"));
}
let raw = stdout.to_string();
@@ -43,7 +48,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
Ok(())
Ok(0)
}
fn filter_curl_output(output: &str) -> String {
+1
View File
@@ -0,0 +1 @@
automod::dir!(pub "src/cmds/cloud");
+17 -38
View File
@@ -3,9 +3,9 @@
//! Detects table and expanded display formats, strips borders/padding,
//! and produces compact tab-separated or key=value output.
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
use crate::core::runner::{self, RunOptions};
use crate::core::utils::resolved_command;
use anyhow::Result;
use lazy_static::lazy_static;
use regex::Regex;
@@ -19,9 +19,11 @@ lazy_static! {
static ref RECORD_HEADER: Regex = Regex::new(r"^-\[ RECORD (\d+) \]-").unwrap();
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Edge cases vs previous manual implementation:
// - On failure: stderr is no longer eprinted on the success path (only on failure via early_exit)
// - On success: tracking raw includes stderr (previously stdout-only, but stderr is empty on success)
// - Tee hint uses merged stdout+stderr as raw (was stdout-only)
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("psql");
for arg in args {
cmd.arg(arg);
@@ -31,38 +33,15 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: psql {}", args.join(" "));
}
let output = cmd
.output()
.context("Failed to run psql (is PostgreSQL client installed?)")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let exit_code = output.status.code().unwrap_or(1);
if !stderr.is_empty() {
eprint!("{}", stderr);
}
if exit_code != 0 {
std::process::exit(exit_code);
}
let filtered = filter_psql_output(&stdout);
if let Some(hint) = crate::tee::tee_and_hint(&stdout, "psql", exit_code) {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
}
timer.track(
&format!("psql {}", args.join(" ")),
&format!("rtk psql {}", args.join(" ")),
&stdout,
&filtered,
);
Ok(())
runner::run_filtered(
cmd,
"psql",
&args.join(" "),
filter_psql_output,
RunOptions::stdout_only()
.tee("psql")
.early_exit_on_failure(),
)
}
fn filter_psql_output(output: &str) -> String {
+119 -8
View File
@@ -1,9 +1,9 @@
use crate::tracking;
use crate::utils::resolved_command;
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, resolved_command};
use anyhow::{Context, Result};
/// Compact wget - strips progress bars, shows only result
pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
pub fn run(url: &str, args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -45,14 +45,14 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
let msg = format!("{} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "wget"));
}
Ok(())
Ok(0)
}
/// Run wget and output to stdout (for piping)
pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -108,10 +108,10 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
let msg = format!("{} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "wget"));
}
Ok(())
Ok(0)
}
fn extract_filename_from_output(stderr: &str, url: &str, args: &[String]) -> String {
@@ -261,3 +261,114 @@ fn truncate_line(line: &str, max: usize) -> String {
format!("{}...", t)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compact_url_strips_protocol() {
assert_eq!(compact_url("https://example.com/file.zip"), "example.com/file.zip");
assert_eq!(compact_url("http://example.com/file.zip"), "example.com/file.zip");
}
#[test]
fn test_compact_url_truncates_long_url() {
let long = "https://example.com/very/long/path/that/exceeds/fifty/characters/file.zip";
let result = compact_url(long);
assert!(result.contains("..."), "Long URL should be truncated with ...");
assert!(result.len() < long.len());
}
#[test]
fn test_compact_url_short_unchanged() {
let short = "https://x.com/f";
assert_eq!(compact_url(short), "x.com/f");
}
#[test]
fn test_format_size_zero() {
assert_eq!(format_size(0), "?");
}
#[test]
fn test_format_size_bytes() {
assert_eq!(format_size(512), "512B");
}
#[test]
fn test_format_size_kilobytes() {
let result = format_size(2048);
assert!(result.ends_with("KB"), "Expected KB, got {}", result);
}
#[test]
fn test_format_size_megabytes() {
let result = format_size(2 * 1024 * 1024);
assert!(result.ends_with("MB"), "Expected MB, got {}", result);
}
#[test]
fn test_parse_error_404() {
assert_eq!(parse_error("HTTP request failed: 404", ""), "404 Not Found");
}
#[test]
fn test_parse_error_dns() {
assert_eq!(
parse_error("unable to resolve host example.com", ""),
"DNS lookup failed"
);
}
#[test]
fn test_parse_error_ssl() {
assert_eq!(
parse_error("SSL certificate verification failed", ""),
"SSL/TLS error"
);
}
#[test]
fn test_parse_error_unknown() {
assert_eq!(parse_error("", ""), "Unknown error");
}
#[test]
fn test_truncate_line_short() {
assert_eq!(truncate_line("hello", 10), "hello");
}
#[test]
fn test_truncate_line_exact() {
assert_eq!(truncate_line("hello", 5), "hello");
}
#[test]
fn test_truncate_line_long() {
let result = truncate_line("hello world this is long", 10);
assert!(result.ends_with("..."));
assert!(result.len() <= 10);
}
#[test]
fn test_extract_filename_from_output_flag() {
let args = vec!["-O".to_string(), "myfile.zip".to_string()];
assert_eq!(
extract_filename_from_output("", "https://example.com/x", &args),
"myfile.zip"
);
}
#[test]
fn test_extract_filename_from_url_fallback() {
let result = extract_filename_from_output("", "https://example.com/file.tar.gz", &[]);
assert_eq!(result, "file.tar.gz");
}
#[test]
fn test_extract_filename_empty_url_fallback() {
let result = extract_filename_from_output("", "https://example.com/", &[]);
assert_eq!(result, "index.html");
}
}
+9
View File
@@ -0,0 +1,9 @@
# .NET Ecosystem
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
## Specifics
- `dotnet_cmd.rs` uses `DotnetCommands` sub-enum in main.rs
- Internal helper modules (`dotnet_trx.rs`, `dotnet_format_report.rs`, `binlog.rs`) are only used by `dotnet_cmd.rs` -- they parse specialized .NET output formats (TRX XML, binary logs, format reports)
- Test fixtures are in `tests/fixtures/dotnet/` (JSON and text formats)
+5 -3
View File
@@ -1,4 +1,6 @@
use crate::utils::strip_ansi;
//! Reads MSBuild binary log files and extracts errors and test results.
use crate::core::utils::strip_ansi;
use anyhow::{Context, Result};
use flate2::read::GzDecoder;
use lazy_static::lazy_static;
@@ -1535,7 +1537,7 @@ Restore failed with 1 error(s) in 1.0s
#[test]
fn test_parse_build_from_fixture_text() {
let input = include_str!("../tests/fixtures/dotnet/build_failed.txt");
let input = include_str!("../../../tests/fixtures/dotnet/build_failed.txt");
let summary = parse_build_from_text(input);
assert_eq!(summary.errors.len(), 1);
@@ -1571,7 +1573,7 @@ Time Elapsed 00:00:00.12
#[test]
fn test_parse_test_from_fixture_text() {
let input = include_str!("../tests/fixtures/dotnet/test_failed.txt");
let input = include_str!("../../../tests/fixtures/dotnet/test_failed.txt");
let summary = parse_test_from_text(input);
assert_eq!(summary.failed, 1);
@@ -1,8 +1,10 @@
//! Filters dotnet CLI output — build, test, and format results.
use crate::binlog;
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, resolved_command, truncate};
use crate::dotnet_format_report;
use crate::dotnet_trx;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
use quick_xml::events::Event;
use quick_xml::Reader;
@@ -16,19 +18,19 @@ const DOTNET_CLI_UI_LANGUAGE: &str = "DOTNET_CLI_UI_LANGUAGE";
const DOTNET_CLI_UI_LANGUAGE_VALUE: &str = "en-US";
static TEMP_PATH_COUNTER: AtomicU64 = AtomicU64::new(0);
pub fn run_build(args: &[String], verbose: u8) -> Result<()> {
pub fn run_build(args: &[String], verbose: u8) -> Result<i32> {
run_dotnet_with_binlog("build", args, verbose)
}
pub fn run_test(args: &[String], verbose: u8) -> Result<()> {
pub fn run_test(args: &[String], verbose: u8) -> Result<i32> {
run_dotnet_with_binlog("test", args, verbose)
}
pub fn run_restore(args: &[String], verbose: u8) -> Result<()> {
pub fn run_restore(args: &[String], verbose: u8) -> Result<i32> {
run_dotnet_with_binlog("restore", args, verbose)
}
pub fn run_format(args: &[String], verbose: u8) -> Result<()> {
pub fn run_format(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let (report_path, cleanup_report_path) = resolve_format_report_path(args);
let mut cmd = resolved_command("dotnet");
@@ -67,14 +69,10 @@ pub fn run_format(args: &[String], verbose: u8) -> Result<()> {
}
}
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
Ok(exit_code_from_output(&output, "dotnet"))
}
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
if args.is_empty() {
anyhow::bail!("dotnet: no subcommand specified");
}
@@ -111,14 +109,10 @@ pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
&raw,
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
Ok(exit_code_from_output(&output, "dotnet"))
}
fn run_dotnet_with_binlog(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
fn run_dotnet_with_binlog(subcommand: &str, args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let binlog_path = build_binlog_path(subcommand);
let should_expect_binlog = subcommand != "test" || has_binlog_arg(args);
@@ -259,11 +253,7 @@ fn run_dotnet_with_binlog(subcommand: &str, args: &[String], verbose: u8) -> Res
eprintln!("Binlog cleaned up: {}", binlog_path.display());
}
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
Ok(exit_code_from_output(&output, "dotnet"))
}
fn build_binlog_path(subcommand: &str) -> PathBuf {
@@ -1,3 +1,5 @@
//! Parses dotnet format JSON reports into compact summaries.
use anyhow::{Context, Result};
use serde::Deserialize;
use std::fs::File;
@@ -1,3 +1,5 @@
//! Parses .trx test result files (Visual Studio XML format) into compact summaries.
use crate::binlog::{FailedTest, TestSummary};
use chrono::{DateTime, FixedOffset};
use quick_xml::events::{BytesStart, Event};
+1
View File
@@ -0,0 +1 @@
automod::dir!(pub "src/cmds/dotnet");
+15
View File
@@ -0,0 +1,15 @@
# Git and VCS
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
## Specifics
- **git.rs** uses `trailing_var_arg = true` + `allow_hyphen_values = true` so native git flags (`--oneline`, `--cached`, etc.) pass through correctly
- Auto-detects `--merges` flag to avoid conflicting with `--no-merges` injection
- Global git options (`-C`, `--git-dir`, `--work-tree`, `--no-pager`) are prepended before the subcommand
- Exit code propagation is critical for CI/CD pipelines
## Cross-command
- `gh_cmd.rs` imports `compact_diff()` from `git.rs` for diff formatting; markdown helpers (`filter_markdown_body`, `filter_markdown_segment`) are defined in `gh_cmd.rs` itself
- `diff_cmd.rs` is a standalone ultra-condensed diff (separate from `git diff`)
+3 -1
View File
@@ -1,4 +1,6 @@
use crate::tracking;
//! Compares two files and shows only the changed lines.
use crate::core::tracking;
use anyhow::Result;
use std::fs;
use std::path::Path;
File diff suppressed because it is too large. Load diff
+62 -60
View File
@@ -1,6 +1,9 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
//! Filters git output — log, status, diff, and more — keeping just the essential info.
use crate::core::config;
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, exit_code_from_status, resolved_command};
use std::process::Stdio;
use anyhow::{Context, Result};
use std::ffi::OsString;
use std::process::Command;
@@ -37,7 +40,7 @@ pub fn run(
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<()> {
) -> Result<i32> {
match cmd {
GitCommand::Diff => run_diff(args, max_lines, verbose, global_args),
GitCommand::Log => run_log(args, max_lines, verbose, global_args),
@@ -61,7 +64,7 @@ fn run_diff(
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<()> {
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Check if user wants stat output
@@ -88,7 +91,7 @@ fn run_diff(
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -101,7 +104,7 @@ fn run_diff(
&stdout,
);
return Ok(());
return Ok(0);
}
// Default RTK behavior: stat first, then compacted diff
@@ -127,7 +130,7 @@ fn run_diff(
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
if verbose > 0 {
@@ -163,7 +166,7 @@ fn run_diff(
&final_output,
);
Ok(())
Ok(0)
}
fn run_show(
@@ -171,7 +174,7 @@ fn run_show(
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<()> {
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// If user wants --stat or --format only, pass through
@@ -197,7 +200,7 @@ fn run_show(
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
if wants_blob_show {
@@ -213,7 +216,7 @@ fn run_show(
&stdout,
);
return Ok(());
return Ok(0);
}
// Get raw output for tracking
@@ -237,7 +240,7 @@ fn run_show(
if !summary_output.status.success() {
let stderr = String::from_utf8_lossy(&summary_output.stderr);
eprintln!("{}", stderr);
std::process::exit(summary_output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&summary_output, "git"));
}
let summary = String::from_utf8_lossy(&summary_output.stdout);
println!("{}", summary.trim());
@@ -282,7 +285,7 @@ fn run_show(
&final_output,
);
Ok(())
Ok(0)
}
fn is_blob_show_arg(arg: &str) -> bool {
@@ -384,7 +387,7 @@ fn run_log(
_max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<()> {
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = git_cmd(global_args);
@@ -442,8 +445,7 @@ fn run_log(
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("{}", stderr);
// Propagate git's exit code
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -463,7 +465,7 @@ fn run_log(
&filtered,
);
Ok(())
Ok(0)
}
/// Filter git log output: truncate long messages, cap lines
@@ -738,7 +740,7 @@ fn filter_status_with_args(output: &str) -> String {
}
}
fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// If user provided flags, apply minimal filtering
@@ -763,7 +765,7 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
if verbose > 0 || !stderr.is_empty() {
@@ -781,7 +783,7 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
&filtered,
);
return Ok(());
return Ok(0);
}
// Default RTK compact mode (no args provided)
@@ -804,7 +806,7 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let message = "Not a git repository".to_string();
eprintln!("{}", message);
timer.track("git status", "rtk git status", &raw_output, &message);
std::process::exit(output.status.code().unwrap_or(128));
return Ok(exit_code_from_output(&output, "git"));
}
let formatted = format_status_output(&stdout);
@@ -814,10 +816,10 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
// Track for statistics
timer.track("git status", "rtk git status", &raw_output, &formatted);
Ok(())
Ok(0)
}
fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = git_cmd(global_args);
@@ -882,11 +884,10 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
}
// Propagate git's exit code
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
Ok(())
Ok(0)
}
fn build_commit_command(args: &[String], global_args: &[String]) -> Command {
@@ -898,7 +899,7 @@ fn build_commit_command(args: &[String], global_args: &[String]) -> Command {
cmd
}
fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let original_cmd = format!("git commit {}", args.join(" "));
@@ -908,6 +909,7 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
}
let output = build_commit_command(args, global_args)
.stdin(Stdio::inherit())
.output()
.context("Failed to run git commit")?;
@@ -952,14 +954,14 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
eprint!("{}", stdout);
}
timer.track(&original_cmd, "rtk git commit", &raw_output, &raw_output);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
}
Ok(())
Ok(0)
}
fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -972,7 +974,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run git push")?;
let output = cmd.stdin(Stdio::inherit()).output().context("Failed to run git push")?;
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -1015,13 +1017,13 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
Ok(())
Ok(0)
}
fn run_pull(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_pull(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1101,13 +1103,13 @@ fn run_pull(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
Ok(())
Ok(0)
}
fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1181,9 +1183,9 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
return Ok(());
return Ok(0);
}
// Write operation: action flags, or positional args without list flags (= branch creation)
@@ -1221,9 +1223,9 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
return Ok(());
return Ok(0);
}
// List mode: show compact branch list
@@ -1252,7 +1254,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
let filtered = filter_branch_output(&stdout);
@@ -1265,7 +1267,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
&filtered,
);
Ok(())
Ok(0)
}
fn filter_branch_output(output: &str) -> String {
@@ -1322,7 +1324,7 @@ fn filter_branch_output(output: &str) -> String {
result.join("\n")
}
fn run_fetch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_fetch(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1345,7 +1347,7 @@ fn run_fetch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
// Count new refs from stderr (git fetch outputs to stderr)
@@ -1363,7 +1365,7 @@ fn run_fetch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
println!("{}", msg);
timer.track("git fetch", "rtk git fetch", &raw, &msg);
Ok(())
Ok(0)
}
fn run_stash(
@@ -1371,7 +1373,7 @@ fn run_stash(
args: &[String],
verbose: u8,
global_args: &[String],
) -> Result<()> {
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1391,7 +1393,7 @@ fn run_stash(
let msg = "No stashes";
println!("{}", msg);
timer.track("git stash list", "rtk git stash list", &raw, msg);
return Ok(());
return Ok(0);
}
let filtered = filter_stash_list(&stdout);
@@ -1452,7 +1454,7 @@ fn run_stash(
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
}
Some(sub) => {
@@ -1487,7 +1489,7 @@ fn run_stash(
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
}
None => {
@@ -1523,12 +1525,12 @@ fn run_stash(
timer.track("git stash", "rtk git stash", &combined, &msg);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
}
}
Ok(())
Ok(0)
}
fn filter_stash_list(output: &str) -> String {
@@ -1552,7 +1554,7 @@ fn filter_stash_list(output: &str) -> String {
result.join("\n")
}
fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1595,9 +1597,9 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
}
std::process::exit(output.status.code().unwrap_or(1));
return Ok(exit_code_from_output(&output, "git"));
}
return Ok(());
return Ok(0);
}
// Default: list mode
@@ -1613,7 +1615,7 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
println!("{}", filtered);
timer.track("git worktree list", "rtk git worktree", &raw, &filtered);
Ok(())
Ok(0)
}
fn filter_worktree_list(output: &str) -> String {
@@ -1644,7 +1646,7 @@ fn filter_worktree_list(output: &str) -> String {
}
/// Runs an unsupported git subcommand by passing it through directly
pub fn run_passthrough(args: &[OsString], global_args: &[String], verbose: u8) -> Result<()> {
pub fn run_passthrough(args: &[OsString], global_args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -1662,9 +1664,9 @@ pub fn run_passthrough(args: &[OsString], global_args: &[String], verbose: u8) -
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
return Ok(exit_code_from_status(&status, "git"));
}
Ok(())
Ok(0)
}
#[cfg(test)]
+21 -49
View File
@@ -1,5 +1,9 @@
use crate::tracking;
use crate::utils::{ok_confirmation, resolved_command, strip_ansi, truncate};
//! Filters Graphite (gt) CLI output for stacking workflows.
use crate::core::tracking;
use crate::core::utils::{
exit_code_from_output, ok_confirmation, resolved_command, strip_ansi, truncate,
};
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
@@ -23,7 +27,7 @@ fn run_gt_filtered(
verbose: u8,
tee_label: &str,
filter_fn: fn(&str) -> String,
) -> Result<()> {
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("gt");
@@ -50,7 +54,7 @@ fn run_gt_filtered(
let stderr = String::from_utf8_lossy(&cmd_output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = cmd_output.status.code().unwrap_or(1);
let exit_code = exit_code_from_output(&cmd_output, "gt");
let clean = strip_ansi(stdout.trim());
let output = if verbose > 0 {
@@ -59,7 +63,7 @@ fn run_gt_filtered(
filter_fn(&clean)
};
if let Some(hint) = crate::tee::tee_and_hint(&raw, tee_label, exit_code) {
if let Some(hint) = crate::core::tee::tee_and_hint(&raw, tee_label, exit_code) {
println!("{}\n{}", output, hint);
} else {
println!("{}", output);
@@ -77,18 +81,14 @@ fn run_gt_filtered(
let rtk_label = format!("rtk {}", label);
timer.track(&label, &rtk_label, &raw, &output);
if !cmd_output.status.success() {
std::process::exit(exit_code);
}
Ok(())
Ok(exit_code)
}
fn filter_identity(input: &str) -> String {
input.to_string()
}
pub fn run_log(args: &[String], verbose: u8) -> Result<()> {
pub fn run_log(args: &[String], verbose: u8) -> Result<i32> {
match args.first().map(|s| s.as_str()) {
Some("short") => run_gt_filtered(
&["log", "short"],
@@ -108,27 +108,27 @@ pub fn run_log(args: &[String], verbose: u8) -> Result<()> {
}
}
pub fn run_submit(args: &[String], verbose: u8) -> Result<()> {
pub fn run_submit(args: &[String], verbose: u8) -> Result<i32> {
run_gt_filtered(&["submit"], args, verbose, "gt_submit", filter_gt_submit)
}
pub fn run_sync(args: &[String], verbose: u8) -> Result<()> {
pub fn run_sync(args: &[String], verbose: u8) -> Result<i32> {
run_gt_filtered(&["sync"], args, verbose, "gt_sync", filter_gt_sync)
}
pub fn run_restack(args: &[String], verbose: u8) -> Result<()> {
pub fn run_restack(args: &[String], verbose: u8) -> Result<i32> {
run_gt_filtered(&["restack"], args, verbose, "gt_restack", filter_gt_restack)
}
pub fn run_create(args: &[String], verbose: u8) -> Result<()> {
pub fn run_create(args: &[String], verbose: u8) -> Result<i32> {
run_gt_filtered(&["create"], args, verbose, "gt_create", filter_gt_create)
}
pub fn run_branch(args: &[String], verbose: u8) -> Result<()> {
pub fn run_branch(args: &[String], verbose: u8) -> Result<i32> {
run_gt_filtered(&["branch"], args, verbose, "gt_branch", filter_identity)
}
pub fn run_other(args: &[OsString], verbose: u8) -> Result<()> {
pub fn run_other(args: &[OsString], verbose: u8) -> Result<i32> {
if args.is_empty() {
anyhow::bail!("gt: no subcommand specified");
}
@@ -167,38 +167,10 @@ pub fn run_other(args: &[OsString], verbose: u8) -> Result<()> {
}
}
fn passthrough_gt(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("gt");
cmd.arg(subcommand);
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: gt {} {}", subcommand, args.join(" "));
}
let status = cmd
.status()
.with_context(|| format!("Failed to run gt {}", subcommand))?;
let args_str = if args.is_empty() {
subcommand.to_string()
} else {
format!("{} {}", subcommand, args.join(" "))
};
timer.track_passthrough(
&format!("gt {}", args_str),
&format!("rtk gt {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
fn passthrough_gt(subcommand: &str, args: &[String], verbose: u8) -> Result<i32> {
let mut os_args: Vec<OsString> = vec![OsString::from(subcommand)];
os_args.extend(args.iter().map(OsString::from));
crate::core::runner::run_passthrough("gt", &os_args, verbose)
}
const MAX_LOG_ENTRIES: usize = 15;
+1
View File
@@ -0,0 +1 @@
automod::dir!(pub "src/cmds/git");
+9
View File
@@ -0,0 +1,9 @@
# Go Ecosystem
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
## Specifics
- `go_cmd.rs` uses `GoCommands` sub-enum in main.rs (same pattern as git/cargo)
- `go test` outputs NDJSON (`-json` flag injected by RTK) -- parsed line-by-line as streaming events
- `golangci_cmd.rs` forces `--out-format=json` for structured parsing
+223 -129
View File
@@ -1,5 +1,9 @@
use crate::tracking;
use crate::utils::{resolved_command, truncate};
//! Filters Go command output — test results, build errors, vet warnings.
use crate::core::runner;
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, resolved_command, truncate};
use crate::golangci_cmd;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
@@ -36,13 +40,10 @@ struct PackageResult {
failed_tests: Vec<(String, Vec<String>)>, // (test_name, output_lines)
}
pub fn run_test(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run_test(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("test");
// Force JSON output if not already specified
if !args.iter().any(|a| a == "-json") {
cmd.arg("-json");
}
@@ -55,49 +56,16 @@ pub fn run_test(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: go test -json {}", args.join(" "));
}
let output = cmd
.output()
.context("Failed to run go test. Is Go installed?")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = output
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
let filtered = filter_go_test_json(&stdout);
if let Some(hint) = crate::tee::tee_and_hint(&raw, "go_test", exit_code) {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
}
// Include stderr if present (build errors, etc.)
if !stderr.trim().is_empty() {
eprintln!("{}", stderr.trim());
}
timer.track(
&format!("go test {}", args.join(" ")),
&format!("rtk go test {}", args.join(" ")),
&raw,
&filtered,
);
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(exit_code);
}
Ok(())
runner::run_filtered(
cmd,
"go test",
&args.join(" "),
filter_go_test_json,
crate::core::runner::RunOptions::stdout_only().tee("go_test"),
)
}
pub fn run_build(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run_build(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("build");
@@ -109,48 +77,16 @@ pub fn run_build(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: go build {}", args.join(" "));
}
let output = cmd
.output()
.context("Failed to run go build. Is Go installed?")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = output
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
let filtered = filter_go_build(&raw);
if let Some(hint) = crate::tee::tee_and_hint(&raw, "go_build", exit_code) {
if !filtered.is_empty() {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", hint);
}
} else if !filtered.is_empty() {
println!("{}", filtered);
}
timer.track(
&format!("go build {}", args.join(" ")),
&format!("rtk go build {}", args.join(" ")),
&raw,
&filtered,
);
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(exit_code);
}
Ok(())
runner::run_filtered(
cmd,
"go build",
&args.join(" "),
filter_go_build,
crate::core::runner::RunOptions::with_tee("go_build"),
)
}
pub fn run_vet(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run_vet(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = resolved_command("go");
cmd.arg("vet");
@@ -162,50 +98,27 @@ pub fn run_vet(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: go vet {}", args.join(" "));
}
let output = cmd
.output()
.context("Failed to run go vet. Is Go installed?")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = output
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
let filtered = filter_go_vet(&raw);
if let Some(hint) = crate::tee::tee_and_hint(&raw, "go_vet", exit_code) {
if !filtered.is_empty() {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", hint);
}
} else if !filtered.is_empty() {
println!("{}", filtered);
}
timer.track(
&format!("go vet {}", args.join(" ")),
&format!("rtk go vet {}", args.join(" ")),
&raw,
&filtered,
);
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(exit_code);
}
Ok(())
runner::run_filtered(
cmd,
"go vet",
&args.join(" "),
filter_go_vet,
crate::core::runner::RunOptions::with_tee("go_vet"),
)
}
pub fn run_other(args: &[OsString], verbose: u8) -> Result<()> {
pub fn run_other(args: &[OsString], verbose: u8) -> Result<i32> {
if args.is_empty() {
anyhow::bail!("go: no subcommand specified");
}
// Intercept: `go tool <known>` invocations for filtered output
if let Some((tool, tool_args)) = match_go_tool(args) {
match tool {
GoTool::GolangciLint => return run_go_tool_golangci_lint(tool_args, verbose),
}
}
let timer = tracking::TimedExecution::start();
let subcommand = args[0].to_string_lossy();
@@ -238,12 +151,137 @@ pub fn run_other(args: &[OsString], verbose: u8) -> Result<()> {
&raw, // No filtering for unsupported commands
);
// Preserve exit code
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
Ok(exit_code_from_output(&output, "go"))
}
/// Detect golangci-lint major version when invoked via `go tool`.
/// Returns 1 on any failure (safe fallback — v1 behaviour).
fn detect_go_tool_golangci_version() -> u32 {
let output = resolved_command("go")
.arg("tool")
.arg("golangci-lint")
.arg("--version")
.output();
match output {
Ok(o) => {
let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr);
let version_text = if stdout.trim().is_empty() {
&*stderr
} else {
&*stdout
};
golangci_cmd::parse_major_version(version_text)
}
Err(_) => 1,
}
}
fn has_golangci_format_flag(args: &[OsString]) -> bool {
args.iter().any(|a| {
let s = a.to_string_lossy();
s == "--out-format"
|| s.starts_with("--out-format=")
|| s == "--output.json.path"
|| s.starts_with("--output.json.path=")
})
}
/// Known `go tool` subcommands that RTK provides filtered output for.
#[derive(Debug, Clone, Copy, PartialEq)]
enum GoTool {
GolangciLint,
}
impl GoTool {
fn from_name(name: &str) -> Option<Self> {
match name {
"golangci-lint" => Some(Self::GolangciLint),
_ => None,
}
}
}
/// If the first arg is `tool` identify if it is a tool we already handle.
fn match_go_tool(args: &[OsString]) -> Option<(GoTool, &[OsString])> {
if args.first().map(|a| a == "tool").unwrap_or(false) {
if let Some(tool_arg) = args.get(1) {
if let Some(tool) = GoTool::from_name(&tool_arg.to_string_lossy()) {
return Some((tool, &args[2..]));
}
}
}
None
}
/// Run `go tool golangci-lint` and filter its output via the golangci JSON filter.
/// Reusing parts of golangci_cmd.
fn run_go_tool_golangci_lint(args: &[OsString], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let version = detect_go_tool_golangci_version();
let mut cmd = resolved_command("go");
cmd.arg("tool").arg("golangci-lint");
let has_format = has_golangci_format_flag(args);
if !has_format {
if version >= 2 {
cmd.arg("run").arg("--output.json.path").arg("stdout");
} else {
cmd.arg("run").arg("--out-format=json");
}
} else {
cmd.arg("run");
}
Ok(())
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
if version >= 2 {
eprintln!("Running: go tool golangci-lint run --output.json.path stdout");
} else {
eprintln!("Running: go tool golangci-lint run --out-format=json");
}
}
let output = cmd
.output()
.context("Failed to run go tool golangci-lint")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
// v2 outputs JSON on first line + trailing text; v1 outputs just JSON
let json_output = if version >= 2 {
stdout.lines().next().unwrap_or("")
} else {
&*stdout
};
let filtered = golangci_cmd::filter_golangci_json(json_output, version);
println!("{}", filtered);
if !stderr.trim().is_empty() && verbose > 0 {
eprintln!("{}", stderr.trim());
}
timer.track(
"go tool golangci-lint",
"rtk go tool golangci-lint",
&raw,
&filtered,
);
let exit_code = exit_code_from_output(&output, "go tool golangci-lint");
// golangci-lint: exit 0 = clean, exit 1 = lint issues found (not an error),
// exit 2+ = config/build error, None = killed by signal (OOM, SIGKILL)
Ok(if exit_code == 1 { 0 } else { exit_code })
}
/// Parse go test -json output (NDJSON format)
@@ -588,4 +626,60 @@ utils.go:15:5: unreachable code"#;
assert_eq!(compact_package_name("example.com/foo"), "foo");
assert_eq!(compact_package_name("simple"), "simple");
}
fn os(args: &[&str]) -> Vec<OsString> {
args.iter().map(OsString::from).collect()
}
#[test]
fn test_match_go_tool_golangci_lint() {
let args = os(&["tool", "golangci-lint", "run", "./..."]);
let (tool, rest) = match_go_tool(&args).expect("should match");
assert_eq!(tool, GoTool::GolangciLint);
assert_eq!(rest.len(), 2); // ["run", "./..."]
}
#[test]
fn test_match_go_tool_bare() {
let args = os(&["tool", "golangci-lint"]);
let (tool, rest) = match_go_tool(&args).expect("should match");
assert_eq!(tool, GoTool::GolangciLint);
assert!(rest.is_empty());
}
#[test]
fn test_match_go_tool_rejects_unknown() {
assert!(match_go_tool(&os(&["tool", "pprof"])).is_none());
assert!(match_go_tool(&os(&["tool"])).is_none());
assert!(match_go_tool(&os(&["test", "./..."])).is_none());
assert!(match_go_tool(&os(&[])).is_none());
}
#[test]
fn test_has_golangci_format_flag_v1() {
assert!(has_golangci_format_flag(&os(&["--out-format=json"])));
assert!(has_golangci_format_flag(&os(&[
"./...",
"--out-format",
"json"
])));
}
#[test]
fn test_has_golangci_format_flag_v2() {
assert!(has_golangci_format_flag(&os(&[
"--output.json.path",
"stdout"
])));
assert!(has_golangci_format_flag(&os(&[
"--output.json.path=stdout"
])));
}
#[test]
fn test_has_golangci_format_flag_absent() {
assert!(!has_golangci_format_flag(&os(&["run", "./..."])));
assert!(!has_golangci_format_flag(&os(&[])));
assert!(!has_golangci_format_flag(&os(&["--fix"])));
}
}
@@ -1,7 +1,9 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
//! Filters golangci-lint output, grouping issues by rule.
use crate::core::config;
use crate::core::runner;
use crate::core::utils::{resolved_command, truncate};
use anyhow::Result;
use serde::Deserialize;
use std::collections::HashMap;
@@ -44,7 +46,7 @@ struct GolangciOutput {
/// Parse major version number from `golangci-lint --version` output.
/// Returns 1 on any failure (safe fallback — v1 behaviour).
fn parse_major_version(version_output: &str) -> u32 {
pub(crate) fn parse_major_version(version_output: &str) -> u32 {
// Handles:
// "golangci-lint version 1.59.1"
// "golangci-lint has version 2.10.0 built with ..."
@@ -60,7 +62,7 @@ fn parse_major_version(version_output: &str) -> u32 {
/// Run `golangci-lint --version` and return the major version number.
/// Returns 1 on any failure.
fn detect_major_version() -> u32 {
pub(crate) fn detect_major_version() -> u32 {
let output = resolved_command("golangci-lint").arg("--version").output();
match output {
@@ -78,9 +80,7 @@ fn detect_major_version() -> u32 {
}
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let version = detect_major_version();
let mut cmd = resolved_command("golangci-lint");
@@ -115,53 +115,29 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
}
let output = cmd.output().context(
"Failed to run golangci-lint. Is it installed? Try: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest",
let exit_code = runner::run_filtered(
cmd,
"golangci-lint",
&args.join(" "),
|stdout| {
// v2 outputs JSON on first line + trailing text; v1 outputs just JSON
let json_output = if version >= 2 {
stdout.lines().next().unwrap_or("")
} else {
stdout
};
filter_golangci_json(json_output, version)
},
crate::core::runner::RunOptions::stdout_only(),
)?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
// v2 outputs JSON on first line + trailing text; v1 outputs just JSON
let json_output = if version >= 2 {
stdout.lines().next().unwrap_or("")
} else {
&*stdout
};
let filtered = filter_golangci_json(json_output, version);
println!("{}", filtered);
// Always forward stderr (config errors, missing linters, etc.)
if !stderr.trim().is_empty() {
eprintln!("{}", stderr.trim());
}
timer.track(
&format!("golangci-lint {}", args.join(" ")),
&format!("rtk golangci-lint {}", args.join(" ")),
&raw,
&filtered,
);
// golangci-lint: exit 0 = clean, exit 1 = lint issues, exit 2+ = config/build error
// None = killed by signal (OOM, SIGKILL) — always fatal
match output.status.code() {
Some(0) | Some(1) => Ok(()),
Some(code) => {
std::process::exit(code);
}
None => {
eprintln!("golangci-lint: killed by signal");
std::process::exit(130);
}
}
// golangci-lint: exit 0 = clean, exit 1 = lint issues found (not an error),
// exit 2+ = config/build error, None = killed by signal (OOM, SIGKILL)
Ok(if exit_code == 1 { 0 } else { exit_code })
}
/// Filter golangci-lint JSON output - group by linter and file
fn filter_golangci_json(output: &str, version: u32) -> String {
pub(crate) fn filter_golangci_json(output: &str, version: u32) -> String {
let result: Result<GolangciOutput, _> = serde_json::from_str(output);
let golangci_output = match result {
@@ -510,7 +486,7 @@ mod tests {
#[test]
fn test_golangci_v2_token_savings() {
let raw = include_str!("../tests/fixtures/golangci_v2_json.txt");
let raw = include_str!("../../../tests/fixtures/golangci_v2_json.txt");
let filtered = filter_golangci_json(raw, 2);
let savings = 100.0 - (count_tokens(&filtered) as f64 / count_tokens(raw) as f64 * 100.0);
+1
View File
@@ -0,0 +1 @@
automod::dir!(pub "src/cmds/go");
+15
View File
@@ -0,0 +1,15 @@
# JavaScript / TypeScript / Node
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
## Specifics
- `utils::package_manager_exec()` auto-detects pnpm/yarn/npm -- JS modules should use this instead of hardcoding a package manager
- `lint_cmd.rs` is a cross-ecosystem router: detects Python projects and delegates to `mypy_cmd` or `ruff_cmd`
- `vitest_cmd.rs` uses the `parser/` module for structured output parsing
- `playwright_cmd.rs` uses the `parser/` module for test result extraction
## Cross-command
- `lint_cmd` routes to `cmds/python/mypy_cmd` and `cmds/python/ruff_cmd` for Python projects
- `prettier_cmd` is also called by `cmds/system/format_cmd` as a format dispatcher target
+10 -8
View File
@@ -1,8 +1,10 @@
use crate::config;
//! Filters ESLint and Biome linter output, grouping violations by rule.
use crate::core::config;
use crate::core::tracking;
use crate::core::utils::{package_manager_exec, resolved_command, truncate};
use crate::mypy_cmd;
use crate::ruff_cmd;
use crate::tracking;
use crate::utils::{package_manager_exec, resolved_command, truncate};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -83,7 +85,7 @@ fn detect_linter(args: &[String]) -> (&str, bool) {
}
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let skip = strip_pm_prefix(args);
@@ -179,7 +181,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
stderr.lines().take(5).collect::<Vec<_>>().join("\n")
);
}
return Ok(());
return Ok(crate::core::utils::exit_code_from_output(&output, "eslint"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -206,7 +208,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
if let Some(hint) = crate::tee::tee_and_hint(&raw, "lint", exit_code) {
if let Some(hint) = crate::core::tee::tee_and_hint(&raw, "lint", exit_code) {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
@@ -220,10 +222,10 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
return Ok(crate::core::utils::exit_code_from_output(&output, "eslint"));
}
Ok(())
Ok(0)
}
/// Filter ESLint JSON output - group by rule and file
+1
View File
@@ -0,0 +1 @@
automod::dir!(pub "src/cmds/js");
+13 -25
View File
@@ -1,11 +1,11 @@
use crate::tracking;
use crate::utils::{resolved_command, strip_ansi, tool_exists, truncate};
use anyhow::{Context, Result};
//! Filters Next.js build output down to route metrics and bundle sizes.
use crate::core::runner;
use crate::core::utils::{resolved_command, strip_ansi, tool_exists, truncate};
use anyhow::Result;
use regex::Regex;
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
// Try next directly first, fallback to npx if not found
let next_exists = tool_exists("next");
@@ -28,25 +28,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: {} build", tool);
}
let output = cmd
.output()
.context("Failed to run next build (try: npm install -g next)")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let filtered = filter_next_build(&raw);
println!("{}", filtered);
timer.track("next build", "rtk next build", &raw, &filtered);
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
runner::run_filtered(
cmd,
"next build",
&args.join(" "),
|raw| filter_next_build(raw),
runner::RunOptions::default(),
)
}
/// Filter Next.js build output - extract routes, bundles, warnings
+13 -26
View File
@@ -1,6 +1,8 @@
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
//! Filters npm output and auto-injects the "run" subcommand when appropriate.
use crate::core::runner;
use crate::core::utils::resolved_command;
use anyhow::Result;
/// Known npm subcommands that should NOT get "run" injected.
/// Shared between production code and tests to avoid drift.
@@ -71,9 +73,7 @@ const NPM_SUBCOMMANDS: &[&str] = &[
"restart",
];
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<i32> {
let mut cmd = resolved_command("npm");
// Determine if this is "npm run <script>" or another npm subcommand (install, list, etc.)
@@ -109,26 +109,13 @@ pub fn run(args: &[String], verbose: u8, skip_env: bool) -> Result<()> {
eprintln!("Running: npm {}", args.join(" "));
}
let output = cmd.output().context("Failed to run npm")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let filtered = filter_npm_output(&raw);
println!("{}", filtered);
timer.track(
&format!("npm {}", args.join(" ")),
&format!("rtk npm {}", args.join(" ")),
&raw,
&filtered,
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
runner::run_filtered(
cmd,
"npm",
&args.join(" "),
|raw| filter_npm_output(raw),
runner::RunOptions::default(),
)
}
/// Filter npm run output - strip boilerplate, progress bars, npm WARN
@@ -1,5 +1,7 @@
use crate::tracking;
use crate::utils::{detect_package_manager, resolved_command, strip_ansi};
//! Filters Playwright E2E test output to show only failures.
use crate::core::tracking;
use crate::core::utils::{detect_package_manager, resolved_command, strip_ansi};
use anyhow::{Context, Result};
use regex::Regex;
use serde::Deserialize;
@@ -238,7 +240,7 @@ fn extract_failures_regex(output: &str) -> Vec<TestFailure> {
failures
}
pub fn run(args: &[String], verbose: u8) -> Result<()> {
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Skip `which playwright` — it can find pyenv shims or other non-Node
@@ -314,8 +316,8 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
}
};
let exit_code = output.status.code().unwrap_or(1);
if let Some(hint) = crate::tee::tee_and_hint(&raw, "playwright", exit_code) {
let exit_code = crate::core::utils::exit_code_from_output(&output, "playwright");
if let Some(hint) = crate::core::tee::tee_and_hint(&raw, "playwright", exit_code) {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
@@ -330,10 +332,10 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(exit_code);
return Ok(exit_code);
}
Ok(())
Ok(0)
}
#[cfg(test)]
+15 -33
View File
@@ -1,5 +1,7 @@
use crate::tracking;
use crate::utils::resolved_command;
//! Filters pnpm output — dependency trees, install logs, outdated packages.
use crate::core::tracking;
use crate::core::utils::resolved_command;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::collections::HashMap;
@@ -283,7 +285,7 @@ pub enum PnpmCommand {
Install { packages: Vec<String> },
}
pub fn run(cmd: PnpmCommand, args: &[String], verbose: u8) -> Result<()> {
pub fn run(cmd: PnpmCommand, args: &[String], verbose: u8) -> Result<i32> {
match cmd {
PnpmCommand::List { depth } => run_list(depth, args, verbose),
PnpmCommand::Outdated => run_outdated(args, verbose),
@@ -291,7 +293,7 @@ pub fn run(cmd: PnpmCommand, args: &[String], verbose: u8) -> Result<()> {
}
}
fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("pnpm");
@@ -308,7 +310,7 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(crate::core::utils::exit_code_from_output(&output, "pnpm"));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -345,10 +347,10 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
Ok(())
Ok(0)
}
fn run_outdated(args: &[String], verbose: u8) -> Result<()> {
fn run_outdated(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("pnpm");
@@ -396,10 +398,10 @@ fn run_outdated(args: &[String], verbose: u8) -> Result<()> {
timer.track("pnpm outdated", "rtk pnpm outdated", &combined, &filtered);
Ok(())
Ok(0)
}
fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()> {
fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Validate package names to prevent command injection
@@ -433,7 +435,7 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
if !output.status.success() {
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
return Ok(crate::core::utils::exit_code_from_output(&output, "pnpm"));
}
let combined = format!("{}{}", stdout, stderr);
@@ -448,7 +450,7 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
&filtered,
);
Ok(())
Ok(0)
}
/// Filter pnpm install output - remove progress bars, keep summary
@@ -490,28 +492,8 @@ fn filter_pnpm_install(output: &str) -> String {
}
}
/// Runs an unsupported pnpm subcommand by passing it through directly
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("pnpm passthrough: {:?}", args);
}
let status = resolved_command("pnpm")
.args(args)
.status()
.context("Failed to run pnpm")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("pnpm {}", args_str),
&format!("rtk pnpm {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
crate::core::runner::run_passthrough("pnpm", args, verbose)
}
#[cfg(test)]
@@ -1,13 +1,12 @@
use crate::tracking;
use crate::utils::package_manager_exec;
use anyhow::{Context, Result};
//! Filters Prettier output to show only files that need formatting.
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
use crate::core::runner::{self, RunOptions};
use crate::core::utils::package_manager_exec;
use anyhow::Result;
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = package_manager_exec("prettier");
// Add user arguments
for arg in args {
cmd.arg(arg);
}
@@ -16,50 +15,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: prettier {}", args.join(" "));
}
let output = cmd
.output()
.context("Failed to run prettier (try: npm install -g prettier)")?;
let stdout = String::from_utf8_lossy(&output.stdout);
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);
timer.track(
&format!("prettier {}", args.join(" ")),
&format!("rtk prettier {}", args.join(" ")),
&raw,
&filtered,
);
// Preserve exit code for CI/CD
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
runner::run_filtered(
cmd,
"prettier",
&args.join(" "),
filter_prettier_output,
RunOptions::stdout_only(),
)
}
/// Filter Prettier output - show only files that need formatting
+17 -15
View File
@@ -1,5 +1,7 @@
use crate::tracking;
use crate::utils::{resolved_command, tool_exists};
//! Filters Prisma CLI output by stripping ASCII art and verbose decoration.
use crate::core::tracking;
use crate::core::utils::{resolved_command, tool_exists};
use anyhow::{Context, Result};
use std::process::Command;
@@ -17,7 +19,7 @@ pub enum MigrateSubcommand {
Deploy,
}
pub fn run(cmd: PrismaCommand, args: &[String], verbose: u8) -> Result<()> {
pub fn run(cmd: PrismaCommand, args: &[String], verbose: u8) -> Result<i32> {
match cmd {
PrismaCommand::Generate => run_generate(args, verbose),
PrismaCommand::Migrate { subcommand } => run_migrate(subcommand, args, verbose),
@@ -36,7 +38,7 @@ fn create_prisma_command() -> Command {
}
}
fn run_generate(args: &[String], verbose: u8) -> Result<()> {
fn run_generate(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = create_prisma_command();
@@ -54,7 +56,7 @@ fn run_generate(args: &[String], verbose: u8) -> Result<()> {
.output()
.context("Failed to run prisma generate (try: npm install -g prisma)")?;
let exit_code = output.status.code().unwrap_or(1);
let exit_code = crate::core::utils::exit_code_from_output(&output, "prisma");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
@@ -67,17 +69,17 @@ fn run_generate(args: &[String], verbose: u8) -> Result<()> {
eprint!("{}", stderr);
}
timer.track("prisma generate", "rtk prisma generate", &raw, &raw);
std::process::exit(exit_code);
return Ok(exit_code);
}
let filtered = filter_prisma_generate(&raw);
println!("{}", filtered);
timer.track("prisma generate", "rtk prisma generate", &raw, &filtered);
Ok(())
Ok(0)
}
fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> Result<()> {
fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = create_prisma_command();
@@ -111,7 +113,7 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
let output = cmd.output().context("Failed to run prisma migrate")?;
let exit_code = output.status.code().unwrap_or(1);
let exit_code = crate::core::utils::exit_code_from_output(&output, "prisma");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
@@ -124,7 +126,7 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
eprint!("{}", stderr);
}
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &raw);
std::process::exit(exit_code);
return Ok(exit_code);
}
let filtered = match subcommand {
@@ -136,10 +138,10 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
println!("{}", filtered);
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &filtered);
Ok(())
Ok(0)
}
fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
fn run_db_push(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = create_prisma_command();
@@ -155,7 +157,7 @@ fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
let output = cmd.output().context("Failed to run prisma db push")?;
let exit_code = output.status.code().unwrap_or(1);
let exit_code = crate::core::utils::exit_code_from_output(&output, "prisma");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
@@ -168,14 +170,14 @@ fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
eprint!("{}", stderr);
}
timer.track("prisma db push", "rtk prisma db push", &raw, &raw);
std::process::exit(exit_code);
return Ok(exit_code);
}
let filtered = filter_db_push(&raw);
println!("{}", filtered);
timer.track("prisma db push", "rtk prisma db push", &raw, &filtered);
Ok(())
Ok(0)
}
/// Filter prisma generate output - strip ASCII art, extract counts
+13 -31
View File
@@ -1,12 +1,12 @@
use crate::tracking;
use crate::utils::{resolved_command, tool_exists, truncate};
use anyhow::{Context, Result};
//! Filters TypeScript compiler errors, grouping them by file and error code.
use crate::core::runner;
use crate::core::utils::{resolved_command, tool_exists, truncate};
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
// Try tsc directly first, fallback to npx if not found
let tsc_exists = tool_exists("tsc");
@@ -27,31 +27,13 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
eprintln!("Running: {} {}", tool, args.join(" "));
}
let output = cmd
.output()
.context("Failed to run tsc (try: npm install -g typescript)")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let filtered = filter_tsc_output(&raw);
let exit_code = output.status.code().unwrap_or(1);
if let Some(hint) = crate::tee::tee_and_hint(&raw, "tsc", exit_code) {
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
}
timer.track(
&format!("tsc {}", args.join(" ")),
&format!("rtk tsc {}", args.join(" ")),
&raw,
&filtered,
);
// Preserve tsc exit code for CI/CD compatibility
std::process::exit(exit_code);
runner::run_filtered(
cmd,
"tsc",
&args.join(" "),
|raw| filter_tsc_output(raw),
runner::RunOptions::with_tee("tsc"),
)
}
/// Filter TypeScript compiler output - group errors by file, show every error
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more